A ---> B ---> C ---> D
A ---> B ---> C if( condition = true ) ---> D
\
\
\--------> else ---> E
Note how if the condition is not true (~ condition ), then the logic automatically flows to the else. This makes the else the default position of the logic flow. In pseudo code, this is how it looks:
1 if( condition )
2 {
3 statements;
4 }
5
6 else
7 {
8 statements;
9 }
The other case is a series of if statements.
1 if( condition )
2 {
3 statement_1;
4 }
5
6 if( condition )
7 {
8 statement_2;
9 }
10
11 if( condition )
12 {
13 statement_3;
14 }
Note that in the case of a series of statements and no else at the end, there is no default behavior. Default behavior in a program is the result of else statements, and so if a program has a default behavior, then that should be written as an else. This makes the following syntax the best format for writing a program:
1 if( condition )
2 {
3 optional behavior;
4 }
5
6 else
7 {
8 default behavior;
9 }
1 if( condition )
2 {
3 statements;
4 }
5
6 else
7 {
8 statements;
9 }
The other case is a series of if statements.
1 if( condition )
2 {
3 statement_1;
4 }
5
6 if( condition )
7 {
8 statement_2;
9 }
10
11 if( condition )
12 {
13 statement_3;
14 }
Note that in the case of a series of statements and no else at the end, there is no default behavior. Default behavior in a program is the result of else statements, and so if a program has a default behavior, then that should be written as an else. This makes the following syntax the best format for writing a program:
1 if( condition )
2 {
3 optional behavior;
4 }
5
6 else
7 {
8 default behavior;
9 }
Conclusion
If and if-else statements are a relatively simple logical structure. Implementing them in code is not very hard to do, but there simplicity belies the power that they bring to life and code.
No comments:
Post a Comment