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

The following program should print out “x is even” if the remainder of x divided by 2 is 0 and “x is odd” otherwise, but the code is mixed up. The % symbol gives the remainder after the first number is divided by the second number. Drag the blocks from the left and place them in the correct order on the right. Be sure to also indent correctly! Click on <i>Check Me</i> to see if you are right. You will be told if any of the lines are in the wrong order or have the wrong indention.</p>

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

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 1 of 5 activities on this page