
Java Program To Break Integer into Digits
In this Java Program, we break Integers into Digits
Here we use Scanner class to get input from the user. First While loop is use to count the digits in the input number and second while loop is use to extract the digits from the input number using modulus operator.
Step 1 : Import Scanner Class
Step 2 : Create a Class IntegerToDigit
Step 3 : Create main method
Step 4 : Initialize num, temp, digit and count and store 0 in count
Step 5 : Ask the user to enter any number
Step 6 : Store the user entered number into num variable
Step 7 : Close the Scanner class to avoid memory leaks
Step 8 : Create a copy of input number
Step 9 : Store the num into temp
Step 10 : Count the digits into the input number
Step 11 : Apply While loop where num is greater than zero
Step 12 : Divide num by 10 and store the result into num variable
Step 13 : Increment count by one.
Step 14 : Apply another while loop where temp is greater than zero and store the result of temp % 0 into digit.
Step 15 : Print the Digit
Step 16 : Divide temp by 10 and store the result into temp variable
Step 17 : Decrement count by one.
Program :
import java.util.Scanner;
public class IntegerToDigit {
public static void main(String[]args)
{
int num, temp, digit, count = 0;
//getting the number from user
Scanner sc = new Scanner(System.in);
System.out.print("Enter any number:");
num = sc.nextInt();
sc.close();
//creating a copy of the input number
temp = num;
//counting digits int the input number
while(num > 0)
{
num = num / 10;
count++;
}
while(temp > 0)
{
digit = temp % 10;
System.out.println("Digit at place "+count+" is:"+digit);
temp = temp / 10;
count --;
}
}
}
Output :
Enter any number:7891
Digit at place 4 is:1
Digit at place 3 is:9
Digit at place 2 is:8
Digit at place 1 is:7
For execution of the same do visit my YouTube Channel :
https://youtu.be/yYfE4xFPj4s