Вы находитесь на странице: 1из 61

Last updated: 30 May 2014

Acknowledgements

COPYRIGHT - UWSCollege 2014

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 eort 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

I CONS

INDICATES VIDEO FILE

I NDICATES

I NDICATES

OPEN WEB LINK

I NDICATES

DOCUMENT TO

OPEN

I NDICATES AUDIO

I NDICATES

FILE

UWSCollege Pty Ltd! !

I NDICATES

STUDENT
INSTRUCTION

STUDENT ACTIVITY

I NDICATES

STUDENT READING

NOTE - MAKING

FILE

R EADER C LOUD ( WWW . READERCLOUD . COM )

iii

Reader Cloud

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
syncd 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.

Create a reader account


to store your data from
the iBook on a cloud
account.

Example applications can include students sharing devices in a school and siblings sharing a book
at home.

Interact with other eBook readers


vUWS site

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.

V UWS

S ITE

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.

Blackboard App

Please explore the vUWS Information for Students and vUWS Information for Sta sites listed
under My vUWS Sites after you have logged in for support in using vUWS.

UWSCollege Pty Ltd! !

iv

C HAPTER 1

Introduction to programming
Chapter overview

Reading resources
UWSCollege 2014, Introductory Programming
Workbook, UWSCollege, Sydney.

In this chapter students will learn about:


recent developments in engineering

Introductory Programming vUWS site.

computer systems

Chapter revisions tools

programs and programming languages


structured programming, and

Student checklist widget

the program development process.

Revision questions widget

iPad apps to download

Suggested chapter duration

Blackboard

Six (6) hours

DropBox

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.

UWSCollege Pty Ltd! !

Chapter 1: Introduction to programming: Study tools

F IGURE 1.1 Chapter 1:


Introduction to
programming checklist

F IGURE 1.2 Chapter 1:


Introduction to
programming notes

F IGURE 1.3 Chapter 1:


Introduction to
programming feedback

Use this checklist to


prepare for assessments.

Use this widget to create


study notes for this
chapter.

Provide your tutor with


feedback about your
knowledge and
understanding of the
chapter.

UWSCollege Pty Ltd! !

S ECTION 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 oce workers. The
following blog explains why engineers and scientists
need to learn programming skills: http://bit.ly/UxwLpV/

Student activity 1
F IGURE 1.4
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! !

F IGURE 1.5 Chapter 1:


The greatest
engineering
achievements of the
20th century: YouTube

F IGURE 1.7 Computer

http://bit.ly/1ym9oz9

F IGURE 1.6 Chapter 1:


The greatest
engineering
achievements of the
20th century: QR code
Viewed 30 December 3013. <www.downstech.com.au>.

UWSCollege Pty Ltd! !

S ECTION 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

F IGURE 1.8 Computer


architecture: YouTube

http://www.youtube.com/watch?
v=HEjPop-aK_w

F IGURE 1.9 Computer


architecture: QR code

Source: Gaddis, T. 2012, Starting out with C++: From control structures
through objects, Pearson Addison-Wesley, Boston.
UWSCollege Pty Ltd! !

Computer hardware

Secondary storage

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.

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 dierent types of input devices such
as keyboard, mouse, scanner, digital camera, joy sticks and
microphones.

Central processing unit


The central processing unit (CPU) is the brain of the
computer. The CPUs 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).

Output devices
We use output devices to output data from the computer.
There are many dierent output devices such as monitors,
printers and speakers.

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.

Student activity 2

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 o, it will be deleted.

UWSCollege Pty Ltd! !

F IGURE 1.10 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.

10

Computer software

Student activity 3

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.

Write a software specification for


the gaming lab for Nirimba
campus.

F IGURE 1.11
Student activity 3

Prepare a report on software


applications used by engineering
professionals. You can use as
many dierent sources to
research on this including the
internet, engineering magazines,
interviewing engineering
professionals, etc.

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.

UWSCollege Pty Ltd! !

11

S ECTION 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 dierent 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

F IGURE 1.12 Student


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 dierent 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 computers screen. However, all
dierent 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.

T ABLE 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

S ECTION 4

Structured programming
Structured programs involve using dierent
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

S ECTION 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 dierent 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! !

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.

15

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.

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 dierent 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
!

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.

Code the program

Generate the executable code from your program

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 dierent 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.

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.

Test the design

UWSCollege Pty Ltd! !

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.

16

S ECTION 6

Integrated development environment


An integrated development environment (IDE) consists of
dierent 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 computers main memory.
Step 6: Run the executable code.
UWSCollege Pty Ltd! !

17

18

S ECTION 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

F IGURE 1.13 Code::Blocks web link

The links on the following page take you to a


video which shows how to install and test Code::Blocks IDE.

UWSCollege Pty Ltd! !

These links will show you how to install and test Code::Blocks:

F IGURE 1.14 How to


install and test
Code::Blocks: YouTube

UWSCollege Pty Ltd! !

F IGURE 1.15 How to


install and test
Code::Blocks: QR
Code

19

S ECTION 8

End of chapter review questions


Answer the end of chapter review questions on
the following page.

UWSCollege Pty Ltd! !

20

1.

