Home > other >  Why is the output 321 instead of 212?
Why is the output 321 instead of 212?

Time:05-17

#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.

CodePudding user response:

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);

CodePudding user response:

You have 2 bugs.

The first was already mentioned and should also be reported by your compiler. You have a stray semicolon after your for loop.

The second is that your condition is rather strange: i <= 5, j <= 6, k > 1
Relational operators have higher precedence than coma operator. That means this condition is same as (i <= 5), (j <= 6), (k > 1) which again is same as k>1.
If you want to have all the relational operands evaluate to true, you must add logical operator: i <= 5 && j <= 6 && k > 1

  •  Tags:  
  • c
  • Related