Search code examples
cif-statementconditional-statementsoperator-precedence

Assignment and Conditional check in C


I came across this below program and I don't understand the output.

Can someone please shed some light on it?

#include <stdio.h>

int main()
{
  int i=1,j=1;
  for(;j;printf("%d %d\n",i,j))
  j=i++ <=5;
  return 0;
}

And its output is:

2 1
3 1
4 1
5 1
6 1
7 0

Solution

  • #include <stdio.h>
    
    int main()
    {
      int i=1,j=1;
    
      //for(initialisation; condition; operations)
      // here no initialisation, 
      // 1. condition is j, if j is true 
      // 2. then it will execute block statements 
      // 3. then finally it execute operations, here printf
      // 4. again check step 1.
    
      for(;j;printf("%d %d\n",i,j))
      j=i++ <=5;  // j = (i <= 5); i++;
      return 0;
    }
    

    Your question can be simplified as follows

    #include <stdio.h>
    int main()
    {
      int i=1,j=1;
      while(j) {   
        j = (i++ <=5);
        printf("%d %d\n",i,j);
      }
      return 0;
    }