Read: §4.1-§4.9 of the Textbook, pp 39-46

Decisions, Decisions

The decision involved with while-loops is whether or not to execute the statement coming after the condition. If the condition is true, the computer executes the following statement and then re-checks the condition to see if there should be another repetition. If the condition is false, the following statement is skipped. The if prefix discussed below does not involve repetitions.

Decision Version 1: if (condition)


Do the statement that comes after the condition or skip it. One way to think of this is that the statement after the condition is protected. It will only be executed if the condition is true. Often the statement is compound. Recall that we execute a compound statement by executing each of the statements in it.

Example 1
Example 1a: Counting letter a's

Format:

if (condition)
     statement
Semantics: The statement after the condition is the body of the decision. If the condition is True then the statement is executed once. If the condition is False then the statement is skipped. In either case the program continues with whatever comes after the statement.

Decision Version 2:

if (condition)

else

Do ONE of two statements. Do the statement after the condition if the condition is true. Otherwise do the statement after the else.

Example 2

Format:

if (condition)
     statement1
else
     statement2
Semantics: Exactly one of the two statements will be executed, then execution will continue with the rest of the program. If the condition is True then the statement1 is executed. If the condition is False then the statement2 is executed.

Decision Version 3: Chained if-else constructs

Do one of several sets of statements.

Example 3

Format: You can have as many else if clauses as you want

if (condition1)
     statement1
else if (condition2)
     statement2
else if (condition3)
     statement3
  .
  .
  .
else:
     statementN
Semantics: C will do exactly one statement and then continue with the rest of the program. It will do the first statement whose conditon is True or if no condition is true, it will do the statement after the last else.

Next: Function scanf