I have been trying out some basic exercises involving loops.
Can someone tell me why the following snippets have different outputs?
While Loop
while (i<3)
{
while(j<3)
{
printf("(%d %d) ",i,j);
j++;
}
i++;
}
Output
(0 0) (0 1) (0 2)
For Loop
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("(%d %d) ",i,j);
}
Output
(0 0) (0 1) (0 2) (1 0) (1 1) (1 2) (2 0) (2 1) (2 2)
Aren’t they supposed to have the same output?
Yes, they are not equivalent. To make the two snippets of code equivalent, you need to initialize
i = 0and especiallyj = 0inside the while loop like so:Remember that
is translated to
In particular,
is translated to
As such, you are missing the very key
j = 0initialization before entering the innerwhileloop as well as thei = 0initialization before entering the outerwhileloop.So to wrap it all up, the translation of
is (first pass)
and finally