Explain the dierent 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 dierent components in Code::Blocks IDE.

F IGURE 1.16 End of


chapter review questions

UWSCollege Pty Ltd! !

21

C HAPTER 2

Understanding a simple C++ program


Chapter overview

Reading resources

In this chapter students will learn about:


the parts of a C++ program

UWSCollege 2014, Introductory Programming


Workbook, UWSCollege, Sydney.

literals

Introductory Programming vUWS site.

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).

UWSCollege Pty Ltd! !

22

S ECTION 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

F IGURE 2.12 Program 2.1: HelloWorld.cpp

F IGURE 2.13 Program 2.1: output console window

Line 1: #include <iostream>

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.

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.

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.

(Note that there is no semicolon (;) at the end of


preprocessor directives.)

Lines 5 and 9: {}
Every C++ function opens with a left curly bracket ({) and
ends with a right curly bracket (}). Curly brackets are used

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
UWSCollege Pty Ltd! !

24

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.

F IGURE 2.14 Chapter 2,


Section 1: Structure of a
C++ program. Weblink

F IGURE 2.15 Chapter 2,


Section 1: Structure of
a C++ program - QR
code. Weblink

http://bit.ly/1r55MN8

UWSCollege Pty Ltd! !

25

Student activity 1

Student activity 2

Complete the blanks below by explaining the use of each


special character in a simple C++ program.

Use arrows to indicate the


correct order of the lines in
the code puzzle.

F IGURE 2.18 Student


activity 2

When/where did we
see it?

Character

Name

hash sign

<>

Open/close
brackets

()

Open/close
parentheses

{}

Open/close
curly bracket

Semicolon

F IGURE 2.17 Code puzzle

F IGURE 2.16 Student


activity 1

UWSCollege Pty Ltd! !

26

S ECTION 2

Literals, identifiers, variables and constants


Literals and variables
A program can use two dierent 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 computers memory
while a program is running.

Literals
We can hard code dierent types of data such as numbers, texts and
keyboard characters. They are called literals. Table 2.1 specifies dierent
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.

F IGURE 2.19 Program 2.2: unitDetails.cpp

Variables
Variables store data used by the program in the
computers 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.

F IGURE 2.20 Program 2.2: Output console window

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

29

T ABLE 2.2 Examples of variable definitions


Variable definition

Variable type

Variable(s) name

Int

distance

Float

acceleration

Int

weight1,weight2

int distance;
float acceleration;

int weight1, weight2;

F IGURE 2.21 C++ KeyWords (Gaddis, 2012)

UWSCollege Pty Ltd! !

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),

Integer data types


There are six dierent 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 variables
memory location are varied depending on the operating
system. Table 2.3 shows the size and range of dierent
integer data types typical on many computer systems.


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:

F IGURE 2.22 YouTube:


C++ Console lesson 4:
Basic data types

eg double total_force;

double totalForce;

F IGURE 2.23 C++


Console lesson 4:
Basic data types:QR
code

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.
http://bit.ly/Ukk7KW

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.

UWSCollege Pty Ltd! !

T ABLE 2.3 Different integer data types (Gaddis, 2012)


Size (bytes)

Range

Short

-32,768 to +32,767

unsigned short

0 to +65,535

Int

-2,147,483,648 to +2,147,483,647

unsigned int

0 to 4,294,967,295

Long

-2,147,483,648 to +2,147,483,647

unsigned long

0 to 4,294,967,295

E notation

123

1.23 102

123

25.4

2.54 101

25.4

0.0086

8.6 10-3

0.0086

30

Size

Float

4 bytes

Double

8 bytes

Description

Range

Single
precision

3.4E-38 and
3.4E38

Double
precision

1.7E-308 and
1.7E308

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 computers memory as
small integer values,

eg char user_selection=a;

char first_letter= D;

Boolean data type

Scientific notation

Data type

T ABLE 2.4 E notation (Gaddis, 2012)

UWSCollege Pty Ltd! !

T ABLE 2.5 Different floating data types

There are three dierent 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.

Number

We can use float or double data type to store floating point


numbers, depending on the level of accuracy you require in
the data.

Floating point data types


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.

31

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;

F IGURE 2.24 Program 2.3: string.cpp

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! !

2.

Which of the following are valid variable names?

32

F IGURE 2.25 Program 2.3: Output console window

Student activity 3
1.

a.
b.
c.
d.
e.
f.
g.

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

velocity
total force
force_x_direction
y(force)
totalForce
1stdistance
weight1

F IGURE 2.26 Student


activity 3

unitNumber
unit-number
UWSCollege Pty Ltd! !

33

S ECTION 3

Comments
Comments are used to explain our programs or hide an unwanted part of a
program from the compiler. There are two dierent 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.

F IGURE 2.27 Program 2.4: HellowWorld.cpp with file header

UWSCollege Pty Ltd! !

34

S ECTION 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;


term.

// displays the content of the variable

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.
http://labor-liber.org/en/gnu-linux/introduction/
input_output - viewed 2 July 2014

UWSCollege Pty Ltd! !

35

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
T ABLE 2.6 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

S ECTION 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

S ECTION 6

End of chapter review questions


End of chapter review questions: Q1
1.

