Using if and else

Most professional programmers would write the following code:

Like this:

An else is an additional optional phrase on an if statement. IF AND ONLY IF the test in the if is false does the block of statements after the else get executed. Using an if with an else makes sure that either the if block is executed or the else block is executed, but never both.

Flowchart for both an if and else

Figure 4: Flow of execution for both an if and else

Mixed up programs

It is easy to write an if when you want exactly one block to execute, but you can accidentally create a “hole” – a condition where neither block executes. That’s what happened in the example below when the weight is equal to 1 pound.

You have attempted of activities on this page