CS 1440 Lab 2
Cover sheetPrevious ActivityNext Activity

Activity 2-5: IF and IF-ELSE Statements

Activity Procedure

Conditional execution
The order in which statements are executed is the flow of control. So far in the programs you have written, each and every statement you write gets executed one after the other. To write more sophisticated programs, we will need to alter this sequential flow of control.Sometimes you may need your program to decide to execute one statement and not another. The IF-ELSE statement provides this branching capability.
 
IF-ELSE Statement basics

Sometimes it is necessary to have a program choose one of two alternatives, depending on some condition. For example, suppose your program has to output the larger of two integers, x or y. Well, if x is the larger value your C++ output statement would look like:

cout << "The largest value is " << x;
 

And if y is the larger value your C++ output statement would look like:

cout << "The largest value is " << y;

The problem then becomes how to make the program decide which of these statements to execute (based on the values of x and y)?

The IF-ELSE statement to the rescue!

Here is the C++ statement to do exactly what we want:

if (x > y)

cout << "The largest value is " << x;
else
cout << "The largest value is " << y;

IF-ELSE Statement syntax
 
The basic syntax of the C++ IF-ELSE statement is:

if (Logical_Expression)
Yes_Statement
else
No_Statement

The two embedded statements may be any executable statements. The Logical-Expression is some test that can be checked to see if it is true or false. The Logical-Expression in our example was:
 
x > y
 
When the program reaches an IF-ELSE statement, exactly one of the two embedded statements are executed. If the Logical-Expression is true then Yes_Statement is executed; if the Logical-Expressionis false then the No_Statement is executed. Every IF-ELSE statement must have a Logical_Expression so let's talk a little about logical expressions.
A simpler variation of the IF-ELSE statement is when you don't want to do anything in the No_Statement. In this situation the else part can be omitted altogether. For example, to abort if there is a malfunction detected.

if (Logical_Expression)
Yes_Statement
 
A more complicated variation of the IF-ELSE statement is when you need to execute more than one statement based on the logical expression. In this case the Yes_Statement and/or the No_Statement can be a compound statement. A compound statement is a list of statements enclosed in a pair of braces. A compound statement is treated as a single statement by C++ and can be used anywhere that a single statement can be used.
 
if (Logical_Expression)
{
Yes_Statement_1
Yes_Statement_2
. . .
Yes_Statement_Last
}
else
{
No_Statement_1
No_Statement_2
. . .
No_Statement_Last
}