F IGURE 2.29 End of


chapter review
questions: Q.1

Circle the errors in Program 1:

F IGURE 2.28 Program 1

UWSCollege Pty Ltd! !

38

End of chapter review questions: Q2


2.

Circle the errors in Program 2:

F IGURE 2.30 End of


chapter review
questions: Q2

F IGURE 2.31 Program 2

End of chapter review questions Q3-5


F IGURE 2.32 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

C HAPTER 3

Arithmetic operators and interactivity


Chapter overview

Suggested chapter duration

In this chapter students will learn about:

12 hours

arithmetic operators

Reading resources

mathematical functions library in C++

UWSCollege 2014, Introductory Programming


Workbook, UWSCollege, Sydney.

designing and coding interactive programs, and


designing and developing interactive programs.

Introductory Programming vUWS site.

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.

UWSCollege Pty Ltd! !

40

Chapter 3: Arithmetic operators and interactivity: Study tools

F IGURE 3.1 Chapter 3:


Arithmetic operators and
interactivity: Checklist.

F IGURE 3.2 Chapter 3:


Arithmetic operators and
interactivity: Notes.

F IGURE 3.3 Chapter 3:


Arithmetic operators and
interactivity: Feedback.

Use this checklist to


prepare for assessments.

Use this widget to create


study notes for this
chapter.

Provide your unit tutor


with feedback about your
knowledge and
understanding of the
chapter.

UWSCollege Pty Ltd! !

41

S ECTION 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.

F IGURE 3.5 C++


program - Operators:
QR code

F IGURE 3.4 C++


program - Operators:
Web link

http://bit.ly/1dQnRW4

UWSCollege Pty Ltd! !

Addition (+)

Code example

Result

double temperatureCelcious,
temperatureKelvin=50.0;
temperatureKelvin=86
temperatureKelvin=
.5
temperatureCelcious+36.5;

int width=5,length=7;
area=width*length;

Area=35

int distance=22, time=4;


double speed= distance/time;

speed=5

double distance=22, time=4;


double speed= distance/time;

speed=5.5

double distance=22, time=4;


double speed= distance/time;

Remainder=1

42

Student activity 1
Refresh your memory on division at www.mathsisfun.com/
long_division.html.

double temperatureCelcious,
temperatureKelvin;
temperatureCelcious=
Subtraction (-) temperatureCelcious = 100.0;
63.5
temperatureCelcious =
temperatureKelvin - 36.5;
Multiplication
(*)

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.

TABLE 3.1 Common arithmetic operators


Operator

F IGURE 3.6 Student


activity 1: long division:
Web link

F IGURE 3.7 Student


activity 1: long
division: QR code

Division (/)

Modulus (%)

http://bit.ly/1a3lJ20

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
UWSCollege Pty Ltd! !

43

Student activity 2

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.

Operator precedence

F IGURE 3.8 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.

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.

x = 5 + 6;
x = 5 + a;
x = a + b;
y = 4.5 + a;
y = 3.2 + d;
y = c + d;
x = b - 1;
x = b - a;
y = c - d;
x = a * b;
y = 2 * d;
y = c * d;
x = b / a;
y = c / a;
y = 5 / 2;
y = 5.0 / 2;
y = 5 / 2.0;
y = c / d;
x = 8 % 3;
x = b % a;

UWSCollege Pty Ltd! !

F IGURE 3.10 Precedent


rules: QR code

F IGURE 3.9 Precedent


rules: Web link

http://bit.ly/1ipqju8

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.

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.

Student activity 3
1.

int x = 5 + 4 * 2;

The complete list of precedence rules in C++ can be found


at http://bit.ly/1ipqju8.

2.

int x = (5 + 4) * 2;

The following video explains the arithmetic operators in


C++.

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;

F IGURE 3.11 Buckys


C++ Programming
tutorials - 7 - Basic
Arithmetic: YouTube

44

F IGURE 3.13 Student


activity 3

Find the correct value of x.

1. F IGURE 3.12 Buckys


C++ Programming
tutorials - 7 - Basic
Arithmetic: QR code

10. int x = (3 + 4) *(12 7) % 3;

http://bit.ly/1gtdteH

UWSCollege Pty Ltd! !

45

S ECTION 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.

F IGURE 3.14 Chapter


3: Section 2: C++
<cmath>: QR code

F IGURE 3.15 Chapter 3:


Section 2: C++ <cmath>:
Web link

http://bit.ly/1idccpz

UWSCollege Pty Ltd! !

T ABLE 3.2 Some common functions available in cmath


library
Function
name

Description
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);

46

Student activity 4
F IGURE 3.16 Student
activity 4

Write a C++ program to


perform following
calculations and display the
results.

Example

sqrt(x)

1.

73

2.

5+3
5.6
4 + 62

3.

6
+ 7.53+2
12

4.

5.

sin(60 o)

sin
2

6.
7.

sin(x) cos(2x) where x =

8.

2e 3

9.

9.8ln 51

10. log 7- 4

UWSCollege Pty Ltd! !

47

S ECTION 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
F IGURE 3.17
read the data from the user. We need to choose a suitable data type
Pseudocodes: Web link
such as integer, double, etc to store data entered by the user.

