Subscribe to Penguin-man the computer guy

Wednesday, May 15, 2013

Gaining a basic understanding of the Logic of If and If-else statements

Next to while statements, if statements are one of the most important statements that can be made. As we noted in the last post, while statements and if statements control the flow of logic in a statement. This of course is equally important in language as it is in code. This is all well and good, but what do we mean by controlling the flow of logic in a sentence? Well, what I mean is that good logic flows in specific ways, and instead of a linear flow we can control that flow with while loops and if statements. Consider the following linear logic flow.

A ---> B ---> C ---> D

Here, premises A, B, and C all lead to D... but what if I wanted to lead to either D or E? To accomplish that, I would need to use a control structure that would make the logic flow to D if some condition were met, and to E if some other condition were met. Ideally, this might be an If-Else statement. Before showing pseudo code, lets examine our previous example altered to let us


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     }

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