Output writing – If-else ambiguities – CSKC
Sign In

Search

Solved Problem #CPP#3249    siteicon   siteicon  

Problem Statement - Output writing – If-else ambiguities

Write output of the following code. Assume that required header files are included.

int main()
{
  int x=10,y=20;
  if(x=0) cout<<"Hello"<<endl;
  else cout<<"Sorry"<<endl;
  if(y=10) cout<<"Hello"<<endl;
  else cout<<"Sorry"<<endl;
  if(x+y==10) cout<<"Hello"<<endl;
  else cout<<"Sorry"<<endl;
  return 0;
}

Solution

TC++ #3249

 

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Notes

int x=10,y=20;  //Initial values

if(x=0) cout<<“Hello”<<endl; else cout<<“Sorry”<<endl;
Here instead of comparison only assignment is done. Since by assignment there is zero value put so the selection answer would be false. In c++ any value of 0 is considered as equivalent to false. So it will go to the else condition Sorry would be printed.

if(y=10) cout<<“Hello”<<endl; else cout<<“Sorry”<<endl;
Here again assignment is there but this time it as positive value being assigned. So it will assume the condition to be true and Hello will be printed.

if(x+y==10) cout<<“Hello”<<endl; else cout<<“Sorry”<<endl;
Now x has become 0 and y has become 10 due to previous two assignments within the if condition checks.  So the condition x+y==10  will be true. Here addition will occur before assignment. Now Hello would be printed.

 

Common Errors

  • Student often forget to watch that there is assignment happening in first two if conditions and comparison is just not happening.

 


Share

Created: 2-Feb-2018 21:00 | Updated: 22-Mar-2026 20:17|