F IGURE 3.18
Pseudocodes: QR
code

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! !

http://bit.ly/1iRlytU

48

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.

T ABLE 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

F IGURE 3.19
Flowcharts: Web
link

F IGURE 3.20
Flowcharts: QR
code

http://bit.ly/1dbVX6Z

UWSCollege Pty Ltd! !

49

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

51

F IGURE 3.21 Program 3.2: ReadMultipleDataVer1.cpp

F IGURE 3.22 Program 3.2: ReadMultipleDataVer1.cpp

UWSCollege Pty Ltd! !

F IGURE 3.23 Program 3.2: ReadMutipleDataVer2.cpp

F IGURE 3.24 Program 3.2: ReadMutipleDataVer2.cpp

UWSCollege Pty Ltd! !

Student activity 5

52

F IGURE 3.25 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 users weight

//in kilogram.

return 0;

UWSCollege Pty Ltd! !

53

S ECTION 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


Purpose of the
program

Calculate area of a rectangle using the


values entered

Inputs

width, length

Outputs

area

Pseudocode
BEGIN
1.

DISPLAY This program calculates area of a


rectangle.

2.

DISPLAY Enter the width of the rectangle (in cm):

Step 2: Design the program solution

3.

INPUT width

Screen design for the program

4.

DISPLAY Enter the length of the rectangle (in cm):

This program calculates area of a rectangle.

5.

INPUT length

Enter the width of the rectangle (in cm): 2

6.

area= width*length

Enter the length of the rectangle (in cm): 10

7.

INPUT Area of the rectangle is, area, square


centimetres.

Area of the rectangle is 20 square centimetres.

UWSCollege Pty Ltd! !

END
!

Flowchart

54

T ABLE 3.4 Test data


Data set 1

Data set 2

Width

2.4

Length

3.6

Area

40

8.64

Input data
Expected
output

The following two tables shows desk checking table for two
sets of test data.

T ABLE 3.5 Data set 1


Line
number

Width

Length

Area

Console output

This program calculates


area of a rectangle.

Enter the width of the


rectangle (in cm):

5
Enter the length of the
rectangle (in cm):

4
5

40
Area of the rectangle is
40 square centimetres

Step 4: Test the design


We will use the following test data to test our design and
program.
UWSCollege Pty Ltd! !

55

int main()

T ABLE 3.6 Data set 2


Line
number.

