See pages 115-122 in A Computer Science Tapestry for more coverage of this information and pages 122-126 for additional information. When reading these pages you should substitute character arrays for string statements and ignore the #include "CPstring.h" statement.
Using the expressions that we have incorporated so far, we have not allowed the computer to make any "decisions." That is, when a program is run the computer must execute every line of code that is written. We can allow the computer to adjust to user input by utilizing conditional expressions, so called because their execution is conditional upon certain values. The first conditional expression that we will use is the if/else statement. The basics of this statement are similar to the if-then-else statements of QuickBasic and Visual Basic.
The basic form of the if/else statement is as follows:
The test expression is usually an equality or inequality that evaluates to either true or false. If it is true the first statement list is executed. If it is false then the second statement list is executed. The else portion of the if/else statement is actually optional. It is valid to have just an if statement. For an explanation of the valid operators in the test expression see page 119 (they are ==, >, <, !=, >= and <=). The most confusing of these is the equals operator (==). This is different than the equals that we use when assigning values to variables (=). This is to differentiate their functions. The single equals (=) assigns values to variables whereas the double equals (==) tests for equality. Here is an example:
What does this program do? Try using different expressions in place of guess==4. For example try guess<4, or guess>=4. Now what does the program do?
One particularly useful place for if/else statements is in conjunction with selections from menus. With just if/else statements as outlined above, you could only select from a menu with two choices. This can be extended through multiple if/else if/else statements. The format for these statements is:
This can be used to select from menu choices as in the following example:
There is a lot more to learn about if/else statements and the expressions that can be evaluated in them, but for now let's experiment with these forms. Notice the way that the if statments are indented. This makes it easy to read. Let's construct a program that allows you to enter a name, and then makes one of four statements using that person's name. The basic structure of this program looks as follows:
A sample run of this program looks like this:
What does this printchoice function need to look like? Make sure that it responds properly to choices other than one to four.