If Else If – Age of Friend problem bettered
Simple if-else-if in a ladder style comparison to resolve age of friends problem which was not able to compare two friends with equal age.
Learning Objectives
- Using if-else-if in a ladder form, which means checking for more if conditions in the else part of the selection.
- Bettering the friend’s age problem which was done using the simple if-else only.
Source Code
|
|
Related ( ? ) : |
Run Output
Code Understanding
int sa,fa; cout<<“Enter your age : “;cin>>sa; cout<<“Enter your friend’s age : “;cin>>fa;
Here we collect your and your friend’s age.
if(sa==fa) cout<<“You both friends are equal in age.”<<endl;
We first compare if the age is equal. This we were not doing earlier when the age of two friends were assumed to be different.
else if(sa>fa) cout<<“You are older than your friend.”<<endl;
Here we compare your age to friend’s age. Mark the use of additional if in the else section. Here we are using the if ladder technique to create another level of comparison.
else cout<<“You friend is older than you.”<<endl;
Here we are doing the last condition assuming the other conditions are not met.
Notes
- The simple if-else problem without the equal age condition can be seen at
http://computersirkiclass.com/?codesheet=comparing-age-of-two-friends-of-different-age&tag=cp009-simple-if-and-if-else - 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): agecomparison-better.cpp, age-comparison.cpp
Created: 26-Dec-2017 23:25 | Updated: 15-Sep-2018 11:47|
