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

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 . . .

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.

Edited 3 Years Ago by gusano79

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.

This article has been dead for over six months. Start a new discussion instead.