[Solved] for loop – why does this print 12 and not 3?


The values of your variables throughout the loops are like follows:

x y result
----------
0 0 1
0 1 2
0 2 3
1 0 4
1 1 5
1 2 6
2 0 7
2 1 8
2 2 9
3 0 10 
3 1 11
3 2 12

So that’s why result ends up being 12.

To get 3 you should increment result just with the first loop and from 1 to 3 (0 <= x < 3 or 1 <= x <= 3):

#include <stdio.h>

int main()
{
  int result = 0, x, y;
  for (x = 0; x < 3; x++) {
      result++;
  }
  printf("%d", result);
  return 0;
}

2

solved for loop – why does this print 12 and not 3?