user3733225
user3733225

Reputation: 9

Inner and outer loop in C

int a = 0, b = 0, c;

while ( a < 10){
    while (b < 10){
        c = a * b;
        b++;
    }
    a++;
}

Variable b is being incremented but a isn't. A stays 0 and doesn't change until the last line where it magically turns to 10 even though C is 0 throughout the loops. Am I missing something? Sorry I am a beginner.

Upvotes: 0

Views: 2230

Answers (4)

Arun Gupta
Arun Gupta

Reputation: 808

Please run the code and you will get it. Problem is that once second while loop start, b'a values becomes b=10. So when Outer Loop runs for a =1(second time), at that time b=10 so inner loops condition get fails.

#include <stdio.h>


void main()
{
int a = 0, b = 0, c;

while ( a < 10){
printf("out:  a : %d\tb: %d\tc: %d\n", a,b,c);  
    while (b < 10){
    printf("in:  a : %d\tb: %d\tc: %d\n", a,b,c);       
        c = a * b;
        b++;
    }
    a++;
}
printf("a : %d\tb: %d\tc: %d\n", a,b,c);
}

You need to reinitialize the b's value every time when it goes to inner loop

Upvotes: 1

dede9714
dede9714

Reputation: 73

what I would suggest you do is in the first while loop. print all your variables. and do the same in the outer loop to confirm your values.

int a = 0, b = 0, c;

while ( a < 10){
    while (b < 10){
        c = a * b;
        b++;
        printf("Inner Loop :\n");
        printf("value of a :%d; value of b :%d;value of c :%d\n",a,b,c);
    }
    a++;
    printf("OuterLoop :\n");
    printf("value of a :%d; value of b :%d;value of c :%d\n",a,b,c);
}

Upvotes: 0

Devolus
Devolus

Reputation: 22104

You are not reinitliazing b before you enter the loop. It should be:

int a = 0, b = 0, c;
while ( a < 10)
{
    b = 0;
    while (b < 10)
    {
        c = a * b;
        b++;
    }
    a++;
}

If you don't then the inner loop will only be entered once, because for each iteration of a, b is no longer < 10.

Upvotes: 4

NTj
NTj

Reputation: 385

When a first a++, b already became 10. The inner looper will never enter again. I guess you print both variable in the inner loop. So you see a stay 0, and pop to 10 after 2while loop.

Upvotes: 2

Related Questions