{
Width

Length

Area

Console output

double width,height,area;

This program calculates


area of a rectangle.

Enter the width of the


rectangle (in cm):

// read width from the user

Enter the length of the


rectangle (in cm):

cin >> width;

cout << "This program calculates area of a rectangle.\n";

cout << "Enter the width of the rectangle (in cm):\";

2.4

4
5

// read length from the user

3.6

cout << "Enter the length of the rectangle (in cm):\n";

8.64
Area of the rectangle is 40
square centimetres

cin >> length;


// calculate area

Step 5: Write the program

area = width * length;

/*
Name

// Display the area of the rectangle


: rectArea.cpp

cout << "Area of the rectangle is " << area

Description: This program asks user to enter

<< " square centimetres./n";

the width and height of a rectangle

return 0;

and calculate and display the area of a rectangle.


Author
Date

: Buddhima De Silva
: 30/12/13 05:00

*/
#include <iostream>
using namespace std;
UWSCollege Pty Ltd! !

56

57

Step 6: Test the program


F IGURE 3.26 Test data set 1

F IGURE 3.27 Test data set 2

UWSCollege Pty Ltd! !

S ECTION 5

End of chapter review questions


Answer the end of chapter review questions on
the following page.

UWSCollege Pty Ltd! !

58

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 = 4r2
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.

F IGURE 3.28 End of


chapter review questions

UWSCollege Pty Ltd! !

59

C HAPTER 4

Control structures
Chapter overview

Learning outcomes

In this chapter students will learn about:

At the completion of this chapter, students should be able


to:

relational operators
if control structure
if-else control structure

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.

logical operators
if-else-if control structure
nested if control structure, and
the switch control structure.

Suggested chapter duration


15 hours

UWSCollege Pty Ltd! !

60

S ECTION 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 dierent 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

S ECTION 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

Student activity 1

T ABLE 4.1 Relational operators


Meaning

Pseudocode

C++ syntax

Greater than

>

>

Provide a C++ statement for the following pseudocodes,


and give the result for each (True or False value).

Less than

<

<

Assume x = 5 and y = 7.

Greater than or equal to

>=

>=

The first one has been done for you.

Less than or equal to

<=

<=

Equal to

<==

<==

Not equal to

<>

!=

Psuedocode

C++ statement

Result

a. x > y

x>y

FALSE

b. x >= y
c. x < 8

Note

d. x <= y

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.

e. x == y

Not equal to is represented differently in program


design and C++. The syntaxes of other relational
operators are similar in program design and C++.

h. x < (y/2)

f.

x <> y

g. (2 + x) <= y

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.

UWSCollege Pty Ltd! !

F IGURE 4.7 Student


activity 1

63

S ECTION 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! !

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.

F IGURE 4.8 The simple


selection control structure
flowchart

Is condition true?

true

false

Statement(s)

64

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

T ABLE 4.2 Pseudocode and C++ syntax for if control structure


Pseudocode

C++ syntax
if (condition)
{
Statement1;
Statement2;
....................
.......................
}

IF condition THEN
Block of statements
ENDIF

UWSCollege Pty Ltd! !

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

65

Flowchart

C++ program and output

F IGURE 4.9 testSpeed program flowchart

F IGURE 4.11 testSpeed.cpp

BEGIN

DISPLAY
This program tests your speed limit.
DISPLAY Enter the speed (in km/h):

INPUT.speed

F IGURE 4.10 Output with input test data, speed = 110


speed>90

true

DISPLAY
Reduce your speed
false

END

UWSCollege Pty Ltd! !

66

F IGURE 4.12 Output with input test data, speed = 25

Student activity 2
1.

Circle the errors in the following code segments:

F IGURE 4.13
Student activity 2,
Question 1

a. if (marks = 100) cout<<congratulations;


b. if (marks =< 50) cout<<you need more eort;
2.

F IGURE 4.14
Student activity
2, Question 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

S ECTION 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.

F IGURE 4.15 The if-else control structure flowchart

Is condition true?

true

false

Statement(s)

Statement(s)

UWSCollege Pty Ltd! !

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.

F IGURE 4.16 How to


write selection control
structures in C++:
YouTube

68

F IGURE 4.17 How to


write selection control
structures in C++: QR
code

T ABLE 4.3 Pseudocode and C++ syntax for if-else


control structure
Pseudocode

C++ syntax

IF condition THEN

if (condition)
{
Statement1;
Statement 2;
.....
..

Block of statements
ELSE

http://bit.ly/1lLASIR

Program design and


C++ code

Block of statements

ENDIF

}else
{
Statement 3;
Statement 4;
.....
..

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

The following video explains how to write selection control


structures in C++.

UWSCollege Pty Ltd! !

Design and develop a program to test whether a user


entered number is odd or even and display it to the user.

69

Pseudocode

Flowchart

BEGIN

D IAGRAM 4.1 NumberTest flowchart

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

BEGIN

DISPLAY This program display


whether a user entered number is
odd or even.
DISPLAY Enter a number:

INPUT number

8.
9.

END IF

Remainder of (number/
2)==0

true

false

END
DISPLAY
number, is an
odd number

DISPLAY
number, is an
even number

END

UWSCollege Pty Ltd! !

C++ program and output

70

F IGURE 4.20 Program 4.2: Output with input test data,


number = 5

F IGURE 4.18 numberTest.cpp

Student activity 3

F IGURE 4.21
Student activity 3

1. Circle the errors in the


following code segments.

F IGURE 4.19 Program 4.2: Output with input test data,


number = 20

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

S ECTION 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! !

The following table shows the results of logical operators


when used in an expression.

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

FALSE

FALSE

FALSE

FALSE

72

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.

T ABLE 4.4 Truth table


A

Pseudocode

C++ statement

Result

TRUE

(x > y) OR (x < z)

(x > y) || (x < z)

TRUE

TRUE

(y >= x) AND (y == z)
NOT (x < 8)

The following link explains how to program logical


operators in C++.

(x <= y) AND ((x + 3)>y)


NOT (x == y)
(x < (y/2)) OR ((x + y)<z)

F IGURE 4.22 How to


program logical
operators in C++:
weblink

F IGURE 4.23 How to


program logical
operators in C++: QR
code

F IGURE 4.24 Student


activity 4

http://bit.ly/1mgxWEA

UWSCollege Pty Ltd! !

73

S ECTION 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! !

Worked example

74

Pseudocode

Problem

BEGIN

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.

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

Enabled funding is allocated to local students who earn


less than or equal to $10,000 per year.

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

D IAGRAM 4.2 enabledFundingQualifier flowchart

Student activity 5
1.

BEGIN

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?

DISPLAY-This-program-determine-whetheryou-are-qualified-for-enabled-funding-place.
DISPLAY-Enter-1-if-you-are-a-local-student?Enter-0-if-you-are-an---international-student.-

cin >> x>>y;


if (x > 5)
{
if (y<0)
z = 5;
else
z = 0;
}
else
{
if (y<10)
z = 100;
else
z = 1000;
}

INPUT-residency

residency==1

true

DISPLAY
Enter your annual income

false

INPUT-income

DISPLAY
Sorry, Only local
students are qualified for
Enabled Funding
Places.

income<=1000
false
true

DISPLAY-Congratulations,you-are-qualified-forEnabled-Funding-Place

DISPLAY-Sorry, you are not


qualified. Enabled Funding
Places are income tested

END

UWSCollege Pty Ltd! !

10

10

2.

Design test data to test the given pseudocode for


enabledFundingQualifier program.

3.

Write the C++ code for enabledFundingQualifier


program.

F IGURE 4.25
Student activity 5

76

S ECTION 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.

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.

T ABLE 4.5 Pseudocode and C++ syntax for if-else-if


control structures
Pseudocode

Worked example

C++ syntax

IF condition1 THEN

if (condition1)
{
Statement1;
Statement 2;
..
..

Block of statements
ELSE IF condition2 THEN
Block of statements
ELSE IF condition3 THEN

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.

}else if (condition2)
{

}
else if (condition3)
{

else
{

Block of statements
..
..
ELSE
Block of statements

ENDIF

Marks

Grade

75 to 100

65 to 74

50 to 64

0 to 50

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

four input data sets to validate the design of


gradeCalculator.

Flowchart
D IAGRAM 4.3 Program 4.4: gradeCalculator.cpp

T ABLE 4.6 Example gradeCalculator design

BEGIN

Student number
DISPLAY
Enter your marks:

Marks

Output

Test 1
1, 2

20

INPUT number

Your grade is F

Test 2
Marks>=75

1, 2

DISPLAY
Your grade is D

true

51

false

Marks>=65

DISPLAY
Your grade is C

true

Your grade is P

Test 3
1, 2

67

false

3
Marks>=50

DISPLAY
Your grade is P

true

Your grade is C

Test 4
1, 2

DISPLAY
Your grade is F

false

95

3
END

Your grade is D

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
UWSCollege Pty Ltd! !

79

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.

F IGURE 4.26 C++ program and output.Program 4.4:


gradeCalculator.cpp

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.

F IGURE 4.27 Student


activity 6
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
UWSCollege Pty Ltd! !

80

S ECTION 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 dierent
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 dierent animals
and get a user input value to select an animal. Based
on the users 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 switchcase statements in C++ is explained in the link below.
http://classes.mst.edu/compsci53/switchcase.htm

T ABLE 4.7 Pseudocode


Pseudocode using if-else if control Pseudocode using case control
structure
structure
BEGIN
!
DISPLAY Animal Sounds
!
DISPLAY Pig
!
DISPLAY Dog
!
DISPLAY Cow
!
DISPLAY Your choice
!
INPUT choice;
!
!
!
!
!
!
!
ELSE

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

CASE OF choice
1 :DISPLAY Oink
2 : DISPLAY Bark
!
DISPLAY Ruffruff"
3 : DISPLAY Moooo
other: DISPLAY Error
ENDCASE

!
!
!
!

DISPLAY Error
ENDIF

END

END

UWSCollege Pty Ltd! !

82

S ECTION 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.

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:

Design and write a program which calculates the


grade according to the table below and displays it to
the user.
Marks

Grade

85-100

75-84

60-69

C+

50-59

40-49

30-39

0-29

If the user presses 1, the


program should ask the user to
enter the radius of a circle and
calculate and display the area.

6.

Design and write a program which asks the user to


enter two numbers and calculate the dierence
between those two numbers. (The dierence 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

UWSCollege Pty Ltd! !

Welcome to the Simple Area Calculator.


Select one of the following options:
1. Circle
2. Rectangle
3. Triangle

F IGURE 4.28 End


of chapter review
questions

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.
!

84

C HAPTER 5

Iteration control structure


Chapter overview

Reading resources

In this chapter students will learn to:


design and program using the while loop

UWSCollege 2014, Introductory Programming


workbook, UWSCollege, Sydney.

design and program using the do-while loop, and

Introductory Programming vUWS site.

design and program using the for loop.

Chapter revision tools

Learning outcomes

Student checklist widget

At the completion of this chapter, students should be able


to:

End of chapter review questions widget

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
UWSCollege Pty Ltd! !

85

Chapter 5: Iteration control structure: Study tools

F IGURE 5.1 Chapter 5: Iteration


control structure: Checklist

F IGURE 5.2 Chapter 5: Iteration


control structure: Notes

F IGURE 5.3 Chapter 5: Iteration


control structure: Feedback

Use this checklist to prepare for


assessments.

Use this widget to create study


notes for this chapter.

Provide your unit tutor with


feedback about your knowledge
and understanding of the chapter.

UWSCollege Pty Ltd! !

86

S ECTION 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 eort 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 n1. 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 dierent 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

S ECTION 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! !

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.

89

The while loop is explained in the video in Figure 5.5.

F IGURE 5.5 Section 2: YouTube: Buckys C++


Programming tutorials 18 While loops

F IGURE 5.4 The while loop

The pseudocode and C++ syntax for a while loop is given


below.
Pseudocode

C++ syntax

WHILE <expression>
Block of Statements

while (expression)
{
Statement1;
Statement2;
..
..

ENDWHILE

UWSCollege Pty Ltd! !

90

Increment and decrement operator

F IGURE 5.6 displayNumbers flowchart

Increment operator (++) can be used to add 1 to a variable.


We can replace x = x + 1; with x++;

BEGIN

Decrement operator ( ) can be used to subtract 1 from a


variable. We can replace x = x 1; with x ;

number=(0

Often in C++ programs, you will see that increment and


decrement operators are used to shorten the code.
Is
number<=10000

Problem solving using the while loop


Worked example 5.1: Designing and writing a
program

END

false

true

Design and write a program to display numbers from 0 to


10000 using a while loop.

Display number

Problem definition
Display numbers from 0 to 10000.
(((((((((((number=number+1

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

Student activity 1
F IGURE 5.7 Program 5.1: displayNumbers.cpp

1.

What would happen if you commented-out (or deleted) the number++; statement in
F IGURE 5.8 Student activity 1
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

UWSCollege Pty Ltd! !

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
!

92

3.

4.

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.

F IGURE 5.10 Student


activity 1, Question 3:
LucidChart app

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.

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.

BEGIN
DISPLAY This program will calculate the average age
of the students

F IGURE 5.9 Section 2: YouTube: Buckys C++


Programming tutorials 19 Simple program
using a loop

DISPLAY Enter number of students in the class:

INPUT numberOfStudents

studentCount = 0

totalAge = 0

WHILE studentCount < ________________________

Display Enter age of student, (studentCount+1),:

INPUT age

___________________________________________

10

studentCount = ______________________________
ENDWHILE

11

averageAge = _______________________________

12

DISPLAY Average Age is:, averageAge


END

UWSCollege Pty Ltd! !

7.

93

The following test data can be used to test the design. Design another set of test data. Use a dierent number for
numberOfStudents.
Input data
numberOfStudents

Age

Iteration 1

Iteration 2

Iteration 3

Expected output
averageAge

8.

Write C++ program for the design you completed in Question 6.

UWSCollege Pty Ltd! !

94

Student activity 2

F IGURE 5.12 Student


activity 2: App

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.)

F IGURE 5.11 Desk check table


numberOfStudents studentContent

totalAge

DOWHILE condition

age

averageAge

DISPLAY

1
2
3

F IGURE 5.13 Student


acitivty 2

4
5
6
7
8
9
10
11
12

UWSCollege Pty Ltd! !

95

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.

F IGURE 5.14 Section 2: YouTube: Bucky's C++ Programming tutorials 20


Sentinel control program

UWSCollege Pty Ltd! !

96

S ECTION 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! !

The flowchart for the do-while loop is shown in Figure 5.15.

97

The pseudocode and C++ syntax for a do-while loop is


given below.

F IGURE 5.15 The do-while loop

Body

true

Pseudocode

C++ syntax

DO
Block of Statements

do
{
Statement;
Statement;
..
..

WHILE <expression>

} while (expression);

Problem solving using the do-while loop

Expression

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.

false

The do-while loop is explained in the video in Figure 5.16.

F IGURE 5.16 Section 3: YouTube: Buckys C++


Programming tutorials 24 Do-while loops

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

Design test data


TABLE 5.1 Design test data
Data set 1

Data set 2

Data set 3

5, 6, 4, 7, 8, 1*

4, 3, 1*

No ages entered.

3.5

age
Expected output
averageAge
numberOfstudents

*Each iteration is separated with a comma (,)

Program design
BEGIN

numberOfStudents=1

totalAge=0




DO



WHILE (age>0)

IF (numberOfStudents>0) THEN

averageAge=totalAge/numberOfStudents

DISPLAY "Number of Students=", numberOfStudents
DISPLAY "Average Age=", averageAge

ELSE

"no ages entered;"

ENDIF

DISPLAY Enter the age of a student. Enter 1 when you finished entering all the ages:
INPUT age
numberOfStudents= numberOfStudents+1
totalAge=totalAge+age

END
UWSCollege Pty Ltd! !

99

100

F IGURE 5.17 Program 5.2: calcAverageAge.cpp

UWSCollege Pty Ltd! !

4.

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.

F IGURE 5.18 Student


activity 3: Question 1

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

F IGURE 5.19 Student


activity 3: Question 2
5.

3.

What will be the output of following code segment?


int i=0;
do
{
cout<<i<< , ;
i=i+2;
}while (i<=6);

What will be the output


of following code
segment?

F IGURE 5.20 Student


activity 3: Questions 3 to 6

a. 0,1,2,3,4,5,6
b. 0,2,4,6
c. 2,4,6

int i=0;
do
{
i++;
cout<<i<< ;
}while (i<5);

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.

a. 0,1,2,3,4
b. 1,2,3,4,5
c. 0,0,0,0,0
UWSCollege Pty Ltd! !

101

S ECTION 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

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.

Body
End FOR
*Only one of the operations, increment or decrement, can
be applied in one loop statement.

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.

The for loop can be represented using a flow chart as


shown in Figure 5.20.

Step 3 Execute the body of the loop: The body of the


loop can be a single statement or a block of
statements.

F IGURE 5.21 The for loop

Step 4 Update: Usually, the computer increases or


decreases the loop control variable as specified, and the
computer then goes back to step 2.

counter=intital_value2

Problem solving using a for loop

condition

Body

true

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)

Update2Counter

Program design

false

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

The syntax of C++ for loop


for (initialisation; test condition; update)
body of the loop
UWSCollege Pty Ltd! !

103

104

F IGURE 5.22 Program 5.3: inches_to_cm.cpp

UWSCollege Pty Ltd! !

4.

Practice quiz

Design and write a program that can display the


following number pattern on the console window using
a for loop:

Click on the link below and complete the questions in the


online quiz:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10

<http://bulldog2.redlands.edu/facultyfolder/patriciacornez/
cs110/quiz7.html>

5.

Design and write a program that can display the


following number pattern on the screen using a for
loop.

Student activity 4
1.

2.

3.

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).
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

9
8
7
6
5
4
3
2
1
0

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

UWSCollege Pty Ltd! !

6.

Design and write a program


F IGURE 5.23 Student
that can display all odd
numbers between 0 and 20. activity 4

105

S ECTION 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 .

2.

Design and write a program using a while loop which


can display the following even numbers on the
console window:

Hint: radians =180

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.
F IGURE 5.24 Chapter 5: Review

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! !

questions

107

C HAPTER 6

Modularisation
Chapter overview

Suggested chapter duration

In this chapter students will learn about:

6 hours

the parts of the C++ program

Chapter revision tools

variables and constants

Student checklist widget

data types

Revision questions widget

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.
Source: www.tenouk.com/Module4.html

UWSCollege Pty Ltd! !

108

Chapter 6: Modularisation: Study tools

F IGURE 6.1 Chapter 6:


Modularisation:
Checklist

Use this widget to create


study notes for this
chapter.

Use this checklist to


prepare for assessments.

UWSCollege Pty Ltd! !

F IGURE 6.3 Chapter 6:


Modularisation:
Feedback

F IGURE 6.2 Chapter 6:


Modularisation: Notes

Provide your unit tutor


with feedback about your
knowledge and
understanding of the
chapter.

109

S ECTION 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.

F IGURE 6.4 Chapter 6,


Student activity 1

UWSCollege Pty Ltd! !

111

S ECTION 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

Structure charts
The following weblink explains the structure charts in detail.

F IGURE 6.5 Structure


charts: Web link

UWSCollege Pty Ltd! !

113

S ECTION 3

C++ functions
C++ functions
C++ function is a collection of statements to perform a task.
Figure 1.8 shows the dierence between a C++ program with
and without function.
For more information about C++ functions click on the Keynote
presentation on the following page.

Source: Viewed 24 June 2014. <www.cplusplus.com/doc/tutorial/functions>

UWSCollege Pty Ltd! !

Functions

114

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.

F IGURE 6.8 YouTube:


Buckys C++
Programming Tutorials
10 Creating functions
that use parameters

F IGURE 6.9 YouTube:


Buckys C++
Programming Tutorials
11 Creating functions
that use multiple
parameters

Creating functions that


use parameters

F IGURE 6.6 YouTube:


Buckys C++
Programming Tutorials
9 Functions

Creating a function that takes multiple parameters

F IGURE 6.7 C++ function:


Keynote presentation

Watch Buckys C++


Programming Tutorials
9 Functions
YouTube video for a
definition of functions
and why they are
useful in C++
programming.

UWSCollege Pty Ltd! !

Watch Buckys C++


Programming Tutorials 10
Creating functions that use
parameters YouTube video for
more information on creating
functions using parameters.

115

S ECTION 4

Review questions
Chapter 6: Review quiz 1
Multiple choice questions
1.

In a function header, you must furnish:


a.
b.
c.
d.
e.

2.

data type(s) of the parameters


data type of the return value
the name of the function
names of parameter variables, or
all of these.

The value in this type of local variable persists


between functions called:
a.
b.
c.
d.
e.

global
internal
static
dynamic, or
none of these.

UWSCollege Pty Ltd! !

3.

Given the following function definition:

4.

Given the following function definition.

void calc (int a, int& b)


{
int c;

c = a + 2;
a = a * 3;
b = c + a;
}

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)









a.
b.
c.
d.
e.

116

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;

123
163
363
1 14 9, or
none of the above.






a.
b.
c.
d.
e.

x = 1;
y = 2;
z = 3;
calc (x, y);
cout << x << << y << << z << endl;
123
163
363
1 14 9
None of the above.

F IGURE 6.10 Chapter 6:


Review quiz 1

UWSCollege Pty Ltd! !

117

5.

What is the output of the following program?

Chapter 6: Review quiz 2

#include <iostream>
using namespace std;

Programming challenge

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.
b.
c.
d.
e.

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 users
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 users
input for a number and call prime function to
determine the result and display the results.

202
000
222
200
002

3.

Rectangle area
a. Write a function called getLength which asks the
user to enter the rectangles length, and return
value as a double.
b. Write a function called getWidth which asks the
user to enter the rectangles width, and return value
as a double.
c. Write a function called calculateArea to accept
rectangles length and width as arguments, and
return the rectangles area.

UWSCollege Pty Ltd! !

d. Write a function called displayData that accepts the


rectangles length, width, and area as arguments
and displays them in the following format.

If the user enters 1, the program should call the


relevant function to calculate the area of a circle.

Rectangle data

Length: xxxx

If the user enters 2, the program should call the


relevant function to calculate the area of a
rectangle.

Width: xxxx

If the user enters 3, the program should end.

Area: xxxx

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
circles radius or the rectangles length or width.

e. Write a short main program that calls in these


functions and displays the results.
4.

118

Geometry calculator

d. The program should also allow the user to choose


the menu again at the end of each calculation.

a. Write a C++ function called area which takes the


radius of a circle as a parameter, calculates the
area and returns it.

e. Did you notice that you have two functions with the
same names but with dierent 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?

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): ________

UWSCollege Pty Ltd! !

F IGURE 6.11 Chaper 6:


Review quiz 2

119

Вам также может понравиться