Lesson 4 - Selection
Selection statements are
used to carry out a particular task if a certain condition is met (or not
met). In this way an element of decision-making is introduced into out
programs. This lesson outlines the use of the C++ if, else and
switch keywords.
if statements
The general syntax for a
C++ if statement is given below:
if (boolean-expression)
{
// Task statements go here
}
The if keyword if
followed by a bracketed Boolean expression. Recall from the previous lesson
that Boolean expressions use relational operators and are evaluated as being
either true or false. A set of opening and closing braces are
used to delimit the statements that are to be executed if the condition is
true. An example is shown below:
if (mark >= 50)
{
cout << "Congratulations! You have passed the
course." << endl;
}
If the variable mark
has a value of 50 or greater, the statements inside the braces are executed,
otherwise they are skipped over. There is no limit to the number of
statements you can place inside the braces. If there is only one statement
in the braces, the braces can be omitted (but this is not advised
initially). Here's another example using characters and the equality
operator:
if (symbol == '$')
{
cout << "You have chosen dollars." <<
endl;
}
Remember that Boolean
expressions use the equality operator, ==, not the assignment operator, =. Remember
also that character values such as '$' must be enclosed in single quotation
marks. here's another example that uses a Boolean operator as well:
if ( (classMark >= 50) &&
(testScore >= 65) )
{
cout << "Congratulations! You have passed the
course." << endl;
studentsPassed++;
}
In the code sample above,
if the students class mark is 50 or greater, and their test score 65
or greater, the entire expression becomes true. Therefore
the two statements inside the braces will be executed, which display an
appropriate message and increment a variable that keeps track of how many
students passed.
if-else statements
In an if statement,
the code inside the braces is only executed if the bracketed expression is true.
If it's false, the block of code is skipped over. However, an else
statement can be used to carry out an alternate task if the bracketed
expression is false. An example is given below:
if (mark >= 50)
{
cout << "Congratulations! You have passed the
course." << endl;
}
else
{
cout << "You have not yet passed the course."
<< endl;
}
If the bracketed expression
is false, that is, the value of mark is less than 50, the statements
in the else clause are executed. Notice that there is no bracketed
expression after the else as it's not needed.
The conditional operator
A short cut way of
implementing an if-else statement is shown below:
cout << (mark >= 50 ?
"Pass" : "Fail");
In his
example, if mark is 50 or more, the first argument "Pass"
is displayed, else "Fail" is displayed. here's a different
example:
interestRate = (accountBalance >=
3000 ? 0.05 : 0.03);
In his example, if accountBalance
is $3,000 or more, interestRate is assigned 0.05 (5%) else interestRate
becomes 0.03 (3%).
Nested if-else statements
The term nesting in
a programming context means to place something inside something else. In C++
any if or if-else statement can be placed inside any other if
or if-else statement, as many times as is required. This allows for
complex control structures to be developed. The possibilities are endless.
Consider the following
example. For a student to gain entry into a particular course, they must
have completed at least 144 credit points. If they haven't met this criteria
but have studied for at least 4 semesters, they will be placed on a
suitability list if a second round of offers is made. Otherwise, their
application is deemed unsuccessful. The code may look something like this:
if (creditPoints >= 144)
{
cout << "Congratulations! You qualify for entry into
the course."
<< endl;
}
else
{
if (semestersStudied >= 4)
{
cout << "You have been placed on a
suitability list." << endl;
}
else
{
cout << "Your application has been
unsuccessful at this time."
<< endl;
}
}
In this example, and
if-else statement has been nested within the else clause of an outer if-else
statement. If this type of nesting is continued, you end up with a series of
else statements followed by if statements. By removing the braces and reformatting
the layout, you can end up with what looks like a new construct, the else
if. Here's an example:
if (mark > 85)
cout << "High Distinction"
<< endl;
else if (mark > 75)
cout << "Distinction"
<< endl;
else if (mark > 65)
cout << "Credit"
<< endl;
else if (mark > 50)
cout << "Pass"
<< endl;
else
cout << "Fail"
<< endl;
The code above is an
example of a multi-level nested if-else construct laid out in a somewhat unconventional,
but acceptable way.
switch statements
The switch construct
provides an alternate way of coding nested selection statements. An example
is shown below that displays whether a runner has come 1st, 2nd, or 3rd,
based on their position.
switch(position)
{
case 1: cout << "You came 1st."
<< endl;
break;
case 2: cout << "You came 2nd."
<< endl;
break;
case 3: cout << "You came 3rd."
<< endl;
break;
default: cout << "You did not run a place."
<< endl;
}
The words switch, case,
break and default are all C++ keywords. In this example, position
is an integer variable. If the value of position is 1, the first case
is executed and any statements following it are executed up until the break.
If the value of position is 2, the second case is executed and and so
on. For all other values for which there is no case statement, the default
statement is executed. You can switch on any integer or character
variable, and the value following the case keyword can be any integer
or character value. Note the use of parentheses around the switch variable,
the colon after the case value, and the use of braces around the entire code
block.
Lesson
5 - Iteration
|