retagged by
1,024 views
5 votes
5 votes

What is the output of the following program?
main( )
{
int i=4, z=12;
if( i=5 || z > 50)
printf(“ Gate2017”);
else
printf(“ Gateoverflow”);
}

  1. Gate2017
  2. Gateoverflow
  3. syntax error
  4. Gate2017Gateoverflow
retagged by

3 Answers

Best answer
8 votes
8 votes
i=5 will assign value 5 to i so the if statement (i=5||z >50) is true ,  “printf” statement will print Gate2017.
selected by
2 votes
2 votes
int main()
{
    int i=4 , z = 12;
    if(i = 5 || z > 50)
        printf("Inside if %d",i);
    else 
        printf("Inside else %d",i);
    
}
Output : Inside if 1

This is because of precedence, this expression is evaluated as i = (5||z>50) as 5 is a non zero number so it evaluates as true and printf inside if is executed. 

Logical OR has higher precedence than assignment operation.
Source: http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm

A few variations for more clarity:

int main()
{
    int i=4 , z = 12;
    if(i = 5 && z > 50)
        printf("Inside if %d",i);
    else 
        printf("Inside else %d",i);
    
}

Output : Inside else 0
int main()
{
    int i=4 , z = 12;
    if(i = 0 || z > 50)
        printf("Inside if %d",i);
    else 
        printf("Inside else %d",i);
    
}

Output: Inside else 0
1 votes
1 votes
here in if i is assigned 5 any non-zero value is taken as true ,therefore it is true

if(i=5 ||z>50) will become if(5|| z>50) if(true|| z>50)

Gate2017 will be printed
Answer:

Related questions

0 votes
0 votes
1 answer
1
1 votes
1 votes
1 answer
2