Yananas Yananas - 1 year ago 78
C Question

while loop nested in a while loop

I was using a nested while loop, and ran into a problem, as the inner loop is only run once.
To demonstrate I've made a bit of test code.

#include <stdio.h>
int main(){
int i = 0;
int j = 0;
while(i < 10){
printf("i:%d\n", i);
while(j < 10){
printf("j:%d\n", j);
j++;
}
i++;
}
}


This returns:

i:0
j:0
j:1
j:2
j:3
j:4
j:5
j:6
j:7
j:8
j:9
i:1
i:2
i:3
i:4
i:5
i:6
i:7
i:8
i:9


Can anyone explain why the nested loop doesn't execute 10 times? And what can I do to fix it?

Answer Source

You never reset the value of j to 0, and as such, your inner loop condition is never true after the first run. Assigning j = 0; in the outer loop afterward should fix it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download