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?

Recommended Answers

All 5 Replies

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.

is there any other way of doing this question?

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.

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

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.

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.