Learning Unit C
Learning Unit C
1
INTRODUCTION
Sequence, selection, and repetition are the three fundamental control structures that may be
used to create any type of program in any programming language. The first part of this learning
unit presents an introduction of selection (decision) control structure, meanwhile the second
section focusses on iteration control structure.
In this learning unit you are going to learn how to design programs that execute in selection
control structure by using an IPO chart, Flowchart, and the implement these designs in C++.
In the previous learning unit, we have demonstrated the declaration section, input section and
calculation section in details, therefore this learning unit provide more details regarding the
selection and looping structure. Before you can use any selection and looping structure, it is
important to understand various relational and logical operators and how they are evaluated
in programming.
RELATIONAL OPERATORS
All high-level programming languages permit the use of relational and logical operators. Two
values can be compared in a program. Relational expressions are those that compare
operands (values or variables). Such a comparison's outcome or result is always a Boolean
value, which is either true (1) or false (0). Relational operators:
2
Table 3.1 lists relational operators used in programming along with the symbols used to
represent them in this module.
• 2<3 = true
• 8 != 8 = false
• code != "sd" = true
• 2 == 2 = true
• 3.5<=8.5 = true
Relational operators can be applied to strings. Strings are compared character by character,
beginning with first character.
Evaluating Relational Expressions
The arithmetic operators have a higher precedence than the relational operators, but relational
operators have equal priority. The following examples shows how to evaluate relational
expressions:
Examples 1:
Determine whether the following expression is true or false:
Substitute:
5 <= 7 - 3
3
Answer to calculation:
5 <= 4
Outcome of relational comparison:
false
Examples 2
Determine whether the following expression is true or false:
Substitute:
4 + 7 > 12 – 3 * 5
Answer to first calculation: (* higher priority than +)
4 + 7 > 12 – 15
Answer to second calculation: (from left to right)
11 > 12 – 15
Answer to third calculation:
11 > -3
Outcome of relational comparison:
true
Re-write the following mathematical equations using C++ operators and then evaluate the
expressions:
LOGICAL OPERATORS
4
Two Boolean expressions are joined by a logical operator to produce a single Boolean result
that is either true or false. Table 3.2 shows basic logical operators that are used in this module.
When several operators (mixed expression) are used in a single equation, all the arithmetic
operators are first evaluated, followed by the relational operators and then the logical
operators. The order may be altered by using parenthesis. For example, if an || must be
processed before an &&, parenthesis can be inserted.
Evaluate the following expressions:
Example 1:
5
true && true || false
true || false
true
Example 2:
Substitute:
-15 < (-17 + 7) && false || (5 * 12) >= (-15 - -17 + 12)
-15 < -10 && false || (5 * 12) >= (-15 - -17 + 12)
-15 < -10 && false || 60 >= (-15 - -17 + 12)
-15 < -10 && false || 60 >= (-15 + 17 + 12)
-15 < -10 && false || 60 >= (2 + 12)
-15 < -10 && false || 60 >= 14
true && false || 60 >= 14
true && false || true
false || true
true
Evaluate the following expressions where A = 5, B = 7, C = -4, D = 12, E = true and F = false
ONE-WAY if STATEMENT
6
A basic selection control structure allows one set of statements to be executed if a condition
is true. Let's use the following example to illustrate the purpose of if statement:
If an employee has worked more than 45 hours during the week, a bonus of R300 must be
added to his/her wage.
if (expression)
statement;
if (expression)
{
statement1;
statement2;
}
The expression is a Boolean expression. If the end value of the expression is true (1) then the
statement that follows the expression will execute, however if the value of the expression is
false (0) then the computer skips the first statement and execute the next one.
Example:
if (hours > 45)
7
wage = wage + 300;
Parentheses () are optional if the if statement only execute a single statement. In a flow chart
Therefore:
if (‘M’,’a’,’r’,’y’ != ‘M’, ‘p’, ‘h’, ‘o’)
ASCII values
if (77,97,’r’,’y’ != 77, 112, ‘h’, ‘o’)
The selection control structure enables the execution of a block of statements when a
condition is true and another set of statements when a condition is false. This type of a
selection control structure is referred to as an if-else statement.
8
if (expression)
statement1;
else
statement2;
if(expression)
{
statement1;
statement2;
.
.
.
statementn;
}
Example:
Suppose all the employees in a company receives an increase 8%, but the employees from
Department C receive an increase of 10%, as they performed better than the others. We can
accomplish this by writing the following if-statement that contains an else-clause:
if (dept == 'C')
increase = salary * 0.1;
//10% increase applies
else
increase = salary * 0.08;
// 8% increase applies
9
Review Activity 3.3:
10
3.3.3. Draw a flowchart and create a C++ program for each of the following scenarios in
order to solve the problems listed below:
3.3.3.1. Customers of ABC Cell Phone Company pay a base fee of R60 per month to
send texts. An extra 5c per message is charged for the first 100 texts sent each
month. More than 100 messages will incur an extra 10 cent fee. Enter a
customer's monthly text message use to calculate and display the customer's
bill amount.
3.3.3.2. Enter the employee's salary to calculate and display the employee's tax liability.
The percentage tax is 18% for employees making less than R20,000 per month
and 27% for all other wages.
3.3.4. Write down only the exact and correct output that will be displayed for the program
planned in Figure 3.5:
11
Using logical operators
We have the ability to simultaneously test several conditions thanks to logical operators.
Example:
A person may vote in an election if they are 18 years of age or older and have registered to
vote.
Try-It out
Problem statement:
All people entering the Rand Easter show pays a normal entrance fee, except for children
under 12 and pensioners (60 and over), who only pays half of the normal entrance fee. Enter
the normal entrance fee and the age in full years of the person and calculate and display the
actual entrance fee payable.
Draw a flowchart and write a C++ program to solve the following problem:
Athletes who have completed the Two Oceans Marathon or Round the Dam Marathon and
are members of a club and therefore eligible to compete in the Comrades Marathon. Enter the
athlete's name, the name of any clubs they may be a member of, whether or not they
participated in the Two Oceans Marathon, and whether or not they completed the Round the
Dam Marathon. Indicate if the athlete is permitted to take part in the Comrades Marathon and
show the athlete's name with an appropriate caption.
Ternary operator
Example:
12
string genderDescription = (gender == 'F' || gender == 'f') ? "Female" : "Male";
Often, other programming problems will require you to include, or nest, if statements within
another if or else statement to come up with a solution. Figure 3.6 illustrate a structure of a
nested if statement.
if (condition1)
statement1;
else if (condition2)
statement2;
...
else if (condition-n)
statement-n;
else
statement-z;
}
13
Example 1 of using nested if statements:
Problem statement:
Members of a club pay a basic membership fee per month, and then an additional fee
depending on the sport they participate in:
Write an algorithm to enter the basic membership fee, the name of the member, as well as the
code of the sport that he/she participates in. Then display a message containing the name of
the member, the name of the sport, as well as the membership fee, e.g. Peter takes part in
Squash and has a membership fee of R550.50
I P O
14
Step 2: Draw a Flowchart (See Figure 3.7):
15
16
Sample output
I P O
empNum Prompt for input empNum
deptCode Enter input weeklyPay
payRate Calculate weekly pay
hoursWorked Display output
17
Code snippet: Example 2
18
Example 3 on nested if statement:
Problem statement
The gender and age of a person determines how many minutes the athlete will get as a head-
start in a race. Every female of 50 years and older gets a 30-minute head-start, whereas all
other females get a head-start of 15 minutes. Males of 60 years and older gets a head-start of
20 minutes, whereas all other males get no head-start.
Enter the competitor number, the gender (M for male and F for female), as well as the age of
the athlete. Then determine the number of head-start minutes and display the competitor
number and the head-start minutes.
I P O
19
Review Activity 3.4:
In each of the following cases, draw an IPO Chart and flowchart as part of planning, then
write a complete C++ program:
3.4.1. An architect’s fee is calculated as a percentage of the cost of the building. The fee is
made up as follows:
Enter the cost of the building and calculate and display the architect’s fee.
3.4.2. Design a program that will prompt for and enter the price of an article and a discount
code. Calculate a discount according to the discount code and display the original price
on the screen as well as the discount amount and the discounted price. The discount
code and accompanying discount rate is as follows:
H 50%
F 40%
T 33%
Q 25%
Z 0%
Table 3. 8: Discount table for activity 3.4.2
20
If the discount code is Z, the words “No discount” are to be printed on the screen. If
the discount code is neither of the above, the words “Invalid discount code” must be
displayed.
3.4.3. Thabo is a taxi driver and has 3 approved routes, each with the following cost.
Route A: 11.50
Route B: 9.00
Route C: 7.50
Pensioners get 10% discount and children under the age of 10 years pay only R2 per
trip, regardless the route.
For one passenger, enter the route code and whether this person is a pensioner or
under the age of 10. Ensure that all values entered are valid. Calculate the amount
due and display the output in the format provided by the 3 examples.
The switch statement (also known as switch case statement) evaluates a given expression,
then executes the related statements depending on whether the evaluated expression
satisfies predetermined value. It offers an efficient way for splitting execution to different parts
of code depending on the value of the expression as opposed to the lengthy if-else-if ladder.
The switch statement is a type of selection control structure that is used to decide which blocks
of statements to run based on the value of an expression. Inside a switch statement, case
represent the value of switch, and therefore the expression being switched on is evaluated
against the case.
switch(expression)
{
case x:
// statement 1; code block
break;
case y:
//statement 2; code block
break;
default:
//statement 3 code block
}
21
The C++ switch statement executes according to the following rules:
• expression that will evaluate into an integer value (i.e.: int, char, bool, etc.)
• case keyword that represents a possible value of the expression
• break keyword statement to denote an immediate exit of a switch structure.
• default keyword – an optional statement that presents some code to execute in the
event of a no case match. To avoid the break keyword under the default statement,
default statement must be placed as the switch block's last statement.
• If the switch structure has no default and if the value of the expression does not match
any of the case values, the entire switch statement is skipped.
Figure 3.8 illustrate the flow of processes on a generic switch statement syntax.
22
Step 1: Draw a flowchart (Re-design Figure 3.7 to follow the flow of a switch statement)
23
Step 2: A complete C++ program using a switch statement.
24
Example 2 on switch statement:
Problem statement:
Write an algorithm that will read two numbers and an integer code. The value of the integer
code should be 1, 2, 3 or 4. If the value of the code is 1, calculate the sum of the two numbers.
If the code is 2, compute the difference of the two numbers (first minus second). If the code is
3, compute the product of the two numbers. If the code is 4, and the second number is not
zero, compute the quotient (first divided by second). If the code is not equal to 1, 2, 3 or 4,
display an error message.
25
Review Activity 3.5:
3.5.1. Rewrite the programs in exercises 3.4.2 and 3.4.3 using a switch statement:
3.5.2. Design a C++ program that will prompt for and enter the price of an article and a
discount code. Calculate a discount according to the discount code and display the
original price on the screen as well as the discount amount and the discounted price.
The discount code and accompanying discount rate is as follows:
H 50%
F 40%
T 33%
Q 25%
Z 0%
Table 3. 10: Discount table for activity 3.5.1
If the discount code is Z, the words “No discount” are to be printed on the screen. If
the discount code is neither of the above, the words “Invalid discount code” must be
displayed.
3.5.3. Thabo is a taxi driver and has 3 approved routes, each with the following cost.
Route A: 11.50
Route B: 9.00
Route C: 7.50
Pensioners get 10% discount and children under the age of 10 years pay only R2 per
trip, regardless the route.
26
For one passenger, enter the route code and whether this person is a pensioner or
under the age of 10. Ensure that all values entered are valid. Calculate the amount
due and display the output in the format provided by the 3 examples.
27
ITERATION CONTROL STRUCTURE
Iteration control structure (also known as a loop) allows a statement or block statements to
continually execute until a condition is met. In this case, condition is any relational expression;
that is any expression that result in true or false. An iterative structure is used to shorten code,
speed up program execution, use up less memory, and minimize coding time. Therefore, a
program that contains an iteration control structure will run statement or block of code until the
program achieves the desired state. Three different iteration statement types can be used in
C++ are depicted in Figure 3.11.
A fixed-counter, also known as counter-controlled loop is used when the programmer knows
exact number of times to a statement or block of code should be repeated. A standard
programming practice to create a fixed-counter loop is by using a for-loop statement. The
basic syntax of a for-loop is as follows:
28
//Executing block
for (initial statement; loop condition; update statement)
{
statement 1;
statement 2;
.
.
statement n;
}
In C++, for is a reserved word. The initial statement, loop condition, and update statement
enclosed within the parentheses control the body of the for statement.
The initial statement inside the for-loop should be replaced by counter/index variable.
Normally the counter variable is declared and initialized inside the parentheses of the for-loop
header.
for(int item = 0; ;)
The loop condition inside the for-loop is created using any relational/Boolean expression. If
this expression is equals to anything other than zero (0), the loop will repeat the instruction
inside its body. If the loop condition is initialized to false, the loop body will not execute.
The update statement inside the for-loop is used to alter the counter/index variable to affect
the loop condition statement. Usually it is created using increment (++), decrement (--) or
accumulation (+=, -=, …) statement.
• The initial statement executes once during the first execution of the loop. The initial
statement usually initializes the control variable or index variable.
• The loop condition is evaluated. If the loop condition evaluates to true:
29
o The for-loop statement/body will execute.
o Then the update statement (the third expression in the parentheses) will
execute.
o Repeat Step 2 until the loop condition evaluates to false.
Try-it out
First read the C++ syntax to create a for-loop, the follow the flowchart in Figure 3.13 to create
an application that uses a for-loop to display consecutive integers from 5 to 12.
• Note that the initial statement, i = 5;, initializes the int variable i to 5.
• Then, the loop condition, i <= 12, is evaluated. For example: 5 <= 12 is equals to
true, then outputs 5 will be displayed and a whitespace.
• Then, during the first execution of the for-loop, the update statement, i++;, executes,
which sets the value of i to 6.
Once again, the loop condition is evaluated, which is still true, and so on. When i becomes
13, the loop condition evaluates to false, which then result in the for-loop terminating.
30
Possible solution for the try-it out activity
int i = 5;
for (; i <= 12; )
{
cout<< i << “ ”;
i = i + 1;
}
31
Example: Interactive for-loop:
C++ program
Try-it out
a) Includes statements that will determine and display the highest and lowest testScore
b) Include statements that will count and display the number of testScore above 50
Nested for-loops
Nested loops are loops that are contained within other loops. As an illustration, imagine that
we wish to loop through each day of a week for four weeks:
• First, we can create a for-loop that iterates four times (for three weeks), the outer-loop.
32
• Then, within the outer-loop, we create a second for-loop that iterates seven times (for
seven days), inner-loop.
Figure 3.15 shows the flowchart of the nested for-loops example which we identified earlier.
33
Review Activity 3.6:
34
Figure 3.17: flowchart of exercise 3.6.2
3.6.3. Complete the source code using for-loops to perform the following steps:
a) Output all odd numbers between firstNum and secondNum.
b) Output the sum of all even numbers between firstNum and secondNum.
c) Output the numbers and their squares between 1 and 10.
d) Output the sum of the square of the odd numbers between firstNum and secondNum.
e) Output all uppercase letters (A - Z).
35
N.B: Only use variables which are provided.
#include <iostream>
#include <iomanip>
int main()
{
//declare all variables
int firstNum, secondNum;
int sumEven = 0;
int sumSquareOdd = 0;
char chCounter;
int counter;
cout << "Odd integers between " << firstNum << " and "
<< secondNum << " are: " << endl;
//DISPLAY ODD INTEGERS
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
cout << endl;
//Output the sum of all even numbers between firstNum and secondNum
if (firstNum % 2 == 0)
counter = firstNum;
else
counter = firstNum + 1;
//CALCULATE AND DISPLAY SUM OF EVEN INTEGERS
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
36
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
return 0;
}
3.6.4. Write a C++ program that print out a multiplication table, see Figure 3.17:
3.6.5. Create a C++ application that determine if a number is prime or not. NB: A prime is a
number that is divisible by 1 and itself.
3.6.6. Write C++ programs that draw the following patterns, using nested for statements:
37
3.6.6.1. *
**
***
****
*****
******
3.6.6.2. #*#*#
#*#*
#*#
#*
#
Sentinel-controlled loops are employed when the exact number of loop iterations is unknown,
as contrast to counter-control loops. Sentinel value is a special value used to start and
terminate a loop. In order to terminate a loop, a sentinel value is often selected from a list of
invalid values. For example, a program that inputs an unknown number of test scores may
use -1 or 999 as the sentinel. Like counter-controlled loop, sentinel-controlled loop’s
execution is terminated based on the test condition, which is denoted by a relational/Boolean
expression. The while-loop and do...while-loop are recommended in programming when
constructing sentinel-controlled loops.
38
Execution of a while-loop:
• The keyword while tells the computer to create an iteration control structure.
• The condition must be a Boolean expression, which is an expression that evaluates to
either true or false. The expression can contain variables, constants, arithmetic
operators, relational operators, and logical operators.
• The parentheses that surround the condition must always be included, similar to the if
statement.
• Besides providing the condition, the programmer must also provide the loop’s body
statements, which are the statements to be processed when the condition evaluates
to true. If more than one statement needs to be processed, the statements must be
entered as a statement block by enclosing them in a set of braces ({}).
• The body must include a statement that will alter the value of the variable used to
construct the condition to avoid an infinite or endless loop. A loop whose instructions
are processed indefinitely is referred to as either an endless loop or an infinite loop.
Let’s look at an example of the program that calculate the sum of even numbers in Figure
3.18:
39
Figure 3.18: flowchart of a while-loop example
40
Review Activity 3.7:
3.7.2. Write a C++ application that accepts an unknown number of characters as inputs. A
sentinel value of ‘#’ should be used to stop entering characters and the program must
then determine and show the total number of vowels and total number of digits entered.
3.7.3. An unknown number of students have written a test; therefore, you are required to
write an application that will:
• Receive the student number, name and test mark as input. The program must
use the value “99999” to stop entering input. The test mark can be integer
value from 0 to 100, therefore, show an error message for any invalid test
mark and initialize it to zero.
• Calculate the test average.
• Determine the student with the highest mark.
• Show the test average with a proper legend.
• Show the student number, name and test mark of the student with the highest
test mark.
A do…while loop is a sentinel-controlled loop that executes the body of the loop at least once
before it evaluate its condition. This type of a loop is referred to as a post-test loop. The
syntax of the do...while-loop is:
do
{
statement..1;
statement..2;
.
.
statement..n;
} while (condition);
41
Key features of do..while loop:
The do…while loop is commonly used when validating user input, especially in an application
where a valid input is mandatory to proceed to the next process. Look at the example below:
Take a look at the sample program below, which includes a loop that receives as input: the
student number, results of five class tests, and exam mark for each student. The program
calculates predicate for each student as the average of the five tests, and final mark is
calculated as the average of predicate and exam mark. The student with the highest final
grade is then identified, and the total class average is computed and shown prior to the
program's completion:
42
43
Review Activity 3.8:
44
Other C++ Loop Control Statements
C++ support the keywords such as break, continue and goto to alter the normal execution
flow of a loop.
break statement:
The break statement provides an early exit of closest iteration control structure (for, while or
do while). When the break statement executes, the program continues to execute the first
statement that follows the exited loop structure. For example, the code snippet below will
terminate the infinite while-loop when a negative value or zero is entered:
continue statement:
The continue statement is used in an iteration control structure to skip the remaining
statements in the loop and proceeds with the next iteration of the loop.
When the continue statement is encountered inside a for, while or a do…while, the remaining
statements inside the body of the loop are skipped and the execution moves to next iteration.
For example, the program below will continue to prompt the user when a negative value or
zero is entered, if negative or zero is entered, statement in line 12 and 13 are skipped:
45
goto statement:
The goto statement is used to jumps to a specified section inside the function. The use of this
keyword is discouraged as it may complicate the standard flow of a program. In the code
snippet below, whenever the goto ERROR line execute, the program jumps to line 24 whereby
an ERROR label is defined:
Summary
In this chapter, selection and iteration control structures were covered. Firstly, relational and
logical operators were introduced as well as how they are evaluated when used inside a mixed
expression. A selection control structure was created within a program using the if, if-else,
nested if, and switch statements. A control structure for iterations was created using the for-
loop, while-loop, and do...while-loop structures. Finally, the break, continue, and goto
statements were used to demonstrate how a normal flow of a program that contains iteration
control structure can be altered.
46
ADDITIONAL RESOURCES FROM RECOMMENDED BOOK
A First Book of C++
Fourth edition
By Gary J. Bronson
Published by Pearson
In addition to these notes, study the following pages on CHAPTER 4 inside the prescribed
textbook.
47