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?
27 Answers
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.
Because you don't reset it in each iteration of the outer loop. If you want the inner loop to run ten times too, put the initialization of the j variable inside the outer loop, like this:
int i = 0; while (i < 10) { printf("i:%d\n", i); int j = 0; while (j < 10) { printf("j:%d\n", j); j++; } i++; } You need to re-set the value j to 0 after the inner loop is done.
You need to reset j to 0. You don't ever do that in your code Make j equal to 0 in your outside loop.
j needs to be initialized to 0 inside the loop.
#include <stdio.h> int main(){ int i = 0; int j = 0; while(i < 10){ printf("i:%d\n", i); j = 0 ; // initialization while(j < 10){ printf("j:%d\n", j); j++; } i++; } } 1The reason your inner loop only executes once is because you initialize j to 0 outside the loop and then never reset it again. After it runs the first time the value of j is 10. It will never be less than 10 again.
A better way to do this is to use a for loop:
for (int i = 0; i < 10; i++){ printf("i:%i\n", i); for (int j = 0; j < 10; j++){ printf("j:%i\n", j); } } It also makes the code look cleaner.
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.