C++/Codeblock Questions and Activities

C++/Codeblock Questions and Activities

C++ skill required. Codeblocks program required. I need the questions that are on chapters 2-6 to be answered. They are short questions… The answers must be copy and
pasted // written in a Word Document. Questions are on PDF page — Chapter 2: Page 20. Chapter 3: Page 30. Chapter 4: Page 42. Chapter 5: Page 54. Chapter 6: Page 60.
Last updated: 30 May 2014
Acknowledgements
Contributor: Buddhima De Silva
© UWSCollege Pty Ltd
UWSCollege
Nirimba Education Precinct
Eastern Road
Quakers Hill NSW 2763
Postal address:
PO BOX 224
Quakers Hill NSW 2763
Phone: (02) 9852,4488
Fax: (02) 9852,4480
Warning: Aboriginal and Torres Strait Islander readers are warned
that the [ibook title / workbook] may contain and or refer to websites
that use the names or images of Aboriginal and/or Torres Strait
Islander people who may have passed away.
Disclaimer
If you buy or use this publication you should understand clearly that it
has been produced solely for learning purposes. While the author and
the UWSCollege Pty Ltd have made every effort to ensure that the
material in this publication is accurate and of high quality, you are
expressly advised that you should not rely on the contents of this
publication in order to make decisions having legal, accounting,
property, financial, investment or similar consequences; or for any
purpose other than learning. For any purposes other than learning
you should first obtain the advice of an appropriately qualified
professional. The author and the UWSCollege Pty Ltd disclaim any
liability to any person, whether a student or otherwise, in respect of
anything, and the consequences of anything, done or omitted to be
done by any such person in reliance, whether wholly or partially, on
the whole, or any part of, or omission from, the contents of this
publication.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! ii
COPYRIGHT – UWSCollege 2014
ICONS
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!! iii
INDICATES VIDEO FILE INDICATES OPEN WEB LINK INDICATES DOCUMENT TO
OPEN
INDICATES AUDIO FILE INDICATES STUDENT
INSTRUCTION
INDICATES STUDENT READING
INDICATES STUDENT ACTIVITY
INDICATES NOTE-MAKING
FILE
READER CLOUD (WWW.READERCLOUD.COM)
Save your eBook data to the Reader Cloud
Save any data entered into an eBook and access it online. Any changes made online will also be
sync’d with the book on any device. Example data includes personal settings, quiz answers,
achievements, photos, notes entered and game scores.
Login to your eBook data from any device
Access your saved data from any device that has a copy of the eBook. Build up a profile to make
the book your own.
Example applications can include students sharing devices in a school and siblings sharing a book
at home.
Interact with other eBook readers
Connect with family and friends who have the same eBook. Share data through social sites and
communicate from inside the book itself. Example scenarios can include reader chat, photos,
document, notes and other social networking tools.
VUWS SITE
vUWS is the e-learning system at the university. This is known as vUWS (pronounced “views”) and
is where you can access learning materials and participate in online activities, individually or with
your peers. All units have a vUWS presence and you can find important information on each of
your unit or course sites.
Please explore the “vUWS Information for Students” and “vUWS Information for Staff” sites listed
under “My vUWS Sites” after you have logged in for support in using vUWS.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! iv
Reader Cloud
Create a reader account
to store your data from
the iBook on a cloud
account.
vUWS site
Blackboard App
CHAPTER 1
Introduction to programming
Chapter overview
In this chapter students will learn about:
recent developments in engineering
computer systems
programs and programming languages
structured programming, and
the program development process.
Suggested chapter duration
Six (6) hours
Target learning outcomes
At the completion of this chapter, students should be able
to:
1. define terms such as structured programming,
variables, constants, control structures, modularisation,
cohesion, coupling, function, procedures, parameters
and arguments, and
2. illustrate the steps involved in program development.
Reading resources
UWSCollege 2014, Introductory Programming
Workbook, UWSCollege, Sydney.
Introductory Programming vUWS site.
Chapter revisions tools
Student checklist widget
Revision questions widget
iPad apps to download
Blackboard
DropBox
UWSCollege Pty Ltd! ! !!!!!!!!!!!!!!!!!!!! 5
Chapter 1: Introduction to programming: Study tools
FIGURE 1.2 Chapter 1:
Introduction to
programming notes
Use this widget to create
study notes for this
chapter.
FIGURE 1.3 Chapter 1:
Introduction to
programming feedback
Provide your tutor with
feedback about your
knowledge and
understanding of the
chapter.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 6
FIGURE 1.1 Chapter 1:
Introduction to
programming checklist
Use this checklist to
prepare for assessments.
SECTION 1
Recent developments in engineering
Developments in digital computer technology played a
major role in the greatest engineering achievements of
the 20th century. Every engineering discipline from
space engineering to mining engineering has benefited
from using computers. The following video features
some of the engineering achievements of the 20th
century.
Today, computers have replaced rulers, pencils, sketch
books and books. Computers have become an
essential tool for engineers to office workers. The
following blog explains why engineers and scientists
need to learn programming skills: http://bit.ly/UxwLpV/
Student activity 1
List the benefits of learning
programming skills.
Some of the strengths of
computers include the ability to
perform complex calculations
fast and accurate, the ability to
analyse data and the ability to
model data. In this chapter we
are learning about computer
systems, programs and the
programming process.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 7
FIGURE 1.4
Student activity 1
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 8
FIGURE 1.5 Chapter 1:
The greatest
engineering
achievements of the
20th century: YouTube
http://bit.ly/1ym9oz9
FIGURE 1.6 Chapter 1:
The greatest
engineering
achievements of the
20th century: QR code
FIGURE 1.7 Computer
Viewed 30 December 3013. <www.downstech.com.au>.
SECTION 2
Computer systems
This section explains the major components of a computer system — computer hardware and computer software.
Diagram 1.1 Components of a computer
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 9
FIGURE 1.8 Computer
architecture: YouTube
http://www.youtube.com/watch?
v=HEjPop-aK_w
FIGURE 1.9 Computer
architecture: QR code
Source: Gaddis, T. 2012, Starting out with C++: From control structures
through objects, Pearson Addison-Wesley, Boston.
Computer hardware
The physical components of a computer together are called
computer hardware. The major parts of hardware are the
central processing unit (CPU), main memory, secondary
storage devices, input devices and output devices.
Diagram 1.1 shows typical hardware components of a
computer system.
Central processing unit
The central processing unit (CPU) is the brain of the
computer. The CPU’s responsibility is to fetch instructions
and to execute the instruction to produce a result.
However, all these instructions need to be in binary code
(0s and 1s). The CPU is comprised of a control unit (CU)
and an arithmetic and logic unit (ALU).
The control unit is responsible for retrieving and decoding
program instructions and coordinating activities of all other
parts of the computer by sending control signals.
The arithmetic and logic unit performs mathematical
operations.
Main memory
The main memory is used to store the instructions given in
the programs, the data input given to the program while it
is running and the data produced by the program. The main
memory is also known as random access memory or RAM.
Main memory is volatile. In other words, when the power is
switched off, it will be deleted.
Secondary storage
If we want to store data permanently, we need to store it in
a secondary storage device such as a disk drive, a USB
drive, portable disk, etc. These are also called non-volatile
memory devices.
Input devices
We use input devices to input data and instructions into the
computer. There are different types of input devices such
as keyboard, mouse, scanner, digital camera, joy sticks and
microphones.
Output devices
We use output devices to output data from the computer.
There are many different output devices such as monitors,
printers and speakers.
Student activity 2
UWSCollege is planning a
computer gaming lab for
Nirimba campus. The
gaming lab will include
educational games that
can support the learning of
engineering, ICT and
science students. Your job
is to design the computer
gaming lab, and write a
hardware specification for
the gaming lab.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 10
FIGURE 1.10 Student
activity 2
Computer software
Computer software refers to the instructions and
commands that we want the computer to execute. There
are two categories of software — the operating system and
application software.
Operating system
The operating system is responsible for coordinating and
controlling the hardware devices and software inside the
computer. Some of the popular operating systems are
Microsoft Windows 7, Microsoft Windows XP, Vista, Apple
OS X, Apple iOS and Linux.
Application software
The programs that people use to accomplish a specific
purpose such as writing a document or sending an email
are called application software. Application software used
by engineers include:
Microsoft Office applications such as Word,
PowerPoint, Excel and Project
design applications such as AutoCAD and Civil 3D, and
mathematical computation applications such as
MATLAB and Mathematica.
Student activity 3
Write a software specification for
the gaming lab for Nirimba
campus.
Prepare a report on software
applications used by engineering
professionals. You can use as
many different sources to
research on this including the
internet, engineering magazines,
interviewing engineering
professionals, etc.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 11
FIGURE 1.11
Student activity 3
SECTION 3
Programs and programming languages
A program is a set of instructions that the computer follows to perform a task. They mainly belong to two categories called
low level programming languages and high level programming languages.
Low level programming language
A low level language mostly deals with direct hardware interaction, and thus uses program device drivers to access the
hardware. A program written in a low level language is generally hardware specific and needs to run on the same hardware
and software configuration all the time. These programs execute faster than a program written using high level programming
language. However, such programs are hard to read and understand by people. Assembly language is an example of a low
level programming language.
High level programming language
High level languages are easier to read and understand by people
when compared to low level programming languages. Such
programs are portable across different hardware platforms. Most of
the high level programming languages are purpose built. For
example, if we want to analyse some data we may develop a
MATLAB program. However, if we want to program a micro
controller we may consider a C++ program. Some of the most
common programming languages are shown in Diagram 1.2.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 12
Learning activity 4
List common programming languages used by engineers in your intended field of engineering
study. You may research using the internet, discuss with your teachers, etc.
Each language has different syntax (grammar rules). In this unit we are going to learn C++
programming. More specifically, we should be able to write C++ programs that read user input
from a keyboard, perform calculations and display data on the computer’s screen. However, all
different programming languages have common elements. Table 1.1 lists common
programming language elements. We will learn about C++ programming language elements in
detail in further chapters.
TABLE 1.1 Common language elements in C++
Language
element Description
Key words
Words that have a special meaning in a given programming
language and used for a specific purpose. They are also
called reserved words.
Identifiers Words used by programmers to refer to variables or
program routines.
Syntax Grammar rules that need to be followed when writing a
program.
Operators Operators perform operations such as addition (+),
subtraction (-), etc
Punctuation
Punctuation marks such as commas (,) which are used to
separate a list of items, or semi-colons (;) that end a
statement.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 13
FIGURE 1.12 Student
activity 4
SECTION 4
Structured programming
Structured programs involve using different
programming structures to organise the solution to a
problem. A simple structure is usually defined as being
a sequence, selection or a repetition.
A sequence structure contains a set of
statements that are performed one after another.
We will learn to design and write sequential
programs in chapters 2 and 3.
A selection structure contains a conditional
statement and, if it is true, one set of statements
will be performed and, if it is false, another set of
statements will be performed. We will learn to
design and write programs with selection
structures in chapter 4.
Repetition structure contains a set of statements
which will be repeated as long as the conditional
statement is true. We will learn to design and write
programs with repetition structures in chapter 5.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 14
SECTION 5
Program development process
Any engineering design process includes key process steps such as analyse,
design, building and testing. Similarly, to develop a program we will follow
the process outlined below. It is important to follow a process, so that we
can develop a successful program. We will learn about how to apply program
development processes to develop different programs using structured
theorem in the chapters following.
To develop a program the following steps should be completed:
1. Analyse the problem
2. Design the solution program
3. Test the design
4. Code the program in C++
5. Generate the executable code from your program
6. Test the program
7. Document and maintain the program.
Analyse the problem
To build the right solution to the problem, we need to understand the
problem correctly. For this purpose, we should identify the input information
that can be used in the solution program and expected output information need to be produced by the program. We may
sometimes draw screens of our programs to understand how our solution should appear to the user.
Design the solution
In design, we apply our knowledge in structured programming to design and build a solution program for the problem we
analysed. First, we need to identify the high level steps that can be followed to solve the program. Then we will work out
detailed steps which could be used to easily convert the design into a program using a chosen programming language.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 15
We will learn two approaches to design a simple program,
including pseudocode and flowcharts. We will learn how to
write pseudocode and draw flowcharts in chapters 3, 4 and
5. For a basic program, we can use simple English
statements to explain our design. We will learn about the
top-down modular approach to develop a solution for
complex programming in chapter 6. The detailed design or
step-by-step solution design is also known as algorithm.
Test the design
First we will design some input test data to test our design
along with expected outputs. If we are replacing a manual
calculation by our program, we can work out expected
outputs for chosen input data by working out a hand
example. Next we walk through our algorithm with input
test data and produce the output. We compare these
outputs with expected outputs to test the correctness of
the design. This process is also called “Desk Checking”. If
the outputs from the design are different to the expected
outputs, then we assume there are errors in the algorithm.
Such errors are called logic errors. We should correct such
errors and desk check the design again before coding.
Code the program
Once we get the design right, then we can write the
program in our chosen programming language. This
process is also known as coding. In this unit we will learn
to write programs in C++ language. The program we have
written is also called a source file. To write our programs we
use an Integrated Development Environment (IDE). IDE
consists of different tools that can support the process of
generating an executable file from the source file. An editor
allows you to write the code, a compiler will convert our
program into a machine readable format which can be
understood and followed by the computer, and a debugger
can help us to correct any compiling errors, etc. We will use
an IDE called Code::Blocks in this unit. We will write our
program in Code::Blocks editor and save it. Then we will
compile the program. This process is explained in section
6.
Generate the executable code from your program
Once coding is completed, we compile and link the
program using tools in our IDE to generate machine
readable code (binary code). This is generally referred to as
the compiling process. We need to correct any errors found
in the compilation process. Such errors are called syntax
errors or compiling errors. When we fix all syntax errors our
program is ready to execute or run.
Test the program
We run our program with input test data. We test the
output. Even though there maybe no logic errors or
compiling errors, we may encounter errors in our program.
Such errors are called run time errors. Run time errors are
errors that occur due to the limitation of computing power.
In general, we may need to correct any errors found in our
program in this step.
When we run the program, the executable code of our
program will be loaded in the computer’s memory. We can
enter the input data and have the computer process them
to produce the output.
Document and maintain the program
We should update any design document to reflect any
changes made during the program development process.
Also it is good programming practice to add comments to
explain the program.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 16
SECTION 6
Integrated development environment
An integrated development environment (IDE) consists of
different tools that can support the process of generating
an executable file from the source file. These tools include
an editor to write the code, a compiler that converts the
program into a machine readable format that can be
understood and followed by a computer, a debugger that
helps us correct any compiling errors. These are the steps
we will follow in an IDE to run our program.
Step 1: Programmer will write the source code or the
program (.cpp file) using editor.
Then if we choose the built and run option in our IDE, the
computer will perform the following steps.
Step 2: The pre-processor will modify the lines in the
source code starting with # in some way. This step will
be briefly explained in chapter 2. The pre-processor
will also remove the comments in the program.
Step 3: Compile the pre-processed source codes into binary code which is known as object codes (file with .obj, .o
extension).
Step 4: Link the compiled object codes with other object codes and the library object codes (.lib, .a) to produce the
executable code (.exe). Library files are explained in detail in chapter 2.
Step 5: Load the executable code into computer’s main memory.
Step 6: Run the executable code.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 17
SECTION 7
Code::Blocks
We will use a free open source IDE called
Code::Blocks in this unit.
You can download Code::Blocks from the
following website: www.codeblocks.org
The links on the following page take you to a
video which shows how to install and test Code::Blocks IDE.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 18
FIGURE 1.13 Code::Blocks web link
FIGURE 1.14 How to
install and test
Code::Blocks: YouTube
FIGURE 1.15 How to
install and test
Code::Blocks: QR
Code
These links will show you how to install and test Code::Blocks:
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 19
SECTION 8
End of chapter review questions
Answer the end of chapter review questions on
the following page.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 20
FIGURE 1.16 End of
chapter review questions
1. Explain the different parts of a computer system.
2. Discuss the importance of learning programming for engineers.
3. Briefly explain the structured theorem.
4. Why is it important to follow a process in program development?
5. What is an integrated development environment? Identify different components in Code::Blocks IDE.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 21
CHAPTER 2
Understanding a simple C++ program
Chapter overview
In this chapter students will learn about:
the parts of a C++ program
literals
variables
identifiers
data types
variable initialisation
constants
comments
standard output, and
best programming practices.
Suggested chapter duration
Six (6) hours
Target learning outcomes
At the completion of this chapter, students should be able
to code, debug and test programs in C++ using an
Integrated Development Environment (IDE).
Reading resources
UWSCollege 2014, Introductory Programming
Workbook, UWSCollege, Sydney.
Introductory Programming vUWS site.
UWSCollege Pty Ltd! ! !!!!!!!!!!!!!!!!!!!! 22
SECTION 1
The parts of a C++ program
In this chapter, we learn the basic structure of
a simple C++ program. To learn the basic
structure, we are going to analyse the
program given below. The purpose of this
simple program is to display the text “Hello
World” in the console window. The output of
this program is noted below in the program.
(Please note that the line numbers shown
with the code are not a part of the program.)
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 23
Line 1: #include <iostream>
Any line that starts with a hash sign (#) is called a
preprocessor directive. In other words, the lines starting
with a # sign specify instructions to the preprocessor. In
this program, line 1 instructs the preprocessor to include an
iostream file and a C++ library file in the program before the
program is compiled. The iostream file contains the code
required to execute the cout statement in line 6
successfully. Usually any library file required in our
programs are added using #include. The preprocessor
automatically adds content from the specified file, so that
the program can use those codes.
(Note that there is no semicolon (;) at the end of
preprocessor directives.)
Line 2: using namespace std;
A namespace is like an inventory which keeps a record of
all the programming entities such as classes, objects and
functions. The namespace “std” organises the names of all
the programming entities used in the standard library. Line
2 declares that this program will access entities in the
namespace “std”. This line helps to locate the cout object
used in the program in line 6.
Line 4: int main ()
This line marks the beginning of the main function. Every C
++ program must contain a main function. When executed,
it starts executing the C++ statements within the main
function. In Chapter 6, we will learn about functions in
detail.
Lines 5 and 9: {}
Every C++ function opens with a left curly bracket ({) and
ends with a right curly bracket (}). Curly brackets are used
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 24
FIGURE 2.12 Program 2.1: HelloWorld.cpp FIGURE 2.13 Program 2.1: output console window
to group a block of C++ statements. We must close every curly bracket that we open.
Line 6: cout << “Hello World!”;
This is the first C++ statement executed in our program. Every C++ statement ends with a semicolon (;). This statement
displays the words “Hello World” in the console window. We will learn about cout statements in detail later in this chapter.
Line 7: system (“pause”);
This line will pause the console window until a key is pressed. We need this line to see our program output in the console
window, otherwise the program will be executed and close the console window and we would not be able to see the output.
This line is only required because we use the Bloodshed Dev C++ environment.
Line 8: return 0;
The return statement in the main function ends the execution of the program. This line sends zero (0) to the operating system
and flags that the program executed successfully.
Note: In some C++ IDEs you may have to use the following statement to see the console output, otherwise the program will
be executed and the console window closed and we would not be able to see the output.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 25
http://bit.ly/1r55MN8
FIGURE 2.14 Chapter 2,
Section 1: Structure of a
C++ program. Weblink
FIGURE 2.15 Chapter 2,
Section 1: Structure of
a C++ program – QR
code. Weblink
Student activity 1
Complete the blanks below by explaining the use of each
special character in a simple C++ program.
Character Name When/where did we
see it?
# hash sign
< > Open/close
brackets
( ) Open/close
parentheses
{ } Open/close
curly bracket
; Semicolon
Student activity 2
Use arrows to indicate the
correct order of the lines in
the code puzzle.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 26
FIGURE 2.16 Student
activity 1
FIGURE 2.18 Student
activity 2
FIGURE 2.17 Code puzzle
SECTION 2
Literals, identifiers, variables and constants
Literals and variables
A program can use two different types of data — literals and variables.
Literals are data which are hard coded in a program at the time it was
written. Variables are data which are stored in the computer’s memory
while a program is running.
Literals
We can hard code different types of data such as numbers, texts and
keyboard characters. They are called literals. Table 2.1 specifies different
types of literals and examples for each type.
Table 2.1 Different types of literals
Literal type Description Examples
Integer Whole numbers 123, -45
Floating point Fractional numbers 1.34, -432.2
String Texts enclosed with double
quotation marks (“ ”)
“Hello World”, “I love
Programming”
Character Letters enclosed with single
quotation marks (‘ ’) A’, ‘$’
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 27
Figure 2.19 (Program 2.2) contains a string literal “The
unit code for Introductory Programming is” and an
integer literal 900084.
Variables
Variables store data used by the program in the
computer’s random access memory. Every variable has
a name (which is called an identifier) and a type which
specifies the data which can be represented by that
variable such as integers (whole numbers) or floatingpoint
numbers (fractional numbers). Later in this chapter
we will discuss identifiers and data types in detail. We
must define any variables used in the program before
using it. The program will allocate a suitable memory
space in the random access memory for the variable
depending on its type. Table 2.2 gives a few examples
of variable definitions. We can define more than one
variable of the same type in a single statement by
separating with commas (,). The third row in Table 2.3
defines two integer variables.
Identifiers
An identifier is a programmer-defined name for some
parts of a program such as variables and functions.
Usually the identifiers should relate to the purpose of
the variable or the function. We need to adhere to the
following rules when defining variables.
Rule 1: We cannot use C++ key words or reserved words as identifiers. Key words have a special meaning in C++
programming language. All C++ key words are listed in Figure 2.21.
Rule 2: The first character of an identifier must be an alphabetic character (lower case or upper case) or an underscore ( _ ).
Rule 3: We can use alphabetic characters (lower case or upper case), numbers, or underscore characters after the first
character.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 28
FIGURE 2.19 Program 2.2: unitDetails.cpp
FIGURE 2.20 Program 2.2: Output console window
TABLE 2.2 Examples of variable definitions
Variable definition Variable type Variable(s) name
int distance; Int distance
float acceleration; Float acceleration
int weight1, weight2; Int weight1,weight2
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 29
FIGURE 2.21 C++ KeyWords (Gaddis, 2012)
It is best programming practice to use meaningful
identifiers. In other words, variables should be selfdescriptive
so that the purpose of the variable or the
function can be understood by the identifier (name),
eg “force” is a better variable name than the variable
name “f” to explain the force of an object.
If a variable name consists of more than one word we can
either use an underscore (“_”) to separate the variable
names or use a capital letter to begin each word after the
first word to improve the readability:
eg double total_force;
double totalForce;
C++ is a case sensitive language. Therefore, identifiers
totalforce and totalForce are identified as two variables.
Every time we refer to a variable in a program we must type
in the variable name in the same case as we defined it. If it
is a long variable name, the best programming practice
would be to copy and paste it rather than type it in the
program, to avoid syntax errors.
Data types
Computers can only work with ones (1) and zeros (0).
However, in the real world we deal with numbers, texts, etc.
High level programs such as C++ allow us to work with
data such as numeric data and texts. This data is internally
represented in ones and zeros. However, we need to use
appropriate data types in the variable definitions when
defining the data.
Integer data types
There are six different integer data types we can use to
store whole numbers. The size of the variable and the
range of numbers that can be stored at a variable’s
memory location are varied depending on the operating
system. Table 2.3 shows the size and range of different
integer data types typical on many computer systems.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 30
http://bit.ly/Ukk7KW
FIGURE 2.22 YouTube:
C++ Console lesson 4:
Basic data types
FIGURE 2.23 C++
Console lesson 4:
Basic data types:QR
code
Floating point data types
TABLE 2.3 Different integer data types (Gaddis, 2012)
Data type Size (bytes) Range
Short 2 -32,768 to +32,767
unsigned short 2 0 to +65,535
Int 4 -2,147,483,648 to +2,147,483,647
unsigned int 4 0 to 4,294,967,295
Long 4 -2,147,483,648 to +2,147,483,647
unsigned long 4 0 to 4,294,967,295
There are three different floating point data types called
float, double and long double which we can use to store
fraction numbers in our programs. Floating point numbers
are represented using E notation. In E notation, floating
point numbers are normalised such that they appear with
one digit before the decimal point. Letter E represents
times ten raised to the power of (which would be written as
“x 10”). The exponent is followed by the letter E. Table 2.4
shows scientific notation and E notation for some floating
point number examples.
TABLE 2.4 E notation (Gaddis, 2012)
Number Scientific notation E notation
123 1.23 × 102 123
25.4 2.54 × 101 25.4
0.0086 8.6 × 10-3 0.0086
We can use float or double data type to store floating point
numbers, depending on the level of accuracy you require in
the data.
Char data type
Char data type is used to refer to keyboard characters in
our program. They are enclosed in single quotation marks (‘
‘). Char data types are stored in the computer’s memory as
small integer values,
eg char user_selection=‘a’;
char first_letter= ‘D’;
Boolean data type
Boolean variables can store one of the two values: true
(represented by 1), or false (represented by 0). In C++,
boolean variables are defined using data type “bool”. We
will learn about the boolean variables in detail in Chapter 4.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 31
TABLE 2.5 Different floating data types
Data type Size Description Range
Float 4 bytes Single
precision
±3.4E-38 and
±3.4E38
Double 8 bytes Double
precision
±1.7E-308 and
±1.7E308
String data type
In C++ we can use string data type to store texts. However, we need to include the library file named string in our program.
#include <string>
String data values should be enclosed in double quotation marks (“ ”) as shown in Figure 2.24 (Program 2.3).
Variable initialisation
We can assign a value to a variable at the same time it is defined,
eg int distance = 500;
Constants
When we have data which only require read access but do not require to update during the execution of the program we
store them as constants. Constants are defined using key word “const”,
eg const double GRAVITY = 9.8;
If you need to change the following program to work out the speed due to gravity at sun, we only need to update one place.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 32
FIGURE 2.24 Program 2.3: string.cpp
Student activity 3
1. Indicate whether each of the following identifiers is
valid or invalid in the “valid?” column. If it is not valid,
write the reason in the appropriate comment cell.
Identifier Valid? Comment
unit_number
unitNumber
unit-number
2. Which of the following are valid variable names?
a. velocity
b. total force
c. force_x_direction
d. y(force)
e. totalForce
f. 1stdistance
g. weight1
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 33
FIGURE 2.25 Program 2.3: Output console window
FIGURE 2.26 Student
activity 3
SECTION 3
Comments
Comments are used to explain our programs or hide an unwanted part of a
program from the compiler. There are two different ways to add comments
in to our programs:
1. single line comments: using two forward slashes (//)
2. multi-line comments: using a forward slash followed by an asterisk (/*)
to begin the comment and asterisk and forward slash (*/) to finish the
comment.
Usually we add a file header to explain the purpose of the program using
multi-line comments as shown in program 2.4.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 34
FIGURE 2.27 Program 2.4: HellowWorld.cpp with file header
SECTION 4
Standard output
We use cout objects in C++ programs to display text
output on the monitor screen, more specifically called
“console window”. In C++, cout objects, in conjunction
with an insertion operator (<<) (which is written as two
less-than signs), can be used to display text on the
console window. The insertion operator inserts the data
given in the statement after it into the screen. The data can
be a literal or a content of a variable, for example:
cout << “Hello”; // displays text Hello World on the
console window.
cout << 2014; // displays number 100 on the
console window.
cout << term; // displays the content of the variable
term.
We can also combine multiple cout statements into a
single statement by separating with insertion operator (<<)
as given below:
cout << “Hello”<< 2014<< term;
The output of both of these example code segments are the same.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 35
http://labor-liber.org/en/gnu-linux/introduction/
input_output – viewed 2 July 2014
If we want to display each output in a separate line, we can use the “endl”
manipulator to start a new line (note that last character in endl is a lowercase L, not the number 1),
eg cout<<”Hello”<<endl
TABLE 2.6 Escape character sequences Escape character sequences Escape character sequences
Escape sequence Name Purpose
\n New line print a new line
\t Tab space Print a tab space
The other way to display a line break is to use new line character (“ \n”). Note that \n needs to be inserted inside double
quotation marks (“ “). Table 2.6 lists a few of the escape character sequences that we can use to format output.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 36
SECTION 5
Best programming practices
It is best programming practice to follow a programming style which improves the readability of the programs we write. This
helps to understand our programs easily. It is important as we may need to refer to our own programs later, or we may need
to share them with others.
Guidelines
1. Comment on your code: we should
explain the purpose of each block of
statements in the program.
2. Use meaningful identifiers: identifiers
should relate to the purpose of the
variable or function.
3. Indent your code and add blank lines:
indent you code when you add a block of
statements.
4. Be consistent: stick to the same coding
style. For example, if you used open curly
brackets in a new line, follow that style
throughout the program.
5. Add a file header in a block comment: a file header is added to explain the purpose of the program, author and dates of
the program. It is good programming practice to add a file header to every program you write.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 37
SECTION 6
End of chapter review questions
End of chapter review questions: Q1
1. Circle the errors in Program 1:
FIGURE 2.28 Program 1
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 38
FIGURE 2.29 End of
chapter review
questions: Q.1
End of chapter review questions: Q2
2. Circle the errors in Program 2:
End of chapter review questions Q3-5
3. Write the output of the following code segment:
4. Write a program which displays your full name in the first line, your favourite app/website in
the second line and what you do with that app/website in the third line.
5. Write a program that displays the following pattern on the console output.
******
****
**
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 39
FIGURE 2.30 End of FIGURE 2.31 Program 2
chapter review
questions: Q2
FIGURE 2.32 End of
chapter review
questions: Q3-5
CHAPTER 3
Arithmetic operators and interactivity
Chapter overview
In this chapter students will learn about:
arithmetic operators
mathematical functions library in C++
designing and coding interactive programs, and
designing and developing interactive programs.
Target learning outcomes
At the completion of this chapter, students should be able
to:
1. solve problems and illustrate solutions using
sequence control structure with flow charts and/or
pseudocode, which are then coded in a 3GL language
such as C++
2. code, debug and test programs in C++ using an
Integrated Development Environment (IDE), and
3. develop a set of input test data and desk check
pseudocode.
Suggested chapter duration
12 hours
Reading resources
UWSCollege 2014, Introductory Programming
Workbook, UWSCollege, Sydney.
Introductory Programming vUWS site.
UWSCollege Pty Ltd! ! !!!!!!!!!!!!!!!!!!!! 40
Chapter 3: Arithmetic operators and interactivity: Study tools
FIGURE 3.1 Chapter 3:
Arithmetic operators and
interactivity: Checklist.
Use this checklist to
prepare for assessments.
FIGURE 3.2 Chapter 3:
Arithmetic operators and
interactivity: Notes.
Use this widget to create
study notes for this
chapter.
FIGURE 3.3 Chapter 3:
Arithmetic operators and
interactivity: Feedback.
Provide your unit tutor
with feedback about your
knowledge and
understanding of the
chapter.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 41
SECTION 1
Arithmetic operators
We can design and write programs to perform arithmetic calculations.
One of the strengths of computers is the ability to perform
calculations quickly and accurately. If you recall, in chapter 1 we learnt
operators as a part of programming language elements.
C++ arithmetic operators
Table 3.1 explains the common arithmetic operators available in C++
with some code examples. You can learn about the complete list of
operators in C++ at http://bit.ly/1dQnRW4.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 42
http://bit.ly/1dQnRW4
FIGURE 3.5 C++
program – Operators:
QR code
FIGURE 3.4 C++
program – Operators:
Web link
TABLE 3.1 Common arithmetic operators
Operator Code example Result
Addition (+)
double temperatureCelcious,
temperatureKelvin=50.0;
temperatureKelvin=
temperatureCelcious+36.5;
temperatureKelvin=86
.5
Subtraction (-)
double temperatureCelcious,
temperatureKelvin;
temperatureCelcious = 100.0;
temperatureCelcious =
temperatureKelvin – 36.5;
temperatureCelcious=
63.5
Multiplication
(*)
int width=5,length=7;
area=width*length; Area=35
Division (/)
int distance=22, time=4;
double speed= distance/time; speed=5
double distance=22, time=4;
double speed= distance/time; speed=5.5
Modulus (%) double distance=22, time=4;
double speed= distance/time; Remainder=1
All operators listed in Table 3.1 need two operands to work
with. The operands can be literals or variables as explained
in chapter 2. The first four operators can work with integer
or fractional operands and resemble what you have learnt
in mathematics. However, there are two types of division
operators which can be applied, depending on the type of
operands. If both operands involved in a division are
integer numbers,“Integer division” will be applied. The
result is the quotient (ie integer part of the result). If at least
one operand is a fractional number, then the result will be
similar to what we learnt in mathematics. The last operator,
modulus (%), can only be applied on integer operands and
gives the remainder value after division.
Student activity 1
Refresh your memory on division at www.mathsisfun.com/
long_division.html.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 43
FIGURE 3.6 Student
activity 1: long division:
Web link
FIGURE 3.7 Student
activity 1: long
division: QR code
http://bit.ly/1a3lJ20
Student activity 2
Assume a, b, c and d are
initialised as below.
int a = 4, b = 7, x;
double c = 2.5, d = 1.75, y;
What is the correct value of
z.
1. x = 5 + 6;
2. x = 5 + a;
3. x = a + b;
4. y = 4.5 + a;
5. y = 3.2 + d;
6. y = c + d;
7. x = b – 1;
8. x = b – a;
9. y = c – d;
10. x = a * b;
11. y = 2 * d;
12. y = c * d;
13. x = b / a;
14. y = c / a;
15. y = 5 / 2;
16. y = 5.0 / 2;
17. y = 5 / 2.0;
18. y = c / d;
19. x = 8 % 3;
20. x = b % a;
Operator precedence
In a C++ program, we can evaluate mathematical
calculations which use more than one operator. However,
C++ applies precedence rules when executing such
expressions.
Parentheses or brackets have the highest precedence,
similar to what we have learnt in mathematics. Note that
parentheses are the only type of brackets allowed in an
arithmetic expression.
Multiplication (*), division ( / ) and modulus (%) are the next
highest precedence level. If they share the same operands,
then it will evaluate from left to right.
Addition (+) and subtraction (-) are in the lowest
precedence level. If they share the same operands, then it
will start evaluating from left to right.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 44
http://bit.ly/1ipqju8
FIGURE 3.10 Precedent
rules: QR code
FIGURE 3.9 Precedent
rules: Web link
FIGURE 3.8 Student
activity 2
When we design programs, we must use brackets
appropriately as required to highlight the precedence. If we
do not use them correctly, it may cause logical errors in
your program.
The complete list of precedence rules in C++ can be found
at http://bit.ly/1ipqju8.
The following video explains the arithmetic operators in
C++.
Student activity 3
Find the correct value of x.
1. int x = 5 + 4 * 2;
2. int x = (5 + 4) * 2;
3. int x = 12 / 5 + 4;
4. int x = 12 – 5 * 2 + 3 ;
5. int x = 15 / (7 – 2);
6. int x = 15 / 7 – 2;
7. int x = 15 % 7 – 2;
8. int x = 15 % (7 – 2);
9. int x = 3 + 4 * 12 – 7 % 3;
10. int x = (3 + 4) *(12 – 7) % 3;
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 45
FIGURE 3.11 Buckys
C++ Programming
tutorials – 7 – Basic
Arithmetic: YouTube
1. FIGURE 3.12 Buckys
C++ Programming
tutorials – 7 – Basic
Arithmetic: QR code
http://bit.ly/1gtdteH
FIGURE 3.13 Student
activity 3
SECTION 2
Mathematical functions library in C++
Often in engineering problem solving we need to perform more calculations,
such as square root, exponentiation, trigonometry, etc. In C++, such useful
operations are defined as functions in cmath library. We must include cmath
library in our program to use these functions. Table 3.2 on the following page
lists some common functions available in cmath library. Refer to the following
document for a complete list of functions supported by cmath library.
FIGURE 3.15 Chapter 3:
Section 2: C++ <cmath>:
Web link
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 46
http://bit.ly/1idccpz
FIGURE 3.14 Chapter
3: Section 2: C++
<cmath>: QR code
TABLE 3.2 Some common functions available in cmath
library
Function
name Description Example
sqrt(x)
Calculates the positive square root
value of x. x must be greater than or
equals to 0.
double y=
sqrt(6);
pow(x,y)
Calculates xy.
If x is negative, y must be an integer.
If x is zero, y must be a positive integer.
double
z=pow(5,3);
abs(x) Calculates the absolute value of
integer x.
int y =
abs(-6);
exp(x) Calculates the ex. (e is natural
logarithmic value, e=2.718282)
double y=
exp(4.5);
log(x) Calculates ln x.
x must be greater than or equals to 0.
double y=
log(43);
log10(x) Calculates log10 x.
double
y=log10(100);
sin(x) Calculates the sine of x.
X is in radians.
double
y=sin(2.3);
cos(x) Calculates the cosine of x.
X is in radians.
double
y=cos(2.3);
tan(x) Calculates the tangent of x.
X is in radians.
double
y=tan(2.3);
Student activity 4
Write a C++ program to
perform following
calculations and display the
results.
1. 73
2. 5 + 3
5.6
3. 4 + 62
4. 9
6
12
+ 7.53+2
5. sin(60 o)
6. sin π
2
7. sin(x) cos(2x) where x = π
8. 2e3
9. 9.8ln 51
10. log 7- 4
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 47
FIGURE 3.16 Student
activity 4
SECTION 3
Design and code interactive programs
So far we have learnt to write simple programs which can be used to perform
calculations and display the output to the user in the console window. In this section
we will learn how to design and code interactive programs where the user can enter
data in to the program using the keyboard while it runs.
When we design an interactive program, first we need to understand the data the
user needs to enter in to the program and the output data of the program. We can
list the inputs and outputs of the program. Every input and output should be
identified using a unique name. This name is used as the variable name with which
we are going to store the data in the program. It is good programming practice to
use meaningful names which reflect the purpose of the variable. We will use a
parallelogram in flow charts to indicate input data and output data. We should
display some explanation of the data that the program is expecting the user to enter
to improve usability. In programming, we call it a prompt. We can use
a cout object to display a prompt in C++ followed by a cin object to
read the data from the user. We need to choose a suitable data type
such as integer, double, etc to store data entered by the user.
Design an interactive program
Pseudocode
Pseudocode can be used to explain the design of our program.
Pseudocode is a structured English text. There is only one entry
point and one exit point which exist in a pseudocode. We use
keywords BEGIN and END to mark the entry and exit points. We use
the keywords DISPLAY and INPUT to mark input and output data of
the program.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 48
FIGURE 3.17
Pseudocodes: Web link
FIGURE 3.18
Pseudocodes: QR
code
http://bit.ly/1iRlytU
Flowcharts
Flowcharts can be used to represent the design of the program visually. To design a basic interactive program we need to
follow the flowchart elements given in the table below. The following document explains flow charts in detail.
TABLE 3.3 Flowchart elements
Element Notation Description
Start/end Ellipse Represents the start or the end of a program.
Flow of
control
Arrow
with a
head
Represents a flow of control in a program. An arrow coming
from one symbol and ending at another symbol signifies
flow passes to the symbol the arrow points to.
Input/
Output
Parallelo
gram Represents an input or an output.
Process Rectangl
e Represent a process step/ calculation
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 49
FIGURE 3.20
Flowcharts: QR
code
http://bit.ly/1dbVX6Z
FIGURE 3.19
Flowcharts: Web
link
Program interactivity using the cin object
We can use a cin object and stream extraction operator (>>) in a C++ program to store data read from the user into a variable.
We should include an iostream library file into a program using a cin object. The cin object causes the program to wait until
the enter key is pressed. The user needs to enter the data followed by the enter key. The program will store the data
preceding the enter key in to the variable. It automatically converts the data entered on the keyboard in to the data type of the
variable. The following program example shows for cin object.
Program 3.1: readData.cpp
We have used a cin object to read a single piece of data in to one variable in Program 3.1. If we want to read multiple data for
a program we have to use multiple cin statements as shown in Program 3.2. Instead, we can also read multiple data using a
single cin statement as shown in Program 3.3. In that case, the user needs to press the space key or the enter key to
separate data. After the last piece of data the user needs to press enter key.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 50
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 51
FIGURE 3.21 Program 3.2: ReadMultipleDataVer1.cpp
FIGURE 3.22 Program 3.2: ReadMultipleDataVer1.cpp
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 52
FIGURE 3.23 Program 3.2: ReadMutipleDataVer2.cpp
FIGURE 3.24 Program 3.2: ReadMutipleDataVer2.cpp
Student activity 5
The following program should ask the user to enter his/her weight in pounds and convert it to
kilograms and display. Write the code where prompted in the following program skeleton.
#include <iostream>
using namespace std;
int main()
{
double poundWeight, kilogramWeight;
//write code here that prompt the user
//to enter his or her weight in pounds and reads
//the input into poundWeight variable.
//Write a C++ statement to convert weight in pounds to weight in kilograms.
//Assume 1kg=2.2 pounds
//write the code here that displays the user’s weight
//in kilogram.
return 0;
}
FIGURE 3.25 Student
activity 5
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 53
SECTION 4
Design and develop basic interactive programs
We will follow the process steps outlined in chapter 1 to
design and write a basic interactive program.
Problem
Design and write a program a program which asks a user
to enter width and length of a rectangle and calculate and
display the area.
Step 1: Analyse the problem
Step 2: Design the program solution
Screen design for the program
This program calculates area of a rectangle.
Enter the width of the rectangle (in cm): 2
Enter the length of the rectangle (in cm): 10
Area of the rectangle is 20 square centimetres.
Pseudocode
BEGIN
1. DISPLAY “This program calculates area of a
rectangle.”
2. DISPLAY “Enter the width of the rectangle (in cm):”
3. INPUT width
4. DISPLAY “Enter the length of the rectangle (in cm):”
5. INPUT length
6. area= width*length
7. INPUT “Area of the rectangle is”, area, “square
centimetres.”
END
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 54
Purpose of the
program
Calculate area of a rectangle using the
values entered
Inputs width, length
Outputs area
Flowchart
Step 4: Test the design
We will use the following test data to test our design and
program.
TABLE 3.4 Test data
Data set 1 Data set 2
Input data
Width 5 2.4
Length 8 3.6
Expected
output
Area 40 8.64
The following two tables shows desk checking table for two
sets of test data.
TABLE 3.5 Data set 1
Line
number Width Length Area Console output
1 This program calculates
area of a rectangle.
2
Enter the width of the
rectangle (in cm):
3 5
4 Enter the length of the
rectangle (in cm):
5 8
6 40
7 Area of the rectangle is
40 square centimetres
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 55
TABLE 3.6 Data set 2
Line
number. Width Length Area Console output
1 This program calculates
area of a rectangle.
2
Enter the width of the
rectangle (in cm):
3 2.4
4 Enter the length of the
rectangle (in cm):
5 3.6
6 8.64
7 Area of the rectangle is 40
square centimetres
Step 5: Write the program
/*
Name : rectArea.cpp
Description: This program asks user to enter
the width and height of a rectangle
and calculate and display the area of a rectangle.
Author : Buddhima De Silva
Date : 30/12/13 05:00
*/
#include <iostream>
using namespace std;
int main()
{
double width,height,area;
cout << “This program calculates area of a rectangle.\n”;
// read width from the user
cout << “Enter the width of the rectangle (in cm):\”;
cin >> width;
// read length from the user
cout << “Enter the length of the rectangle (in cm):\n”;
cin >> length;
// calculate area
area = width * length;
// Display the area of the rectangle
cout << “Area of the rectangle is ” << area
<< ” square centimetres./n”;
return 0;
}
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 56
Step 6: Test the program
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 57
FIGURE 3.26 Test data set 1
FIGURE 3.27 Test data set 2
SECTION 5
End of chapter review questions
Answer the end of chapter review questions on
the following page.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 58
FIGURE 3.28 End of
chapter review questions
Develop some test data and desk check the following given pseudocodes.
1. Design and write a program which asks the user to enter a celsius temperature and convert it to kelvin temperature and
display.
2. Design and write a program in C++ which asks for three test scores. The program should calculate the average test
score and display it.
3. Design and write a program which asks for the radius of a sphere and calculates the area of the surface (area a = 4πr2
where r is the radius).
4. Design and write a program which asks the user to enter a temperature in Celsius and calculate the Fahrenheit
temperature and display it.
5. Design and write a program which asks the user to enter the speed of a vehicle at the beginning of a bridge and at the
end of that bridge. The program should calculate and display the average speed of the vehicle.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 59
CHAPTER 4
Control structures
Chapter overview
In this chapter students will learn about:
relational operators
if control structure
if-else control structure
logical operators
if-else-if control structure
nested if control structure, and
the switch control structure.
Suggested chapter duration
15 hours
Learning outcomes
At the completion of this chapter, students should be able
to:
1. illustrate the steps involved in program development
2. solve problems and illustrate solutions using selection
control structure flowcharts, pseudocode and translate
to C++
3. code, debug and test programs in C++ using an
Integrated Development Environment (IDE), and
4. develop a set of input test data and desk check
pseudocode.
UWSCollege Pty Ltd! ! !!!!!!!!!!!!!!!!!!!! 60
SECTION 1
Introduction to selection control structures
So far, in this unit we have learnt to design and write
sequential programs that can take users’ input, process
it and display an output. Each time we run a sequential
C++ program, every line of code inside the main function
is executed. However, computers are capable of making
decisions based on a given condition and performing
selected task(s). Selection control structures are used to
program “making a selection”. More than one path of
execution exists in a selection program structure. In this
chapter we are going to learn how to design and write
more complex programs using selection control
structures. There are a few different selection control
structures we can use to design and write our programs:
if control structure
if-else control structure
nested if control structure
if-else-if control structure, and
the case control structure.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 61
SECTION 2
Relational operators
Introduction to relational operators
Relational operators are used to compare numbers or
character values. Therefore, relational operators can be
used in a condition to make a decision in a selection
control structure. Numbers or character values can be
variables or literals. When relational operators are used in
an expression, the result will be a true or false value.
Table 4.1 lists the meaning of relational operators and
how they are represented in program design and C++
code.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 62
TABLE 4.1 Relational operators
Meaning Pseudocode C++ syntax
Greater than > >
Less than < <
Greater than or equal to >= >=
Less than or equal to <= <=
Equal to <== <==
Not equal to <> !=
Note
We use two equal signs (==) in program design and C++
to represent “equal to” as one equal sign (=) is used to
assign a value into a variable.
“Not equal to” is represented differently in program
design and C++. The syntaxes of other relational
operators are similar in program design and C++.
For “greater than or equal to” or “less than or equal to”
use an equal sign followed by a greater than (>) or less
than (<) sign.
Student activity 1
Provide a C++ statement for the following pseudocodes,
and give the result for each (True or False value).
Assume x = 5 and y = 7.
The first one has been done for you.
Psuedocode C++ statement Result
a. x > y x>y FALSE
b. x >= y
c. x < 8
d. x <= y
e. x == y
f. x <> y
g. (2 + x) <= y
h. x < (y/2)
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 63
FIGURE 4.7 Student
activity 1
SECTION 3
The if control structure
Introduction to the if control structure
In the simplest form of a selection control structure,
there are two paths of execution. One path contains
some tasks to be performed and the other path
contains no tasks to be performed as shown in Figure
4.8. This type of control structure is used to execute a
statement or a block of statements, if, and only if, a
condition is true. If it is false, a statement or a block of
statements is not executed (ie it is skipped).
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 64
The general format of
pseudocode and C++
code for simple
selection control
structures is given in
Table 4.2. The curly
brackets are optional if
using C++ code in a
case where we have
only one statement in
the body of the if
statement. However, we
must use curly brackets
if we have more than
one statement in the
body of an if statement,
otherwise it can cause
logical errors.
TABLE 4.2 Pseudocode and C++ syntax for if control structure
Pseudocode C++ syntax
IF condition THEN
Block of statements
ENDIF
if (condition)
{
Statement1;
Statement2;
………………..
…………………..
}
Program design and C++ code
This section illustrates how if control structures can be
used in problem solving with sample pseudocode,
flowchart, program and program outputs. Since there are
two paths of execution which exist in a program in if control
structures, we need at least two data sets to test such a
program.
Worked example
Problem
Design and develop a program which asks the user to enter
the speed of a car in km/h. If the speed of the car is greater
than the road speed (90 km/h) it should display a message
“Reduce your speed”.
Pseudocode
BEGIN
1. DISPLAY “This program tests your speed limit.”
2. DISPLAY “Enter the speed (in km/h):”
3. INPUT speed
4. IF speed > 90 THEN
DISPLAY “Reduce your speed.”
ENDIF
END
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 65
FIGURE 4.8 The simple
selection control structure
flowchart
Is condition true?
Statement(s)
true
false
Flowchart C++ program and output
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 66
FIGURE 4.9 testSpeed program flowchart
speed>90
true
false
DISPLAY
“Reduce your speed”
BEGIN
END
DISPLAY
“This program tests your speed limit.”
DISPLAY “Enter the speed (in km/h):”
INPUT speed
FIGURE 4.11 testSpeed.cpp
FIGURE 4.10 Output with input test data, speed = 110
Student activity 2
1. Circle the errors in the following code segments:
a. if (marks = 100) cout<<“congratulations;
b. if (marks =< 50) cout<<“you need more effort”;
2. Write a C++ statement to perform the following logic:
a. If a boolean variable named max is set to true, assign 10 to the integer
variable named limit
b. If a double variable sales is less than or equal to 100.00, assign 2 to
double variable commission.
c. If a double variable sales is greater than or equal to 100.00, assign 2 to double variable commission.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 67
FIGURE 4.12 Output with input test data, speed = 25
FIGURE 4.14
Student activity
2, Question 2
FIGURE 4.13
Student activity 2,
Question 1
SECTION 4
The if-else control structure
Introduction to the if-else control structure
In a selection control structure, we can include some tasks to
perform in both paths of executions as shown in Figure 4.18.
If the condition is true, one statement or a block of
statements is executed. Otherwise another statement or a
block of statements is executed. At any time when the
program runs, only one path is executed.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 68
FIGURE 4.15 The if-else control structure flowchart
Is condition true? true
Statement(s) Statement(s)
false
The general format of pseudocodes and C++ codes for a
simple selection control structure is given in Table 4.3. The
curly brackets are optional in a C++ code in a case where
we have only one statement in the body of the if statement.
TABLE 4.3 Pseudocode and C++ syntax for if-else
control structure
TABLE 4.3 Pseudocode and C++ syntax for if-else
control structure
Pseudocode C++ syntax
IF condition THEN
Block of statements
ELSE
Block of statements
ENDIF
if (condition)
{
Statement1;
Statement 2;
………………..
………………..
}else
{
Statement 3;
Statement 4;
………………..
………………..
}
The following video explains how to write selection control
structures in C++.
Program design and
C++ code
This section illustrates how if-else control structures can be
used in problem solving with sample pseudocode,
flowchart, program and program outputs. Since two paths
of execution exist in a program with an if-else control
structure, we need at least two data sets to test such a
program.
Worked example
Problem
Design and develop a program to test whether a user
entered number is odd or even and display it to the user.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 69
FIGURE 4.16 How to
write selection control
structures in C++:
YouTube
http://bit.ly/1lLASIR
FIGURE 4.17 How to
write selection control
structures in C++: QR
code
Pseudocode
BEGIN
1. DISPLAY “This program displays whether a user
entered number is odd or even.”
2. DISPLAY “Enter a number:”
3. INPUT number
4. IF remainder (number/2)==0 THEN
5. DISPLAY number, “is an even number”
6. ELSE
7. DISPLAY number, “is an odd number”
8.
9. END IF
END
Flowchart
DIAGRAM 4.1 NumberTest flowchart
Remainder of (number/ true 2)==0 false
BEGIN
END
DISPLAY
number, “is an
even number”
DISPLAY
number, “is an
odd number”
DISPLAY “This program display
whether a user entered number is
odd or even.”
DISPLAY “Enter a number:”
INPUT number
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 70
C++ program and output
Student activity 3
1. Circle the errors in the
following code segments.
a. if (marks > 50)
cout<<“congratulations”;
cout<<“you passed the
test”<<endl
else
cout<<“sorry, try again”
else
b. if (score > 50)
cout<<“congratulations”;
else (score < 50)
cout<<“sorry, try again”
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 71
FIGURE 4.18 numberTest.cpp
FIGURE 4.19 Program 4.2: Output with input test data,
number = 20
FIGURE 4.20 Program 4.2: Output with input test data,
number = 5
FIGURE 4.21
Student activity 3
SECTION 5
Logical operators
An introduction to logical operators
There are three logical operators we can use in our
programs. The first two logical operators, AND
(represented using && in C++) and OR (represented
using || in C++) are used to combine two or more
relational expressions (conditions). The other logical
operator, NOT (represented using ! in C++) is used
to negate the logic of an expression (condition).
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 72
The following table shows the results of logical operators
when used in an expression.
TABLE 4.4 Truth table
A B a AND b (a && b) a OR b (a ||
b) Not a (!a)
TRUE TRUE TRUE TRUE FALSE
TRUE FALSE FALSE TRUE FALSE
FALSE TRUE FALSE TRUE TRUE
FALSE FALSE FALSE FALSE TRUE
The following link explains how to program logical
operators in C++.
Student activity 4
Fill in the blanks in the following table. The C++ statement
column should be filled with an equivalent C++ statement
and the result column should be filled with a true or false
value. Assume x = 3, y = 5 and z = 10. The first question
has been done for you.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 73
Pseudocode C++ statement Result
(x > y) OR (x < z) (x > y) || (x < z) TRUE
(y >= x) AND (y == z)
NOT (x < 8)
(x <= y) AND ((x + 3)>y)
NOT (x == y)
(x < (y/2)) OR ((x + y)<z)
FIGURE 4.24 Student
activity 4
http://bit.ly/1mgxWEA
FIGURE 4.22 How to
program logical
operators in C++:
weblink
FIGURE 4.23 How to
program logical
operators in C++: QR
code
SECTION 6
Nested if control structure
Introduction to the nested if control
structure
We can include an if block inside another if-or-else
block. The nested if (if statement inside an if
statement) is executed only if the outer if statement
is true. This is called a nested if control structure.
Nested if control structures can be illustrated using
the following problem statement.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 74
Worked example
Problem
Design and write a program that determines whether a
student qualifies for an enabled funding place in the
UWSCollege University Foundation Studies. Note that
hypothetical criteria are used in this program to determine
the enabled funding.
Enabled funding is allocated to local students who earn
less than or equal to $10,000 per year.
Pseudocode
BEGIN
DISPLAY “This program determines whether you qualified for
an enabled funding place.”
DISPLAY “Enter 1 if you are a local student. Enter 0 if you are
an international student.”
INPUT residency
IF (residency==1) THEN
DISPLAY “Enter your annual income.”
INPUT income
IF income<=1000 THEN
DISPLAY “Congratulations, you qualify for
an Enabled Funding Place.”
ELSE
DISPLAY “Sorry, you do not qualify.
Enabled funding places are income tested.”
ENDIF
ELSE
DISPLAY “Sorry, only local students qualify for
enabled funding places.”
ENDIF
END
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 75
DIAGRAM 4.2 enabledFundingQualifier flowchart
residency==1
false
BEGIN
END
DISPLAY
“Sorry, Only local
students are qualified for
Enabled Funding
Places.”
DISPLAY
Enter your annual income
DISPLAY “This program determine whether
you are qualified for enabled funding place”.
DISPLAY “Enter 1 if you are a local student?
Enter 0 if you are an international student. ”
INPUT residency
income<=1000
INPUT income
true
DISPLAY “Congratulations,
you are qualified for
Enabled Funding Place”
DISPLAY “Sorry, you are not
qualified. Enabled Funding
Places are income tested”
true
false
Student activity 5
1. After execution of the following
code segment, what will be the
value of the variable z if the
following data is entered at the
keyboard at run time?
cin >> x>>y;
if (x > 5)
{
if (y<0)
z = 5;
else
z = 0;
}
else
{
if (y<10)
z = 100;
else
z = 1000;
}
x y z
2 10
5 0
8 5
8 10
2. Design test data to test the given pseudocode for
enabledFundingQualifier program.
3. Write the C++ code for enabledFundingQualifier
program.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 76
FIGURE 4.25
Student activity 5
SECTION 7
The if-else-if control structure
Introduction to the if-else-if control
structure
When a nested if control structure includes linear
tests for a series of conditions, as an alternative we
can use an if-else-if control structure. In if-else-if
control structures we have more than one possible
path of execution as shown in Table 4.7. However,
whenever the program runs, only one path is
executed. Usually we use this structure when we
need to test the value in a variable for a series of
conditions as given in the example problem which
follows.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 77
The general format of pseudocodes and C++ codes for ifelse-if
control structures is given in Table 4.5.
TABLE 4.5 Pseudocode and C++ syntax for if-else-if
control structures
TABLE 4.5 Pseudocode and C++ syntax for if-else-if
control structures
Pseudocode C++ syntax
IF condition1 THEN
Block of statements
ELSE IF condition2 THEN
Block of statements
ELSE IF condition3 THEN
Block of statements
…..
…..
ELSE
Block of statements
ENDIF
if (condition1)
{
Statement1;
Statement 2;
……………..
………………..
}else if (condition2)
{
…………
…………
}
else if (condition3)
{
…………
…………
}
…………
…………
else
{
}
Program design and C++ code
This section illustrates how an if-else-if control structure
can be used in problem solving with sample pseudocode,
flowchart, program and program outputs.
Worked example
Problem
Design and develop a program to calculate the grade of a
student. You should ask the user to enter the marks and
calculate the grade according to the following table.
Marks Grade
75 to 100 D
65 to 74 C
50 to 64 P
0 to 50 F
Pseudocode
BEGIN
1. DISPLAY “Enter marks:”
2. INPUT marks
3. IF marks >= 75 THEN
DISPLAY “Your grade is D”
ELSE IF marks >= 65 THEN
DISPLAY “Your grade is C”
ELSE IF marks >= 50 THEN
DISPLAY “Your grade is P”
ELSE
DISPLAY “Your grade is F”
ENDIF
END
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 78
Flowchart
DIAGRAM 4.3 Program 4.4: gradeCalculator.cpp
BEGIN
Marks>=75
Marks>=65
false
Marks>=50
false
DISPLAY
“Your grade is D”
DISPLAY
“Your grade is C”
DISPLAY
“Your grade is P”
true
END
false
true
true
DISPLAY
“Your grade is F”
DISPLAY
“Enter your marks:”
INPUT number
Desk check table
Note: Since only one path is executed in an if-else-if
control structure at any one time, we can consider the
whole if-else-if block as one statement.
We should design test data to test every possible path of
execution in the program. For example, we need at least
four input data sets to validate the design of
gradeCalculator.
TABLE 4.6 Example gradeCalculator design
Student number Marks Output
Test 1
1, 2 20
3 Your grade is F
Test 2
1, 2 51
3 Your grade is P
Test 3
1, 2 67
3 Your grade is C
Test 4
1, 2 95
3 Your grade is D
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 79
Student activity 6
1. What will be the output of the Program 4.4 for the
following input values for marks?
Marks Output
100
75
50
62
210
0
2. After execution of the following code segment, what
will be the value of the variable number if the value 1 is
entered at the keyboard at run time.
cin >> number;
if (number > 8)
number = number + 10;
else if (number >4)
number = number + 20;
else
number = number + 30;
3. Modify Program 4.4 to validate the input. If the mark is
greater than 100 or less than 0 it should display the
message “Invalid marks.”
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 80
FIGURE 4.26 C++ program and output.Program 4.4:
gradeCalculator.cpp
FIGURE 4.27 Student
activity 6
SECTION 8
Case control structure
Introduction to case control structure
Instead of using an if-else-if control structure to
compare the value of a control variable to different
values, we can use the case control structure. Case
control structures help us to design and write short
codes to perform series of if-else-if statements. For
example, the program design given below can be
used to display a menu with three different animals
and get a user input value to select an animal. Based
on the user’s selection, we will display an animal
sound.
An example is given in Table 4.7.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 81
The case control structure implement using switch–case statements in C++ is explained in the link below.
http://classes.mst.edu/compsci53/switchcase.htm
TABLE 4.7 Pseudocode
Pseudocode using if-else if control
structure
Pseudocode using case control
structure
BEGIN
DISPLAY “Animal Sounds”
DISPLAY “Pig”
DISPLAY “Dog”
DISPLAY “Cow”
DISPLAY “Your choice”
INPUT choice;
IF choice==1 THEN
! ! DISPLAY “Oink”
ELSE IF choice==2 THEN
! ! DISPLAY “Bark”
! ! DISPLAY “Ruffruff”
ELSE IF choice==3 THEN
! ! DISPLAY “Moooo”
ELSE
DISPLAY “Error”
ENDIF
END
BEGIN
DISPLAY “Animal Sounds”
DISPLAY “Pig”
DISPLAY “Dog”
DISPLAY “Cow”
DISPLAY “Your choice”
INPUT choice;
CASE OF choice
1 :DISPLAY “Oink”
2 : DISPLAY “Bark”
! ! DISPLAY “Ruffruff”
3 : DISPLAY “Moooo”
other: DISPLAY “Error”
ENDCASE
END
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 82
SECTION 9
End of chapter review questions
Practice questions
The two links below provide practice questions and
answers for topics covered in this chapter.
1. http://bulldog2.redlands.edu/facultyfolder/
patriciacornez/cs110/quiz4.html
2. http://www.cprogramming.com/tutorial/quiz/
quiz2.html
Review questions
1. In mathematics, absolute numbers are defined
as the magnitude of a real number without
regard to its sign. Design and write a program
which asks the user to enter any number and
calculate the absolute value of the number
entered.
2. Design and write a program which asks the
user to enter two numbers (for dividend and
devisor) and calculate the quotient of those
two numbers only if the devisor is a positive
number.
Quotient = dividend/devisor
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 83
3. Design and write a program that prompts the user to
enter the temperature in centigrade degrees. If the
temperature is greater than 37.5oC, display a message
on the command window telling the user that they
have a fever.
4. Design and write a program that asks the user to enter
two numbers. The program should determine which
number is the smallest and display the message
“Small number is [input number] ” in to the console
window.
5. Design and write a program which calculates the
grade according to the table below and displays it to
the user.
6. Design and write a program which asks the user to
enter two numbers and calculate the difference
between those two numbers. (The difference is always
a positive value.)
7. Design and write a program that asks the user to enter
the outside temperature. If the temperature is equal to
or above 70oF, display the message on the command
window “Wear cool clothes and drink plenty of water”.
If the temperature is between 55oF and 70oF display
the message on the command window “It is a
beautiful day. Enjoy the sun”. If the temperature is
equal to or below 55oF display the message “It is a
cold day. Wear warm clothes”.
8. Design and write an arithmetic calculator program so
that when the program runs, it displays the following
menu:
If the user presses 1, the
program should ask the user to
enter the radius of a circle and
calculate and display the area.
If the user presses 2, the
program should ask the user to
enter the width and length of a
rectangle to calculate and
display the area.
If the user presses 3, the program should ask the user
to enter the base and height of a triangle to calculate
and display the area.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 84
FIGURE 4.28 End
of chapter review
questions
Marks Grade
85-100 A
75-84 B
60-69 C+
50-59 C
40-49 D
30-39 E
0-29 F
Welcome to the Simple Area Calculator.
Select one of the following options:
1. Circle
2. Rectangle
3. Triangle
CHAPTER 5
Iteration control structure
Chapter overview
In this chapter students will learn to:
design and program using the while loop
design and program using the do-while loop, and
design and program using the for loop.
Learning outcomes
At the completion of this chapter, students should be able
to:
1. illustrate the steps involved in program development
2. solve problems and illustrate solutions using iteration
control structure flow charts, pseudocode and
translation to C++
3. code, debug and test programs in C++ using an
Integrated Development Environment (IDE), and
4. develop a set of input test data and desk check
pseudocode.
Suggested chapter duration
12 hours
Reading resources
UWSCollege 2014, Introductory Programming
workbook, UWSCollege, Sydney.
Introductory Programming vUWS site.
Chapter revision tools
Student checklist widget
End of chapter review questions widget
UWSCollege Pty Ltd! ! !!!!!!!!!!!!!!!!!!!! 85
Chapter 5: Iteration control structure: Study tools
FIGURE 5.1 Chapter 5: Iteration
control structure: Checklist
Use this checklist to prepare for
assessments.
FIGURE 5.2 Chapter 5: Iteration
control structure: Notes
Use this widget to create study
notes for this chapter.
FIGURE 5.3 Chapter 5: Iteration
control structure: Feedback
Provide your unit tutor with
feedback about your knowledge
and understanding of the chapter.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 86
SECTION 1
What is an iteration control structure?
A computer can iterate (ie repeat) a block of
statements many times. In programming, iteration
control structures are also referred to as loops.
We can use an iteration control structure to replace a
set of sequential statements that perform the same
task. For example, if we have to write a program to
display numbers from 1 to 10000 on the console
window, using the programming knowledge gathered
so far, we only have two choices:
Choice 1: write 10000 cout statement
Choice 2: include all the numbers from 1 to 10000 in
one cout statement with a formatted string.
Either way it is a lengthier program.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 87
In this chapter, we are going to learn about iteration/loop control structure which we can use to program the computer to
perform a repetition task like the one above with less coding effort and in a fewer number of lines.
Also, there are algorithms/programs that require the incorporation of iteration or loops. For example, if we have to design an
algorithm to test a user entered number, n is a primary number, we may need to test whether that n is divisible by any number
from 2 up to n–1. Therefore, we have to use a iteration control structure (loop ) in such a program.
A loop control structure has two parts:
an expression (also known as a condition) that is tested to decide whether to repeat or exit the loop, and
a body of the loop which can be one statement or a block of statements.
There are three different types of iteration/loop structures as listed below:
1. The while loop: Always test the expression first and only enter the body of the loop if the expression is true.
2. The do-while loop: Always test the expression at the end after executing the body of the loop.
3. The for loop: This is similar to while loop; however, it can only be used to repeat a known number of times as specified
in the program design and coding stage.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 88
SECTION 2
The while loop
Ipad apps to download
LucidChart
Cloudon
Introduction to the while loop
The while loop repeats a statement or a block of
statements while the expression is true. There are two
parts in a while loop:
a while condition (expression) that is to be tested for a
true or false value before execution of the body of the
loop, and
a body which can be a statement or a block of
statements that repeats.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 89
After each execution of the body of the loop, the computer
will test the condition. If the condition is true, it will repeat
the execution of the body of the loop. It will exit the loop if
the condition is false. The while loop can be represented
using a flowchart as shown in Figure 5.4.
The while loop is explained in the video in Figure 5.5.
The pseudocode and C++ syntax for a while loop is given
below.
Pseudocode C++ syntax
WHILE <expression>
Block of Statements
ENDWHILE
while (expression)
{
Statement1;
Statement2;
……………..
………………..
}
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 90
FIGURE 5.5 Section 2: YouTube: Bucky’s C++
Programming tutorials — 18 — While loops
FIGURE 5.4 The while loop
Increment and decrement operator
Increment operator (++) can be used to add 1 to a variable.
We can replace x = x + 1; with x++;
Decrement operator (– –) can be used to subtract 1 from a
variable. We can replace x = x – 1; with x– –;
Often in C++ programs, you will see that increment and
decrement operators are used to shorten the code.
Problem solving using the while loop
Worked example 5.1: Designing and writing a
program
Design and write a program to display numbers from 0 to
10000 using a while loop.
Problem definition
Display numbers from 0 to 10000.
Program design
Pseudocode for the program is given below. The equivalent
flowchart for the program is provided in Figure 5.6.
BEGIN
number= 0
WHILE(number<=10000)
DISPLAY number
number=number+1
ENDWHILE
END
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 91
FIGURE 5.6 displayNumbers flowchart
BEGIN
number= 0
Is
number<=10000
Display number
number=number+1
true
false END
Student activity 1
1. What would happen if you commented-out (or deleted) the “number++;” statement in
Program 5.1?
a. The program will not compile as it causes a syntax error
b. It will display only 0
c. It will keep displaying 0 and never stop
2. Which of the following program designs can be used to display the following number
pattern?
5, 4, 3, 2, 1
a. BEGIN
n= 1
WHILE (n<=5)
DISPLAY n
n=n+1
ENDWHILE
b. BEGIN
n= 5
WHILE (n>0)
DISPLAY n
n=n-1
ENDWHILE
c. BEGIN
n= 5
WHILE (n>1)
DISPLAY n
n=n-1
ENDWHILE
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 92
FIGURE 5.7 Program 5.1: displayNumbers.cpp
FIGURE 5.8 Student activity 1
3. Convert the correct
pseudocode (your answer)
for Question 2 into a
flowchart. (You may use
the app in Figure 5.10.)
Write a C++ program to
implement your design.
4. Watch the video in Figure
5.9 which explains how to
calculate running total.
Design and write a
program which asks users
to enter five numbers, as well as calculate and display
the total of user-entered numbers.
5. Modify the program written in Question 4 to calculate
and display the average of five numbers.
6. You are asked to design and write a program to
calculate the average age of the students in a class.
You have been given following incomplete design. Fill
in the blanks.
BEGIN
1 DISPLAY “This program will calculate the average age
of the students”
2 DISPLAY “Enter number of students in the class:”
3 INPUT numberOfStudents
4 studentCount = 0
5 totalAge = 0
6 WHILE studentCount < ________________________
7 Display “Enter age of student”, (studentCount+1),“:”
8 INPUT age
9 ___________________________________________
10 studentCount = ______________________________
ENDWHILE
11 averageAge = _______________________________
12 DISPLAY “Average Age is:”, averageAge
END
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 93
FIGURE 5.9 Section 2: YouTube: Bucky’s C++
Programming tutorials — 19 — Simple program
using a loop
FIGURE 5.10 Student
activity 1, Question 3:
LucidChart app
7. The following test data can be used to test the design. Design another set of test data. Use a different number for
numberOfStudents.
8. Write C++ program for the design you completed in Question 6.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 94
Input data
numberOfStudents 3
Iteration 1 Iteration 2 Iteration 3
Age 7 6 5
Expected output
averageAge 6
Student activity 2
Complete the desk check table in Figure 5.11 with test data given in Question 7 in Student
Activity 1. (You may use the Excel spreadsheet in the app in Figure 5.12.)
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 95
FIGURE 5.12 Student
activity 2: App
FIGURE 5.11 Desk check table
numberOfStudents studentContent totalAge DOWHILE condition age averageAge DISPLAY
1
2
3
4
5
6
7
8
9
10
11
12
FIGURE 5.13 Student
acitivty 2
Sentinel control loop
The loops we have designed so far iterate pre-determined number of times. However, sometimes we need to use a user input
value to decide to continue with the repetition or not. Such a user input value is known as a sentinel value. The video in Figure
5.14 explains an example code written using a sentinel control loop.
FIGURE 5.14 Section 2: YouTube: Bucky’s C++ Programming tutorials — 20
— Sentinel control program
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 96
SECTION 3
The do-while loop
Ipads apps to download
LucidChart
Cloudon
An introduction to the do-while loop
The do-while loop tests the expression or the condition
at the end of the iteration. Therefore, the do-while loop
always performs at least one iteration, even if the
expression is false. In pseudocode, a do-while loop is
represented as a REPEAT_UNTIL control structure.
The do-while loop is preferred if we have to write a
program where the user needs to decide whether to
repeat the loop (sentimental control loop) after an
iteration.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 97
The flowchart for the do-while loop is shown in Figure 5.15.
The do-while loop is explained in the video in Figure 5.16.
The pseudocode and C++ syntax for a do-while loop is
given below.
Pseudocode C++ syntax
DO
Block of Statements
WHILE <expression>
do
{
Statement;
Statement;
……………..
………………..
} while (expression);
Problem solving using the do-while loop
Worked example 5.2: Do-while loop
You are asked to calculate the average age of the students
in the class. However, you are told that the user of your
program does not know how many students are in the
class. Therefore, the user should enter the age of each
student followed by –1 to indicate the end of data. The
program should display both the total number of students
and the average age of the students in the class. You will
note that you will not be able to design this program using
the while loop. Instead, you need to use the do-while loop.
Problem definition
Calculate the average age of a group of students. The user
will enter the age of one student after the other. The user
will enter –1 to indicate the end of the age set.
Problem analysis
Input: set of ageOfStudent (Entered )
Outputs: averageAge, numberofStudents
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 98
FIGURE 5.15 The do-while loop
Expression
true
false
Body
FIGURE 5.16 Section 3: YouTube: Bucky’s C++
Programming tutorials ― 24 ― Do-while loops
Design test data
TABLE 5.1 Design test data
Data set 1 Data set 2 Data set 3
age –1 5, 6, 4, 7, 8, –1* 4, 3, –1*
Expected output
averageAge “No ages entered.” 6 3.5
numberOfstudents 0 5 2
*Each iteration is separated with a comma (,)
Program design
BEGIN
numberOfStudents=–1
totalAge=0
DO
DISPLAY “Enter the age of a student. Enter –1 when you finished entering all the ages:”
INPUT age
numberOfStudents= numberOfStudents+1
totalAge=totalAge+age
WHILE (age>0)
IF (numberOfStudents>0) THEN
averageAge=totalAge/numberOfStudents
DISPLAY “Number of Students=”, numberOfStudents
DISPLAY “Average Age=”, averageAge
ELSE
“no ages entered;”
ENDIF
END
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 99
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 100
FIGURE 5.17 Program 5.2: calcAverageAge.cpp
Student activity 3
1. Draw the equivalent flowchart for the pseudocode of
calcAverageAge program. You may use the app in
Figure 5.18.
2. Create a desk check table to test the design with the
given input test data in Table 5.1 “Design test data”.
You may use the app in Figure 5.19.
3. What will be the output
of following code
segment?
int i=0;
do
{
i++;
cout<<i<<” “;
}while (i<5);
a. 0,1,2,3,4
b. 1,2,3,4,5
c. 0,0,0,0,0
4. What will be the output of following code segment?
int i=0;
do
{
cout<<i<<” “;
i++;
}while (i>=5);
a. 0
b. 1
c. 1,2,3,4,5
5. What will be the output of following code segment?
int i=0;
do
{
cout<<i<<” , “;
i=i+2;
}while (i<=6);
a. 0,1,2,3,4,5,6
b. 0,2,4,6
c. 2,4,6
6. The program given in Question 3 is meant to calculate
the average marks of three tests. However, there is a
logical error in the program. Explain it and fix the error.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 101
FIGURE 5.20 Student
activity 3: Questions 3 to 6
FIGURE 5.18 Student
activity 3: Question 1
FIGURE 5.19 Student
activity 3: Question 2
SECTION 4
The for loop
The for loop is designed to iterate a known number of
times. The for loop consists of a loop header and a body
of the loop. The loop header consists of three elements:
1. the loop control variable which is intitalised with
start-up value
2. the condition which will be tested before executing
the body of the loop, and
3. the update which will be applied to the loop control
variable at the end of each iteration.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 102
FOR counter=intital_value to finalValue increment/
decrement* by value
Body
End FOR
*Only one of the operations, increment or decrement, can
be applied in one loop statement.
The for loop can be represented using a flow chart as
shown in Figure 5.20.
The syntax of C++ for loop
for (initialisation; test condition; update)
body of the loop
Steps for executing a for loop
There are four steps in the execution of a for loop:
Step 1 ⎯ Initialisation: Generally, loop control variable is
defined and initialised with some initial value. This is
executed once at the beginning of the loop.
Step 2 ⎯ Test condition: Check whether the loop control
variable reached the final value. If it is true, the body of
the loop is executed; otherwise, the loop ends.
Step 3 ⎯ Execute the body of the loop: The body of the
loop can be a single statement or a block of
statements.
Step 4 ⎯ Update: Usually, the computer increases or
decreases the loop control variable as specified, and the
computer then goes back to step 2.
Problem solving using a for loop
Display a table of conversions from inches to centimetres.
Ask the user for the maximum value they would like
included in the table. Start the inches column of the table
with 0.0 and increment by 1 inch. Continue the table up to
12 inches. (1 inch = 2.54 cm)
Program design
BEGIN
DISPLAY “Inches to Centimetres Conversion Table”
DISPLAY “ Inches Centimetres”
DISPLAY “======================”
FOR i=0 to 12 increment by 1 DO
DISPLAY i, “ “ i*2.54
ENDFOR
END
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 103
FIGURE 5.21 The for loop
condition true Body
false
Update Counter
counter=intital_value
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 104
FIGURE 5.22 Program 5.3: inches_to_cm.cpp
Practice quiz
Click on the link below and complete the questions in the
online quiz:
<http://bulldog2.redlands.edu/facultyfolder/patriciacornez/
cs110/quiz7.html>
Student activity 4
1. Modify the program given in Program 5.3 according to
the following specification.
Ask the user for the maximum value they would like
included in the table. Start the inches column of the
table with 0.0 and increment by 2 inches. Continue the
table up to the last column value entered by the user (1
inch = 2.54 cm).
2. How many times will the following for loop display
“Introductory Programming”?
for (int i = 0; i < 20; i++)
cout << “Introductory Programming” << endl;
a. 0
b. 19
c. 20
d. 21
3. What values will be stored in x after executing this
code segment?
int x=5;
for(x=10; x>5; x– –)
{
x– –;
}//end loop
a. 10
b. 6 c. 5
d. 4
4. Design and write a program that can display the
following number pattern on the console window using
a for loop:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
5. Design and write a program that can display the
following number pattern on the screen using a for
loop.
9
8
7
6
5
4
3
2
1
0
6. Design and write a program
that can display all odd
numbers between 0 and 20.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 105
FIGURE 5.23 Student
activity 4
SECTION 5
End of chapter review questions
Practice quiz
Click on the link below and complete the questions in the
online quiz:
<http://bulldog2.redlands.edu/facultyfolder/
patriciacornez/cs110/quiz8.html>
End of chapter review questions
1. Design and write a program to display a conversion
table from radian value to degrees. The table should
start with 0.0 radian and increment by π/10. The
table should display all conversions of radians to
degrees until 2 π.
Hint: π radians =180°
2. Design and write a program using a while loop which
can display the following even numbers on the
console window:
2, 4, 6, 8, 10, 12, 14, 16, 18, 20
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 106
3. Design and write a program which asks the user to enter a positive integer number. The program uses loops to draw a
square using stars where the width of the square equals the user-entered number.
Sample output:
If the user enters 4, the program should display
* * * *
* * * *
* * * *
* * * *
4. Design and write a program to test whether a user input number is a primary number or not.
5. Design and write a program which asks the user to enter a positive number for the average speed of an object and
calculate how much distance the object travelled in every five-minute interval
up to one hour.
6. Design and write a program called “area calculator”. Area calculator can be
used to calculate the area of a circle, square, rectangle or triangle. The
program should ask the user to choose a shape for which they want to
calculate the area. Then the program should ask the required dimensions of
the shape. Next, the program should calculate and display the area of the
shape. The program should repeat the menu until the user chooses to exit
the program.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 107
FIGURE 5.24 Chapter 5: Review
questions
CHAPTER 6
Modularisation
Chapter overview
In this chapter students will learn about:
the parts of the C++ program
variables and constants
data types
standard output, and
best coding practices.
Target learning outcomes
At the completion of this chapter, students should be able
to code, debug and test programs in C++ using an
Integrated Development Environment (IDE).
Reading resources
UWSCollege 2014, Introductory Programming
Workbook, UWSCollege, Sydney.
Introductory Programming vUWS site.
Suggested chapter duration
6 hours
Chapter revision tools
Student checklist widget
Revision questions widget
UWSCollege Pty Ltd! ! !!!!!!!!!!!!!!!!!!!! 108
Source: www.tenouk.com/Module4.html
Chapter 6: Modularisation: Study tools
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 109
FIGURE 6.1 Chapter 6:
Modularisation:
Checklist
Use this checklist to
prepare for assessments.
FIGURE 6.2 Chapter 6:
Modularisation: Notes
Use this widget to create
study notes for this
chapter.
FIGURE 6.3 Chapter 6:
Modularisation:
Feedback
Provide your unit tutor
with feedback about your
knowledge and
understanding of the
chapter.
SECTION 1
What is modularisation?
So far in this unit we have learnt to design and write
programs using structured theorems. However, if we
have to solve a more complex or larger problem you
could imagine we would write a lengthier void main ()
function . It would be hard to debug and correct such
a program. Also it would be hard to optimise such a
program to run in lesser time. The solution is to break
the problem in to manageable pieces and write it. A
small piece of program is called a module. In C++ a
module is called a function.
Please complete Student activity 1 on the following
page.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 110
Student activity 1
Play a game in the cargo-bot app and create a solution using modularisation. Discuss the benefits of your approach.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 111
FIGURE 6.4 Chapter 6,
Student activity 1
SECTION 2
How to design modular programs
We can use structure charts to show an overview of the
modular structure and then each module can be
designed using a pseudocode or flowchart.
The weblink on the following page explains the
structure charts in detail.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 112
FIGURE 6.5 Structure
charts: Web link
Structure charts
The following weblink explains the structure charts in detail.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 113
SECTION 3
C++ functions
C++ functions
C++ function is a collection of statements to perform a task.
Figure 1.8 shows the difference between a C++ program with
and without function.
For more information about C++ functions click on the Keynote
presentation on the following page.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 114
Source: Viewed 24 June 2014. <www.cplusplus.com/doc/tutorial/functions>
Functions
Watch Buckys C++
Programming Tutorials
⎯ 9 ⎯ Functions
YouTube video for a
definition of functions
and why they are
useful in C++
programming.
Creating functions that
use parameters
Watch Buckys C++
Programming Tutorials ⎯ 10 ⎯
Creating functions that use
parameters YouTube video for
more information on creating
functions using parameters.
Creating a function that takes multiple parameters
Watch Buckys C++ Programming Tutorials ⎯ 11 ⎯ Creating
functions that use multiple parameters YouTube video for
an understanding of how to create a function that takes
more than one parameter.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 115
FIGURE 6.6 YouTube:
Buckys C++
Programming Tutorials ⎯
9 ⎯ Functions
FIGURE 6.8 YouTube:
Buckys C++
Programming Tutorials ⎯
10 ⎯ Creating functions
that use parameters
FIGURE 6.9 YouTube:
Buckys C++
Programming Tutorials ⎯
11 ⎯ Creating functions
that use multiple
parameters
FIGURE 6.7 C++ function:
Keynote presentation
SECTION 4
Review questions
Chapter 6: Review quiz 1
Multiple choice questions
1. In a function header, you must furnish:
a. data type(s) of the parameters
b. data type of the return value
c. the name of the function
d. names of parameter variables, or
e. all of these.
2. The value in this type of local variable persists
between functions called:
a. global
b. internal
c. static
d. dynamic, or
e. none of these.
UWSCollege Pty Ltd !!!!!!!!!!!!!!!!!!!!! 116
3. Given the following function definition:
void calc (int a, int b)
{
int c;
c = a + 2;
a = a * 3;
b = c + a;
}
What is the output of the following code fragment that
invokes calc? (All variables are of type int)
x = 1;
y = 2;
z = 3;
calc (x, y);
cout << x << “ ” << y << “ ” << z << endl;
a. 1 2 3
b. 1 6 3
c. 3 6 3
d. 1 14 9, or
e. none of the above.
4. Given the following function definition.
void calc (int a, int& b)
{
int c;
c = a + 2;
a = a * 3;
b = c + a;
}
What is the output of the following code fragment that
invokes calc? (All variables are of type int)
x = 1;
y = 2;
z = 3;
calc (x, y);
cout << x << “ ” << y << “ ” << z << endl;
a. 1 2 3
b. 1 6 3
c. 3 6 3
d. 1 14 9
e. None of the above.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 117
FIGURE 6.10 Chapter 6:
Review quiz 1
5. What is the output of the following program?
#include <iostream>
using namespace std;
void doSomething(int&);
int main ( )
{
int x = 2;
cout << x << “ ”;
doSomething (x);
cout << x << “ ”;
return 0;
}
void doSomething (int& num)
{
num = 0;
cout << num << “ ”;
}
a. 2 0 2
b. 0 0 0
c. 2 2 2
d. 2 0 0
e. 0 0 2
Chapter 6: Review quiz 2
Programming challenge
1. Odd or even
a. Design and write a function to test whether a
number is odd or even.
b. Write a short main program which asks for a user’s
input and returns the result of the number odd or
even.
2. Prime number
a. Design and write a function that will determine if a
supplied integer is a prime number or not. Prime
numbers are numbers that have no factors except
for themselves and 1.
b. Write a short main program which asks for a user’s
input for a number and call prime function to
determine the result and display the results.
3. Rectangle area
a. Write a function called getLength which asks the
user to enter the rectangle’s length, and return
value as a double.
b. Write a function called getWidth which asks the
user to enter the rectangle’s width, and return value
as a double.
c. Write a function called calculateArea to accept
rectangle’s length and width as arguments, and
return the rectangle’s area.
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 118
d. Write a function called displayData that accepts the
rectangle’s length, width, and area as arguments
and displays them in the following format.
Rectangle data
Length: xxxx
Width: xxxx
Area: xxxx
e. Write a short main program that calls in these
functions and displays the results.
4. Geometry calculator
a. Write a C++ function called area which takes the
radius of a circle as a parameter, calculates the
area and returns it.
b. Write a C++ function called area which takes the
width and height of a rectangle as parameters,
calculates the area of the rectangle and returns it.
(Hint: You can reuse the codes you did earlier)
In your main program you should display the following
menu:
Geometry calculator
1. Calculate the area of a circle.
2. Calculate the area of a rectangle.
3. Quit
Enter your choice (1 to 3): ________
If the user enters 1, the program should call the
relevant function to calculate the area of a circle.
If the user enters 2, the program should call the
relevant function to calculate the area of a
rectangle.
If the user enters 3, the program should end.
c. Input validations: Display an error message if the
user enters a number other than 1 – 3 for a menu
option. Do not accept negative values for the
circle’s radius or the rectangle’s length or width.
d. The program should also allow the user to choose
the menu again at the end of each calculation.
e. Did you notice that you have two functions with the
same names but with different parameter lists?
This is called function overloading. Can you add a
third function to calculate a triangle with two
parameters (type of “double”) into your program?
UWSCollege Pty Ltd!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 119
FIGURE 6.11 Chaper 6:
Review quiz 2

Order from us and get better grades. We are the service you have been looking for.