Can someone tell me why the following snippets have different outputs?
Yes, they are not equivalent. To make the two snippets of code equivalent, you need to initialize i = 0
and especially j = 0
inside the while loop like so:
i = 0;
while (i < 3) {
j = 0;
while(j < 3) {
printf("(%d %d)", i, j);
j++;
}
i++;
}
Remember that
for(init-statement condition; expression) {
statement
}
is translated to
init-statement
while(condition) {
statement
expression
}
In particular,
for(j = 0; j < 3; j++)
printf("(%d %d)", i, j);
is translated to
j = 0;
while(j < 3) {
printf("(%d %d)", i, j);
j++;
}
As such, you are missing the very key j = 0
initialization before entering the inner while
loop as well as the i = 0
initialization before entering the outer while
loop.
So to wrap it all up, the translation of
for(i = 0; i < 3; i++) {
for(j = 0; j < 3 ; j++)
printf("(%d %d)", i, j);
}
is (first pass)
i = 0;
while(i < 3) {
for(j = 0; j < 3; j++)
printf("(%d %d)", i, j);
i++;
}
and finally
i = 0;
while(i < 3) {
j = 0;
while(j < 3) {
printf("(%d %d)", i, j);
j++;
}
i++;
}