We can break a number into digits by using the mod operator. Suppose if num=523 then num % 10 returns 3. So by using a while loop
we can break a number into digits by using mod by 10 and then dividing the number by 10 to remove the last digit after taking that digit.
To solve this java program, we have to declare the class Digit. Declare the integer variables num, tmp, dgt, count. Read the number from the user into the variable num. Hold the variable into a temporary variable tmp as tmp=num. Then by using a while loop
check num > 0, if true then calculate num=num/10, increment count by one; here we will get the count of digits of the user input number.
By using another while loop
check tmp > 0, then calculate dgt= tmp % 10, Now dgt contains the last digit of the number. Display it using the System.out.println
method. Then divide tmp/10 for the rest of the digits and keep it into tmp. Decrement count by one and repeat these steps until tmp becomes 0.
STEP 1: Declare the class Digit with a public modifier.
STEP 2: Open the main() to start the program, Java program execution starts with the main()
STEP 3: Declare the integer variables num, tmp, dgt, count as an integer. Set count=0.
STEP 4: Read the number into the variable num.
STEP 5: Save the num to tmp.
STEP 6: By using while loop
check num > 0 do step 7. Here we get how many digits are there in the inserted number.
STEP 7: num=num/10,increment count by one.
STEP 8: By using another while loop
check tmp > 0 and do steps 9 to 11.
STEP 9: dgt= tmp % 10,display the digit at place count is dgt.
STEP 10: Calculate tmp=tmp/10.
STEP 11: Decrement count by one.
import java.util.Scanner;
public class Digit{
public static void main(String args[]){
int num, tmp, dgt,count=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number:");
num = sc.nextInt();
sc.close();
tmp = num;
while(num> 0)
{
num= num/10;
count++;
}
while(tmp> 0)
{
dgt=tmp % 10;
System.out.println("The Digit at place "+count+" is: "+dgt);
tmp = tmp/10;
count--;
}
}
}
Enter the number:500 The Digit at the place of 3 is: 0 The Digit at the place of 2 is: 0 The Digit at the place of 1 is: 5