If Else If – Simple If Ladder
Simple if-else-if in a ladder style comparison
Learning Objectives
- Using if-else-if in a ladder form, which means checking for more if conditions in the else part of the selection.
Source Code
|
|
Run Output
Code Understanding
int a,b; cout<<“Enter integer a:”;cin>>a; cout<<“Enter integer b:”;cin>>b;
Two plain integers are collected from the user.
if(a==b) cout<<“A is equal to B”<<endl;
Matching if both integers are same. == is the comparison operator, unlike = which is the assignment operator. If same appropriate message is displayed
else if(a>b) cout<<“A is greater than B”<<endl;
In first else condition there is further check for another if. This is called the if-ladder logic as multiple such conditions can be checked in a sequence. Appropriate message is displayed.
else cout<<“A is smaller than B”<<endl;
This is final else condition of the ladder.
Notes
- Some times programmers call this form also as the nested-if form. Although technically the nested if has more if conditions in the true part of the selection.
Common Errors
- New programmers often confuse between = and == operator. Remember that in if condition check it will always be == or conditional equal to check operator. The assignment operator = used only in statements where left hand side has to be made equal to the right hand side.
Suggested Filename(s): ifelseif.cpp, ifladder.cpp
Created: 26-Dec-2017 17:05 | Updated: 15-Sep-2018 11:46|
