Home > Software engineering >  can use while loop within for loop?
can use while loop within for loop?

Time:11-26

#include<stdio.h>
#include<stdlib.h>

int input, x, c=0;
for (input=1; input<=100; input  )
{
    while(input != 0)
    {
        x = input%10;
        c = c*10   x;
        input = input/10;
    }
    printf("Reverse Number is : %d", c);
 }

This is the reverse number code, but this code printing minus value. Why this code printing minus values?

CodePudding user response:

Yes, you absolutely can use while loops inside for loops. Though, you should be careful while doing so. I noticed a few issues with your code.

First of all, your template isn't correct, so it's weird it even compiles, so let me quickly fix that for you

#include <stdio.h>
#include <stdlib.h>

int main(void) 
{
    int input, x, c = 0;
    for (input = 1; input <= 100; input  )
    {
        while(input != 0)
        {
            x = input % 10;
            c = c * 10   x;
            input = input / 10;
        }
        printf("Reverse Number is : %d\n", c);
    }
    
    return 0;
}

Now let's look at what happens to the input variable in the for loop:

  1. input = 1
  2. while(input != 0) makes so when the while loop ends, input == 0
  3. The for loop starts again, input == 1.

So, as result, the for loop became an infinite loop, where the input variable is always equal to 1. To fix that, we need to introduce a temporary variable in the loop, so input holds its value till the next iteration. Let's do that.

    for (input = 1; input <= 100; input  )
    {
        int temp = input;
        while(temp != 0)
        {
            x = temp % 10;
            c = c * 10   x;
            temp = temp / 10;
        }
        printf("Reverse Number is : %d\n", c);
    }

The next issue is that there's no place where you reset the value of c. Therefore it only gets larger and eventually overflows. To fix that we need to reset the value of c before the while loop starts.

    for (input = 1; input <= 100; input  )
    {
        int temp = input;
        c = 0;
        while(temp != 0)
        {
            x = temp % 10;
            c = c * 10   x;
            temp = temp / 10;
        }
        printf("Reverse Number is : %d\n", c);
    }

And, that's it!

The result will look like this:

#include <stdio.h>
#include <stdlib.h>

int main(void) 
{
    int input, x, c = 0;
    for (input = 1; input <= 100; input  )
    {
        int temp = input;
        c = 0;
        while(temp != 0)
        {
            x = temp % 10;
            c = c * 10   x;
            temp = temp / 10;
        }
        printf("Reverse Number is : %d\n", c);
    }
    
    return 0;
}
  •  Tags:  
  • c
  • Related