This program takes a number from the user and then using loop, modulo and division operator split the number into digits.
as:

import java.util.Scanner;

class Split_num
{
    public static void main ( String [] args)
        {
            Scanner a = new Scanner (System.in); 

            int num, n, r;

            System.out.print ("Enter a number: ");
            num = a. nextInt ();

            n = num;


            while ( n != 0)
            {
                r = n % 10;

                System.out.print (r);

                n = n/10;
            }


        }


}

But this program prints the splited integers in revers order. I have searched alot in books and on the internet to print the integers in forward order but all in vain. so question is:

what we will do in order to print the integers splited from a number in Forward Oreder?

What we

Dani AI

Generated

A short, practical fix and some caveats.

The reason ’s loop prints digits reversed is that taking n % 10 gives the least‑significant digit first. You can either extract the most‑significant digit first (compute a divisor) or collect digits as you extract them and then output them in reverse. Several good alternatives were suggested above (the divisor idea from , recursion from , and string/StringBuilder approaches mentioned by and ). Below is a simple, robust approach that collects digits and then prints them in forward order using a Deque.

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;

class PrintDigitsForward {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int input = sc.nextInt();
        if (input == 0) { System.out.println("0"); return; }

        boolean negative = input < 0;
        long n = input;            // widen before negation to handle MIN_VALUE safely
        if (negative) n = -nL;

        Deque<Integer> stack = new ArrayDeque<>();
        while (n != 0) {
            stack.push((int)(n % 10)); // collect digits (LSB first)
            n /= 10;
        }

        if (negative) System.out.print("-");
        while (!stack.isEmpty()) System.out.print(stack.pop());
        System.out.println();
    }
}

Notes and troubleshooting

  • Handle 0 explicitly; a while (n != 0) loop prints nothing for zero.
  • Widen to long before negating to avoid overflow on Integer.MIN_VALUE.
  • Avoid Math.pow for integer divisors (floating rounding can bite); compute powers by integer multiplication if you need the divisor approach.
  • If the original input may contain leading zeros (e.g., "00123"), read it as a String and iterate characters instead of parsing to an int.
  • Time/space: this Deque method is O(digits) time and O(digits) extra memory; the divisor method is O(digits) time with O(1) extra memory but requires careful integer math.

This gives a clear, safe implementation you can drop into a program and adapt (or choose the divisor/recursion/string route depending on constraints).

Recommended Answers

All 6 Replies

first off, i don't do java programing ,so i can't provide the solution with java syntax but i try to put the logic behind this :

first calculate the length-1 of the number[for ex:- number=1234 then length-1=3(4-1)(i hope you can do this)]

use power fuction :
a=pow(10,3) //3 is length-1

now use this: //

while(a!=0)
{
b=number/a;
b=number%10;
System.out.print (b);
a=a/10;
}

hope you understand the concept . . .

Member Avatar for Member #789783

If you partition a number into its figures recursively, the figures appear in their natural order because they are popped from stack when printed out, for example:

/**
Output figures of a number in their natural order

*/
class FiguresOfNumbers {

  public static void figures(long n){
    long d = n % 10; n = n / 10;
    if ( n > 0) figures (n);
    System.out.print( d + " ");
  }
  public static void main(String args[]) {
    FiguresOfNumbers.figures (1234567890);
  }

}
/***
javac FiguresOfNumbers.java
java FiguresOfNumbers
1 2 3 4 5 6 7 8 9 0
***/

use power fuction
now use this

A little overcomplicated; twice as many divisions. Your original loop is a more traditional way to get digits, I think.

partition a number into its figures recursively

A good illustration of recursion and how it uses the call stack, but I wouldn't accept this in "real" code.

this program prints the splited integers in revers order

My suggestion: Don't print the digits immediately. Instead, use a StringBuilder to collect the digits as you determine what they are. Two ways you can get the right order:

  1. Append the digits, then reverse the StringBuilder afterward.
  2. Insert the characters at the beginning of the StringBuilder (index 0).

Either way, then call the StringBuilder's toString method to get something you can print.

Just turn the number into a String, pump that into a StringBuilder, and call reverse() on it.

Just turn the number into a String, pump that into a StringBuilder, and call reverse() on it.

Why the round trip? Seems more efficient to just use the StringBuilder to build it in the first place.

I'm an oldfashioned guy, from way before there was a StringBuilder :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.