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.
There’s nothing wrong about the loop’s behavior.
Now think a little bit more about your code.
What you want is your second
whileloop 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 firstwhileloop, magically? You might want to try doing it yourself, don’t you?