Write a Java program to break an integer or number into digits using a while loop. In this example, the first while loop will count the total digits in a number. And the second while loop will iterate the Integer and print each digit as an output.
package RemainingSimplePrograms;
import java.util.Scanner;
public class DigitsinNumber1 {
private static Scanner sc;
public static void main(String[] args) {
int num, reminder, temp, count = 0;
sc = new Scanner(System.in);
System.out.print("Please Enter Any Number = ");
num = sc.nextInt();
temp = num;
while(temp > 0)
{
temp = temp / 10;
count++;
}
while(num > 0)
{
reminder = num % 10;
System.out.println("Digit at Position " + count + " = " + reminder);
num = num / 10;
count--;
}
}
}
Please Enter Any Number = 98453217
Digit at Position 8 = 7
Digit at Position 7 = 1
Digit at Position 6 = 2
Digit at Position 5 = 3
Digit at Position 4 = 5
Digit at Position 3 = 4
Digit at Position 2 = 8
Digit at Position 1 = 9
This Program will Break Integer into Digits using for loop.
package RemainingSimplePrograms;
import java.util.Scanner;
public class DigitsinNumber2 {
private static Scanner sc;
public static void main(String[] args) {
int num, reminder, temp, count = 0;
sc = new Scanner(System.in);
System.out.print("Please Enter Any Number = ");
num = sc.nextInt();
for(temp = num; temp > 0; count++)
{
temp = temp / 10;
}
for(;num > 0; num = num / 10)
{
reminder = num % 10;
System.out.println("Digit at Position " + count + " = " + reminder);
count--;
}
}
}
