Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while loop nested in a while loop

Tags:

c

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?

like image 244
Yananas Avatar asked Nov 30 '25 11:11

Yananas


2 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.

like image 88
FatalError Avatar answered Dec 02 '25 23:12

FatalError


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++;
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!