0

i have to create a DigitsDisplay application that prompts the user for a non negative integer and then displays each digit on a separate line like such
"Enter a positive integer: 789
7
8
9
so far i have

  int num;
       c.print ("Enter a postive number: ");
        num = c.readInt ();
        while (num > 0)
        {
            c.println (num % 10);
            num = num / 10;


    }

the output i get is the reversed of what is asked, so I get:
9
8
7
instead of:
7
8
9
so i was wondering if anyone could take a look at my program to see what i did wrong?

Edited by ELMX27

3
Contributors
5
Replies
275
Views
4 Years
Discussion Span
Last Post by stultuske
0

You really didn't do anything wrong, except that you need to reverse the numbers. So, place the extracted digits in an array or vector, and reverse the order on output.

0

Not easily. It is what I would do. IE:

 int num;
 int numdigits = 0;
 int digitarray[10]; // This is assuming that you will not get more than 10 digits.
 c.print ("Enter a postive number: ");
 num = c.readInt ();
 // Accumulate digits into array.
 while (num > 0)
 {
     digitarray[numdigits++] = (num % 10);
     num = num / 10;
 }
 // Print digits in proper order.
 for (int i = numdigits; i > 0; i--)
 {
     c.println(digitarray[i-1]);
 }

So, as you can see, the change in your code is not extensive.

0

i see thank you very much for your help, I really appreciate it.

0

or you can convert the number into a String (which can be transformed in a char array) and then just loop over that chararray to print each element.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.