Why is the output 321 instead of 212?

#include <stdio.h> 

int main()
{
  int i;
  int j;
  int k;
 
  for(i = 1, j = 0, k = 3 ; i <= 5, j <= 6, k > 1 ;i++, j++, k--);
  {
    printf("%d%d%d", i, j, k);
  }
 }

Why is this program printing 321 instead of 212?
I get 321 when I execute the program but I think it should be 212. I cannot understand why it is printing 321.

>Solution :

That’s because you have a semicolon at the end of the for loop, so the code runs essentially like this:

// first you increment i,j and decrement k until k is 1, so twice
for(i = 1, j = 0, k = 3 ; i <= 5, j <= 6, k > 1 ;i++, j++, k--) {}
// then you print the values
printf("%d%d%d", i, j, k);

Leave a Reply