Yananas
Yananas

Reputation: 125

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?

Upvotes: 2

Views: 59830

Answers (7)

user2387778
user2387778

Reputation: 11

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

Upvotes: 1

jjrjrjrj
jjrjrjrj

Reputation: 1

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.

Upvotes: 0

DhruvPathak
DhruvPathak

Reputation: 43265

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

Upvotes: 1

C0L.PAN1C
C0L.PAN1C

Reputation: 12243

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.

Upvotes: 1

user529758
user529758

Reputation:

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

Upvotes: 4

alk
alk

Reputation: 70979

You need to re-set the value j to 0 after the inner loop is done.

Upvotes: 1

FatalError
FatalError

Reputation: 54631

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.

Upvotes: 12

Related Questions