Create a free account on Computer Sir Ki Class and unlock access to valuable learning resources.
Exam Paper Downloads: After registering and logging in, you can download exam question papers in PDF format to practice and prepare for your exams.
Student Support: Get assistance with your doubts, queries, and questions related to your studies. Our support is here to help you understand topics and resolve your learning difficulties.
Register today and make your exam preparation easier and more effective!
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
Run Output
Sorry
Hello
Hello
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.