Easy
tutorial for C / C ++ Control
statement 1-b (Nested if else statements)
Nested if else
statements
:
- It is a control statement that sets a number of
conditions and allows a specific statement to be executed when a certain
condition is true. The structure is as follows.
if ('condition 1') {'execute statement 1'}
else if ('condition 2') {'execute statement 2'}
else if ('condition 3') {'execute statement 3'}
...
else {'execute statement 0'}
else if ('condition 3') {'execute statement 3'}
...
else {'execute statement 0'}
-
If 'condition 1' is satisfied in the first ' if '
statement, 'execute statement 1' is executed. The rest of the statements are
not executed at this time.
-
If the first 'condition 1' is not satisfied, the next 'else
if ' statement is executed and the 'condition 2' is judged again. If 'condition
2' is true, 'execute statement 2' is executed. That is, if 'condition 1' is
false and 'condition 2' is true, 'execute statement 2' is executed and the
remaining execution statements are not executed.
-
You can add multiple else if statements. The last 'else'
statement is a statement that is executed when all the above conditions are not
satisfied.
Example Code
#include
<iostream>
using
namespace std;
int
main() {
int a, b;
a = 10 ;
b = 20 ;
if(a > 100){
cout<<" a > 100 is true !!! "<<endl ;
} else if(b > 100){
cout<<" b > 100 is true
!!! "<<endl ;
} else {
cout<<" Both a > 100 and b > 100 are false !!!
"<<endl ;
}
return 0;
}
Results:
Both a > 100 and b > 100 are false !!!
-
Since the conditional expression of the first ' if '
statement is false, the statement "a > 100 is true !!!" is not printed
and the next 'if else' statement is executed.
- The statement "b > 100 is true !!!" is not also printed because
conditional expression of the 'if else' statement is false.
- Since both of the above conditions are false, the last execute statement is
executed.
No comments:
Post a Comment