Javatpoint Logo
Javatpoint Logo

Java Program to Break Integer into Digits

In Java, to break the number into digits, we must have an understanding of Java while loop, modulo, and division operator. The modulo operator in Java determines the remainder while the division operator gives the quotient as a result.

In this section, we have created Java programs to break an integer into digits by using different logics.

For example, if we have entered the number 98765 then the program should give the following output:

Java Program to Break Integer into Digits

In the following example, we have created an object of the Scanner class that reads an integer from the user. The point to notice that we have used two while loops. The first while loop determines the position of the digits. The second while loop breaks the number into digits using the modulo operator.

BreakIntegerExample1.java

Output:

Enter any number: 988754
Digit at place 6 is: 4
Digit at place 5 is: 5
Digit at place 4 is: 7
Digit at place 3 is: 8
Digit at place 2 is: 8
Digit at place 1 is: 9

Let's see another logic to break an integer into digits.

In the following example, we have read an integer (six-digit) from the user. After that, we have divided the number by 100000%10 it determines the first digit of the number. Similarly, to get the second digit of the number, we have divided the number by 10000%10, and so on.

BreakIntegerExample2.java

Output:

Enter a six-digit number: 912750
9,1,2,7,5,0

Let's understand another logic.

In the following example, we have initialized an integer. In the while loop, we have tested the condition number>0 if the condition is true the loop executes the following two statements and prints the digits:

Let's implement the above logic in the example for better understanding.

Suppose, we want to break the number=1234.

Iteration 1:

while(1234>0)  //condition true
digits=1234%10 = 4 (remainder)
number=1234/10 = 123

Iteration 2:

while(123>0)  //condition true
digits=123%10 = 3 (remainder)
number=123/10 = 12

Iteration 3:

while(12>0)  //condition true
digits=12%10 = 2 (remainder)
number=12/10 = 1

Iteration 4:

while(1>0)  //condition true
digits=1%10 = 1 (remainder)
number=1/10 = 0

In the next iteration, the condition become false and the loop exits.

Let's implement the above logic in a Java program.

BreakIntegerExample3.java

Output:

4 5 7 8 9 3 1

Let's understand another logic.

BreakIntegerExample4.java

Output:

Enter any number: 5623098
5
6
2
3
0
9
8

Next TopicJava Programs





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA