rwhile-loop

Nested while loop behavior in R


I am puzzled by why the output is not what I expect it to be in the following nested while loops:

i = 1
j = 1
while(i<5){
 print("i")
 print(i)
 i = i + 1
 while(j<5){
  print("j")
  print(j)
  j = j + 1
 }
}

The output I get is:

[1] "i"
[1] 1
[1] "j"
[1] 1
[1] "j"
[1] 2
[1] "j"
[1] 3
[1] "j"
[1] 4
[1] "i"
[1] 2
[1] "i"
[1] 3
[1] "i"
[1] 4

But I was expecting something along the lines of

[1] "i"
[1] 1
[1] "j"
[1] 1
[1] "j"
[1] 2
[1] "j"
[1] 3
[1] "j"
[1] 4
[1] "i"
[1] 2
[1] "j"
[1] 1
[1] "j"
[1] 2
[1] "j"
[1] 3
[1] "j"
[1] 4
...

Any suggestions? Thank you for your help.


Solution

  • There's nothing wrong about the loop's behavior.

    i = 1 // Beginning of your code, you're initializing i, changing its value to 1
    j = 1 // ... initializing j as well.
    while(i<5){   // looping while i < 5
     print("i")
     print(i)
     i = i + 1    // incrementing i
     while(j<5){  // looping while j is < 5
      print("j")
      print(j)
      j = j + 1   // incrementing j
     }
    }
    

    Now think a little bit more about your code.

    What you want is your second while loop to actually loop 4 times for each loop of the first one.

    So you're expecting j's value to be set back to 1 inside the scope of the first while loop, magically? You might want to try doing it yourself, don't you?