What are the algorithm(step) through which the given program exhecutes? why if(condition) in 1st code is false? Why not in 2nd? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What are the algorithm(step) through which the given program exhecutes? why if(condition) in 1st code is false? Why not in 2nd?

The if statement in first code says(1≠2 and 2 is greater than 0) which seems to be correct! What is the reason the program prints '0' on screen? Please explain algorithm (steps) of the program through which it exhecutes? 1st code #include<iostream> using namespace std; int main() {int x=1,y=2,z=0; if(x!=y>z) {cout<<"1";} else {cout<<"0";} return 0; } //Output:- 0 2nd code #include<iostream> using namespace std; int main() {int x=1,y=2,z=0; if(y!=x>z) {cout<<"1";} else {cout<<"0";} return 0; } //Output:- 1

19th Mar 2018, 2:35 PM
Suraj Jha
Suraj Jha - avatar
3 Answers
+ 6
If you're evaluating more than one expression with the if statement, you need to define which operator will be used to compare one expression with another. You said you wanted to check whether (1≠2 *and* 2 is greater than 0) but you forgot to define that you are comparing x!=y with y>z using AND operator, that's why you got unexpected result. One thing to remember, when an expression is evaluated, they come out in boolean result, your expression "x!=y>z" is evaluated as follows: - if x(1) not equal to (y(2)>z(0)), see next... - if x(1) not equal to true (true, because y(2) is greater than z(0)), in C or C++ true equals to 1. So next, we end up with: - if x(1) not equal to 1, which gives us false (obviously 1 equals to 1) then the "else" block is executed and output "0". // Your first code int main() { int x=1,y=2,z=0; if(x!=y && y>z) // Use AND operator (&&) // some code here ... return 0; } Your second code is incorrect at the same point, where you did not specify AND operator between y!=x and x>z. The expression is evaluated as follows: - if y(2) not equal to (x(1)>z(0)), see next... - if y(2) not equal to true (true, because x(1) is greater than z(0)), *remember* true equals to 1, next... - if y(2) not equal to 1, which gives us true, because 2 is indeed not equal to 1. This makes the "if" block executed, and outputs "1". int main() { int x=1,y=2,z=0; if(y!=x && x>z) // Use AND operator (&&) // some code here ... return 0; } I tried to explain it best I can, but if it's not clear enough you are welcome to ask again : ) Hth, cmiiw
19th Mar 2018, 4:59 PM
Ipang
+ 6
@Suraj, you're welcome, I'm glad if it could help : )
20th Mar 2018, 2:46 AM
Ipang
+ 2
thankyou so much 'ipang' you explained it very well.... again thank you so much..☺
20th Mar 2018, 2:40 AM
Suraj Jha
Suraj Jha - avatar