Example(s):Palindrome, prime, armstrong, "linear search", reverse etc.
Example(s):1575, 1632, 1539 (Only one at a time)
Login
[lwa]
Solved Problem
#CPP#3249
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.