Java Program to split integer number into digits

Here we are explaining how to write a java program to split the integer number into digits.

How to split a number into digits?

We can split a number into digits by using the mod operator. Suppose if n=523 then n % 10 returns 3.So by using a while loop we can split a number into digits by using mod by 10.

How to implement the java program to split a number into digits?

First, we have to declare the class Digit.Declare the integer variables n,t,d,c.Read the number from the user into the variable n. Hold the variable into a temporary variable t as t=n.Then by using a while loop check n > 0,if true then calculate n=n/10,increment c by one.By using another while loop check t > 0, then calculate d= t % 10, Now d contains the last digit of the number. Display it using the System.out.println method. Then divide t/10 and keep it into t. Decrement c by one and repeat the step until t becomes 0.

ALGORITHM

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 n,t,d,c as an integer. Set c=0.

STEP 4: Read the first number into the variable n.

STEP 5: Set t=n.

STEP 6: By using while loop check n > 0 do step 7.

STEP 7: n=n/10,increment c by one.

STEP 8: By using another while loop check t > 0 and do step 9.

STEP 9: d= t % 10,display the digit at place c is d.

STEP 10: n=n/10,incremnet c by one.

STEP 11: By using another while loop check t > 0 and do step 9.

STEP 12: d=t % 10,display the digit at place c is d.

STEP 13: Calculate  t=t/10.

STEP 14: Decrement c by one and repeat step 12.

Java Source Code

                                          import java.util.Scanner;
public class Digit{
    public static void main(String args[]){
        int n, t, d,c=0;
     
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number:");
        n = sc.nextInt();
        sc.close();
        t = n;
    
        while(n> 0)
        {
            n= n/10;
            c++;
        }
        while(t> 0)
        {
            d = t%10;
            System.out.println("The Digit at place "+c+" is: "+d);
            t = t/10;
            c--;
        }
    }
}
                                      

OUTPUT

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