how do u convert the below to a 'for' loop?

int x = 123456;
    int y =0;

    while (x > 0) {
        y *= 10;
        y += x % 10;
        x /= 10;}

Recommended Answers

All 8 Replies

You try it first and post your best shot. You should know that a for loop is coded sometime similar to this: for(int i = 0; i < 5; i++). All you have to do is substitute the variables in what I just posted with what you posted.

First you understand how a for loop works.
Then understand all the pieces of the for loop expression.
Next, look at the posted code and figure out which of those pieces are there.
Put those pieces into the for loop syntax

well i tried

 for( x = 12; x > 0; x=x/10)
   {
      y *=10;
      y +=x%10;
   }

doesnt work

 for( x =y; x > 0; x=x/10)
   {
      y *=10;
      y +=x%10;
   }

doesnt work.
I dont understand this.I have done other example.The code is suppose to convert 123456 to 654321 but i dont understand why i need y=y*10 and y+x %10.What is the modulus doing here???.These complications are preventing me from otherwise doing a straight-forward 'for' loop.

but i dont understand why i need y=y*10 and y+x %10

if you'd want to convert it you need to understand how the code works using the while loop first
My advice would be to trace the code by printing out the value of x and y in the loop after every operation or do it manually using a pen and paper

lastly take note of the initialization of variable y and x before the while loop,that should help you in the initializing content of the for loop

Also, what's the magic number 12 for? And what does x=x/10 do? Why is it in your FOR statement?

It makes no sense to implement this as a 'for' loop, because the number of loops will vary depending on the integer you wish to reverse.

This will work, but it really seems pointless:

    int x = 123456;
    int y = 0;

    for (int j = 0; ; j++ > 0 ) 
    {
        y *= 10;
        y += x % 10;
        x /= 10;

        if  (x <= 0)
        {
            break;
        }
    }

If this is an assignment task of some sort, then consider the following.

  1. int x = 123456;
  2. In each while loop you have x /= 10;
  3. What is the value of x after the first loop?
  4. How many times do you need to loop until while (x > 0) is false?
  5. If you've followed that, then you'll see the correlation between the number of digits in x and the number of loops needed.

Butin the FOR loop you don't care how many loops it takes. Just wait for x to become 0.

As I said, find the pieces of the WHILE loop code that correlate with the pieces of the FOR loop and plug them in.

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.