Aksh
Aksh

Reputation: 73

Usage of printf() function in for loop

#include<stdio.h>
int main()
{
    int x=1,y=1;
    for(;y&x<6;printf("%d %d\n",x,y++))
     x++;
}

Here I expected an output like:

2 1
3 2
4 3
5 4
6 5

but I got an output

2 1

Upvotes: 2

Views: 437

Answers (4)

Dixel
Dixel

Reputation: 564

I recommand

#include<stdio.h>
int main()
{
    int x,y;
    for(x = 1, y = 1; (y & x)<6;printf("%d %d\n",x,y++));
        x++;
    return 0;
} 

because, as pointed by @coderredoc, > has higher precedence than &.

Upvotes: 0

MSH
MSH

Reputation: 163

Are you trying to check if both y and x are smaller than 6? if so, instead of y&x<6 you should use (y<6)&&(x<6)

Upvotes: 1

user2736738
user2736738

Reputation: 30916

Because < has higher precedence than &from here.

So in the second iteration y=2 and x=1. x<6 becomes true - results in 1 which when ANDed with y the result becomes 0. So it stops. y<x&6 is equivalent to y&(x<6).

To explain you how AND works :- (shown in 6 bits - but the logic holds same way for sizeof(int)*8 bits).

      000010
  AND 000001
   ----------
      000000

Upvotes: 1

Shiva kumar
Shiva kumar

Reputation: 71

#include<stdio.h>
int main()
{
int x=1,y=1;
for(;y<6&x<6;printf("%d%d_",x,y++))
 x++;
}

try this

Upvotes: 0

Related Questions