Professional Documents
Culture Documents
Chapter 3
Chapter 3
Control Statements
THE
if,
if/else,
if/else if
STATEMENTS
THE if STATEMENT
The if statement can cause other statements to execute only
under certain conditions.
If the expression inside the parentheses is true, the
statements inside the braces are executed. Otherwise, they
are skipped.
The following figure shows the general format of the if statement.
… the if statement
Ifthe block of statements to be conditionally executed
contains only one statement, the braces can be
omitted.
Example of if statement:
if (x == 100)
cout << "x is 100";
the cout statement will only be executed only if x is equal
to100
Ifwe want more than a single instruction to be
executed in case that condition is true we can specify a
block of instructions using curly braces { }:
if (x == 100)
{
cout << "x is ";
cout << x;
}
… the if statement
Putting a semicolon after the if part will terminate the if statement.
The block of statements will then always execute. For example,
#include <iostream.h>
int main()
{
int x=4;
if(x>4); // The semicolon terminates the if statement.
{
cout<<"\nInside";
}
cout<<"\nOutside";
}
Output
Inside
Outside
… the if statement
Without a set of braces, it only executes the very
next statement.
For example, notice the following program.
if (average == 100)
cout << "Congratulations! "; // There are no braces.
cout << "That's a perfect score!\n"; // This is outside the
if.
If the condition (average == 100) is false, the
Congratulations! message will be skipped.
That's a perfect score! was executed, as it would
be every time, regardless of whether average
equals 100 or not.
… the if statement
Do not confuse the equality operator (==) with the
assignment operator (=), as in the following statement:
if (x = 2) // Caution here!
cout << "It is True!";
This statement does not determine if x is equal to 2; it
assigns x the value 2!
Furthermore, the cout statement will always be executed
because the expression x = 2 evaluates to 2, which C++
considers true.
C++ stores the value true as 1. But it actually considers
all nonzero values, not just 1, to be true. Thus 2
represents a true condition.
… the if statement
A relational expression has the value 1 when it is true
and 0 when false.
While 0 is considered false, all values other than 0 are
considered true.
Here is a summary of the rules you have seen so far:
When a relational expression is true it has the value 1.
When a relational expression is false it has the value 0.
An expression that has the value 0 is considered false.
An expression that has any value other than 0 is considered
true.
For example, the following is a legal if statement in C++:
if (value)
cout << "It is True!";
If the variable, value, contains any number other than 0, the
message “It is True!” will be displayed.
… the if statement
Here is another example:
if (x + y)
cout << "It is True!";
In this statement the sum of x and y is tested.
If the sum is 0, the expression is false; otherwise it is
true.
You may also use the return value of a function call as a
conditional expression.
if (pow(a, b))
cout << "It is True!";
This if statement uses the pow function to raise a to the power of
b.
If the result is anything other than 0, the cout statement is
executed.
… the if statement
// This program shows an if-statement
#include <iostream.h>
void main()
{
int score1, score2, score3;
double average;
cout << "Enter 3 test scores and I will average them: ";
cin >> score1 >> score2 >> score3;
average = (score1 + score2 + score3) / 3.0;
cout << "Your average is " << average << endl;
if (average == 100)
{
cout << "Congratulations! ";
cout << "That's a perfect score!\n";
}
}
Output Enter 3 test scores and I will average them: 100 100 100[Enter]
Your average is 100.0
Congratulations! That's a perfect score!
THE if/else STATEMENT
THE if/else STATEMENT
The if/else statement is an expansion of the if statement.
The if/else statement will execute one set of statements when the if
expression is true, and another set when the expression is false.
The following figure shows the general format of this statement and
a flowchart visually depicting how it works.
… the if/else Statement
The if/else statement causes program
execution to follow one of two exclusive
paths.
If you don’t use braces the else part
controls a single statement.
To execute more than one statements with
the else part, place these statements
inside a set of braces.
… the if/else Statement
//Example Program 1
/*This program uses the modulus operator to determine if a number is odd or
even. */
#include <iostream.h>
int main()
{
int number;
cout << "Enter an integer and I will tell you if it\n";
cout << "is odd or even. ";
cin >> number;
if (number % 2 == 0) // If the number is evenly divisible by 2, it
cout << number << " is even.\n";
else
cout << number << " is odd.\n";
return 0;
}
Output
Enter an integer and I will tell you if it
is odd or even. 17[Enter]
17 is odd.
… the if/else Statement
// Example Program 2
/*This program makes sure that the divisor is not equal to
0 before it performs a divide operation.*/
#include <iostream.h>
int main() Output
Enter a number: 10[Enter]
{
Enter another number: 0[Enter]
double num1, num2, quotient;
Division by zero is not possible.
cout << "Enter a number: ";
Please run the program again and enter a
cin >> num1;
number other than zero.
cout << "Enter another number: ";
cin >> num2;
if (num2 == 0)
{
cout << "Division by zero is not possible.\n";
cout << "Please run the program again and enter ";
cout << "a number other than zero.\n";
}
else
{
quotient = num1 / num2;
cout << "The quotient of " << num1 << " divided by ";
cout << num2 << " is " << quotient << ".\n";
}
return 0;
}
THE if/else if STATEMENT
THE if/else if STATEMENT
The if/else if statement is a chain of if statements.
They perform their tests, one after the other, until one of them is found to
be true.
The following figure shows its format and a flowchart visually depicting
how it works.
… the if/else if Statement
Each if statement in the structure depends on all
the if statements before it being false.
The statements following a particular else if are
executed when the conditional expression
following the else if is true and all previous
conditional expressions are false.
A trailing else, placed at the end of an if/else if
statement, provides a default set of actions
when none of the if expressions are true.
… the if/else if Statement
/* Example Program :This program uses an if/else if statement to assign a letter grade (A,
B, C, D, or F) to a numeric test score.*/
#include <iostream.h>
void main()
{
int testScore;
char grade;
cout << "Enter your numeric test score: ";
cin >> testScore;
if (testScore < 60)
grade = 'F';
else if (testScore < 70)
grade = 'D';
else if (testScore < 80)
grade = 'C';
else if (testScore < 90)
grade = 'B';
else if (testScore <= 100)
grade = 'A';
else
{
cout << "\nThe test score is an invalid score.\n";
cout << "Please enter a score that is between 0 and 100.\n";
}
cout << "\nYour grade is " << grade << ".\n";
}
Nested if
Statements
Nested if Statements
A nested if statement is an if statement in
the conditionally executed code of another
if statement.
Anytime an if statement appears inside
another if statement, it is considered
nested.
Nested if statement is good for narrowing
choices down and categorizing data.
… Nested if Statements
/* Example Program: This program demonstrates a nested if statement.*/
#include <iostream.h>
int main()
{
char employed, recentGrad;
cout << "Answer the following questions with either Y for Yes or N for No.\n";
cout << "Are you employed? ";
cin >> employed;
cout << "Have you graduated from college in the past two years? ";
cin >> recentGrad;
if (employed == 'Y')
{ // Nested if
if (recentGrad == 'Y') // Employed and a recent graduate
{
cout << "You qualify for the special interest rate.\n";
}
else // Employed but not a recent graduate
{
cout << "You must have graduated from college in the past two years to qualify.\
n";
}
}
else // Not employed
cout << "You must be employed to qualify.\n";
return 0;
}
SWITCH STATEMENT
switch Statement
The switch statement lets the value of a variable
or expression determine where the program will
branch to.
The if/else if statement allows your program to
branch into one of several possible paths.
It performs a series of tests (usually relational) and
branches when one of these tests is true.
The switch statement tests the value of an
integer expression and then uses that value to
determine which set of statements to branch to.
…switch Statement
Here is the format of the switch statement:
switch (integer expression)
{
case constant expression:
// Place one or more statements here.
case constant expression:
// Place one or more statements here.
// Case statements may be repeated as many times as necessary.
case constant expression:
// Place one or more statements here.
default:
// Place one or more statements here.
}
…switch Statement
An integer expression can be either of the
following:
A variable of any of the integer data types (including
char)
An expression whose value is of any of the integer
data types
On the next line is the beginning of a block
containing several case statements.
Each case statement is formatted in the
following manner:
case constant expression:
// Place one or more statements here.
…switch Statement
After the word case is a constant expression
The constant expression can be either an integer literal
or an integer named constant.
The constant expression
cannot be a variable and
it cannot be a Boolean expression such as x < 22 or n == 25.
The case statement marks the beginning of a section of
statements.
case statements are branched to if the value of the
switch expression matches that of the case expression.
The expressions of each case statement in the block
must be unique.
…switch Statement
An optional default section comes after all
the case statements.
This section is branched to if none of the case
expressions match the switch expression.
Thus it functions like a trailing else in an
if/else if statement.
Example(This program demonstrates the use of a
switch statement)
main()
{
char choice; Program Output
cout << "Enter A, B, or C: "; Enter A, B, or C: B [Enter]
cin >> choice; You entered B.
switch (choice) Program Output
{ Enter A, B, or C: F [Enter]
case 'A': You did not enter A, B, or C!
cout << "You entered A.\n";
break;
case 'B':
cout << "You entered B.\n";
break;
case 'C':
cout << "You entered C.\n";
break;
default:
cout << "You did not enter A, B, or C!\n";
}
}
…switch Statement
A break statement is needed whenever you want
to “break out of” a switch statement.
The case statements show the program where
to start executing in the block and the break
statements show the program where to stop.
Without the break statements, the program
would execute all of the lines from the matching
case statement to the end of the block.
the program “falls through” all of the statements below
the one with the matching case expression.
The default section (or the last case section, if
there is no default) does not need a break
statement. Put there anyway, for consistency.
Example (This program demonstrates how a switch
statement works if there are no break statements)
main()
Program Output:
{ Enter A, B, or C: A[Enter]
char choice; You entered A.
You entered B.
cout << "Enter A, B, or C: "; You entered C.
cin >> choice; You did not enter A, B, or C!
switch (choice) Program Output
{ Enter A, B, or C: C[Enter]
You entered C.
case 'A':
You did not enter A, B, or C!
cout << "You entered A.\n";
case 'B':
cout << "You entered B.\n";
case 'C':
cout << "You entered C.\n";
default :
cout << "You did not enter A, B, or C!\n";
}
}
Example (The switch statement in this program uses the "fall
through" feature to catch both uppercase and lowercase letters
main()
entered by the user)
{
char feedGrade;
cout << "Our dog food is available in three grades:\n";
cout << "A, B, and C. Which do you want pricing for? ";
cin >> feedGrade;
switch(feedGrade)
{
case 'a': Program Output
case 'A': Our dog food is available in three grades:
cout << "30 cents per pound.\n"; A, B, and C. Which do you want pricing for?
break; b[Enter]
case 'b': 20 cents per pound.
case 'B': Program Output
cout << "20 cents per pound.\n"; Our dog food is available in three grades:
break; A, B, and C. Which do you want pricing for?
case 'c': B[Enter]
case 'C': 20 cents per pound.
cout << "15 cents per pound.\n";
break;
default :
cout << "That is an invalid choice.\n";
}
return 0;
}
THE CONDITIONAL OPERATOR
The Conditional Operator
You can use the conditional operator to
create short expressions that work like
if/else statements.
The operator consists of the question-
mark (?) and the colon(:).
Its format is