While practising nested loops in C, I wanted to understand how control flows between an outer loop and an inner loop. I understood that the inner loop runs for each iteration of the outer loop, but the order of execution still confuses me.
Example code:
#include <stdio.h>
int main(void)
{
for (int i = 0; i < 2; i++) { /* outer loop: i = 0..1 */
for (int j = 0; j < 3; j++) { /* inner loop: j = 0..2 */
printf("i = %d, j = %d\n", i, j);
}
}
return 0;
}
Output produced:
i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 1, j = 0
i = 1, j = 1
i = 1, j = 2
I initially thought i would increment once every time j increments, but it appears that the inner loop runs completely for each value of i. Why does the inner loop execute all its iterations before i increments? How should I think about the execution path in nested loops in C? Does this behaviour differ in other programming languages?
I have traced the values of i and j using printf statements and also stepped through the code with a debugger. I still find the order counter‑intuitive and would appreciate a deeper explanation or any visualisation techniques to understand it better.
I understood that the inner loop runs for each iteration of the outer loopandinner loop runs completely for each value of i, what exactly you understood?j++reads "incrementj". It does not read "incrementjand also at the same time incrementiand oh I don't know what else, look it up, maybe there's another loop out there". Why would one find the first reading counter-intuitive and the second one not? I'm all confused.