If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To find the last digit of a number, you can use the modulo operator %
in Java. The modulo operator returns the remainder when one number is divided by another. In this case, we'll use it to find the remainder when the given number is divided by 10, which gives us the last digit.
Here's a Java program to find the last digit of a given number:
javaCopy code
import java.util.Scanner;
public class LastDigitOfNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Find the last digit
int lastDigit = number % 10;
System.out.println("The last digit of " + number + " is: " + lastDigit);
scanner.close();
}
}
Example output:
yamlCopy code
Enter a number: 3568
The last digit of 3568 is: 8
In the program above, we take the user input, store it in the variable number
, and then find the last digit using the expression number % 10
. The result is stored in the variable lastDigit
, which is then printed to the console. The % 10
operation effectively gives us the remainder when number
is divided by 10, which corresponds to the last digit of the number.
Comments: 0