# Answer :
GIven : x = 1
Statements on the Left :
If (x>=0)
x =x +1;
else if (x>=1)
x = x+2;
Evaluation : x>=0
1>=0
true . So the first If statement is true . Therefore x =x +1
x =1+1
x = 2 . All other conditions are skipped.
Final Result : x = 2
Explanation :
- This is if-elseif ladder. Here if the specified condition is
not true, it will continue to check the next condition in the
ladder (next else if) until it satisfies any condition.
- The format of the if else if ladder is :
if(condition 1){
// if condition 1 is true execute this block
}
else if(condition 2){
// if condition 1 is false and condition 2 is true
execute this block
}
else if(condition 3){
// if condition 1 is false, condition 2 is false and
condition 3 is true execute this block
}
else{
// if all the conditions are false then execute this
block (optional block)
}
- Here, it will continue to check the next condition in the
ladder (next else if) until it satisfies any condition.
- else is an optional block, it executes when none of the
conditions are true.
- Once it finds the first condition which it satisfies, it
executes its block and skips all the other conditions after it in
the else ladder even if they are satisfied.
- In the above, the problem both the conditions satisfy the given
value of x, but only the first one which comes in the ladder is
being executed and others which are after it are skipped.
- Hence, if(x>=0) condition block is only executed because it
is the earliest condition block.
Statements on the Right :
If ( x>=0)
x = x+1;
if (x>= 1)
x=x+2;
Evaluation :
The first condition : x>=0
1>=0
true . Therefore, x = x+1
x = 1+1
x = 2.
The value of x is now 2. (x =2)
The second condition : x>=
1
2>=1
true . Therefore, x = x+2
x = 2+2
x = 4
The value of x is now 4. (x =4)
Final Result : x = 4
Explanation :
- There are two separate simple if statements.
- The format of simple if :
if(condition){
// if condition is true this block will be executed
otherwise skipped
}
- Above problem (Statements on the right) both the if statements
will be executed as they are separate.
- FIrstly If ( x>=0) is executed which will update the value
of x if the condition is true. It evaluates true and sets value of
x to 2 (x = 2).
- Secondly If ( x>=1) is executed which will update the value
of x if the condition is true. It evaluates true and sets value of
x to 4 (x = 4).
- So the final value of x here is 4.
Difference between the Left and Right Statements
:
- Left statements form an if-elseif ladder. Here the first
condition which satisfies is executed and other conditions are
skipped even though they are satisfied.
- While the right statements have two separate if statements.
They are executed one by one updating the value of x.