Академический Документы
Профессиональный Документы
Культура Документы
Acknowledgements
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
I NDICATES
I NDICATES
I NDICATES
DOCUMENT TO
OPEN
I NDICATES AUDIO
I NDICATES
FILE
I NDICATES
STUDENT
INSTRUCTION
STUDENT ACTIVITY
I NDICATES
STUDENT READING
NOTE - MAKING
FILE
iii
Reader Cloud
Example applications can include students sharing devices in a school and siblings sharing a book
at home.
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.
iv
C HAPTER 1
Introduction to programming
Chapter overview
Reading resources
UWSCollege 2014, Introductory Programming
Workbook, UWSCollege, Sydney.
computer systems
Blackboard
DropBox
2.
S ECTION 1
Student activity 1
F IGURE 1.4
Student activity 1
http://bit.ly/1ym9oz9
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
http://www.youtube.com/watch?
v=HEjPop-aK_w
Source: Gaddis, T. 2012, Starting out with C++: From control structures
through objects, Pearson Addison-Wesley, Boston.
UWSCollege Pty Ltd! !
Computer hardware
Secondary storage
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.
Output devices
We use output devices to output data from the computer.
There are many dierent output devices such as monitors,
printers and speakers.
Student activity 2
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 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
F IGURE 1.11
Student activity 3
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.
11
S ECTION 3
12
Learning activity 4
List common programming languages used by engineers in your intended field of engineering
study. You may research using the internet, discuss with your teachers, etc.
Each language has 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.
Description
Key words
Identifiers
Syntax
Operators
Punctuation
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.
14
S ECTION 5
2.
3.
4.
5.
6.
7.
15
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.
16
S ECTION 6
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
These links will show you how to install and test Code::Blocks:
19
S ECTION 8
20
1.
2.
3.
4.
5.
21
C HAPTER 2
Reading resources
literals
variables
identifiers
data types
variable initialisation
constants
comments
standard output, and
best programming practices.
22
S ECTION 1
23
Lines 5 and 9: {}
Every C++ function opens with a left curly bracket ({) and
ends with a right curly bracket (}). Curly brackets are used
24
to group a block of C++ statements. We must close every curly bracket that we open.
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.
http://bit.ly/1r55MN8
25
Student activity 1
Student activity 2
When/where did we
see it?
Character
Name
hash sign
<>
Open/close
brackets
()
Open/close
parentheses
{}
Open/close
curly bracket
Semicolon
26
S ECTION 2
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.
Description
Examples
Integer
Whole numbers
123, -45
Floating point
Fractional numbers
1.34, -432.2
String
Character
A, $
27
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.
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
Variable type
Variable(s) name
Int
distance
Float
acceleration
Int
weight1,weight2
int distance;
float acceleration;
eg force is a better variable name than the variable
name f to explain the force of an object.
If a variable name consists of more than one word we can
either use an underscore (_) to separate the variable
names or use a capital letter to begin each word after the
first word to improve the readability:
eg double total_force;
double totalForce;
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.
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
eg char user_selection=a;
char first_letter= D;
Scientific notation
Data type
Number
31
#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,
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,
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.
32
Student activity 3
1.
a.
b.
c.
d.
e.
f.
g.
Valid?
Comment
unit_number
velocity
total force
force_x_direction
y(force)
totalForce
1stdistance
weight1
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.
2.
Usually we add a file header to explain the purpose of the program using
multi-line comments as shown in program 2.4.
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:
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
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
\t
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.
36
S ECTION 5
Guidelines
1.
2.
3.
4.
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.
37
S ECTION 6
38
3.
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.
******
****
**
39
C HAPTER 3
12 hours
arithmetic operators
Reading resources
2.
3.
40
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.
http://bit.ly/1dQnRW4
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
speed=5
speed=5.5
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
(*)
Division (/)
Modulus (%)
http://bit.ly/1a3lJ20
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
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;
http://bit.ly/1ipqju8
Student activity 3
1.
int x = 5 + 4 * 2;
2.
int x = (5 + 4) * 2;
3.
int x = 12 / 5 + 4;
4.
int x = 12 5 * 2 + 3 ;
5.
int x = 15 / (7 2);
6.
int x = 15 / 7 2;
7.
int x = 15 % 7 2;
8.
int x = 15 % (7 2);
9.
int x = 3 + 4 * 12 7 % 3;
44
http://bit.ly/1gtdteH
45
S ECTION 2
http://bit.ly/1idccpz
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)
int y =
abs(-6);
exp(x)
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)
double
y=sin(2.3);
cos(x)
double
y=cos(2.3);
tan(x)
double
y=tan(2.3);
46
Student activity 4
F IGURE 3.16 Student
activity 4
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.
8.
2e 3
9.
9.8ln 51
10. log 7- 4
47
S ECTION 3
F IGURE 3.18
Pseudocodes: QR
code
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.
Description
Start/end
Ellipse
Flow of
control
Arrow
with a
head
Input/
Output
Parallelo
gram
Process
Rectangl
e
F IGURE 3.19
Flowcharts: Web
link
F IGURE 3.20
Flowcharts: QR
code
http://bit.ly/1dbVX6Z
49
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.
50
51
Student activity 5
52
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()
{
//in kilogram.
return 0;
53
S ECTION 4
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.
Inputs
width, length
Outputs
area
Pseudocode
BEGIN
1.
2.
3.
INPUT width
4.
5.
INPUT length
6.
area= width*length
7.
END
!
Flowchart
54
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.
Width
Length
Area
Console output
5
Enter the length of the
rectangle (in cm):
4
5
40
Area of the rectangle is
40 square centimetres
55
int main()
{
Width
Length
Area
Console output
double width,height,area;
2.4
4
5
3.6
8.64
Area of the rectangle is 40
square centimetres
/*
Name
return 0;
: Buddhima De Silva
: 30/12/13 05:00
*/
#include <iostream>
using namespace std;
UWSCollege Pty Ltd! !
56
57
S ECTION 5
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.
59
C HAPTER 4
Control structures
Chapter overview
Learning outcomes
relational operators
if control structure
if-else control structure
1.
2.
3.
4.
logical operators
if-else-if control structure
nested if control structure, and
the switch control structure.
60
S ECTION 1
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.
62
Student activity 1
Pseudocode
C++ syntax
Greater than
>
>
Less than
<
<
Assume x = 5 and y = 7.
>=
>=
<=
<=
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
e. x == y
h. x < (y/2)
f.
x <> y
g. (2 + x) <= y
63
S ECTION 3
Is condition true?
true
false
Statement(s)
64
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
C++ syntax
if (condition)
{
Statement1;
Statement2;
....................
.......................
}
IF condition THEN
Block of statements
ENDIF
1.
2.
3.
INPUT speed
4.
END
65
Flowchart
BEGIN
DISPLAY
This program tests your speed limit.
DISPLAY Enter the speed (in km/h):
INPUT.speed
true
DISPLAY
Reduce your speed
false
END
66
Student activity 2
1.
F IGURE 4.13
Student activity 2,
Question 1
F IGURE 4.14
Student activity
2, Question 2
67
S ECTION 4
Is condition true?
true
false
Statement(s)
Statement(s)
68
C++ syntax
IF condition THEN
if (condition)
{
Statement1;
Statement 2;
.....
..
Block of statements
ELSE
http://bit.ly/1lLASIR
Block of statements
ENDIF
}else
{
Statement 3;
Statement 4;
.....
..
Worked example
Problem
69
Pseudocode
Flowchart
BEGIN
1.
2.
3.
INPUT number
4.
5.
6.
ELSE
7.
BEGIN
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
70
Student activity 3
F IGURE 4.21
Student activity 3
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).
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.
Pseudocode
C++ statement
Result
TRUE
(x > y) OR (x < z)
(x > y) || (x < z)
TRUE
TRUE
(y >= x) AND (y == z)
NOT (x < 8)
http://bit.ly/1mgxWEA
73
S ECTION 6
Worked example
74
Pseudocode
Problem
BEGIN
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
75
Student activity 5
1.
BEGIN
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.-
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
END
10
10
2.
3.
F IGURE 4.25
Student activity 5
76
S ECTION 7
77
The general format of pseudocodes and C++ codes for ifelse-if control structures is given in Table 4.5.
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.
2.
INPUT marks
3.
END
UWSCollege Pty Ltd! !
78
Flowchart
D IAGRAM 4.3 Program 4.4: gradeCalculator.cpp
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
79
2.
Output
100
75
50
62
210
0
UWSCollege Pty Ltd! !
80
S ECTION 8
81
The case control structure implement using switchcase statements in C++ is explained in the link below.
http://classes.mst.edu/compsci53/switchcase.htm
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
82
S ECTION 9
http://bulldog2.redlands.edu/facultyfolder/
patriciacornez/cs110/quiz4.html
2.
http://www.cprogramming.com/tutorial/quiz/
quiz2.html
Review questions
1.
2.
Quotient = dividend/devisor
83
3.
4.
5.
Grade
85-100
75-84
60-69
C+
50-59
40-49
30-39
0-29
6.
7.
84
C HAPTER 5
Reading resources
Learning outcomes
1.
2.
3.
4.
85
86
S ECTION 1
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.
88
S ECTION 2
89
C++ syntax
WHILE <expression>
Block of Statements
while (expression)
{
Statement1;
Statement2;
..
..
ENDWHILE
90
BEGIN
number=(0
END
false
true
Display number
Problem definition
Display numbers from 0 to 10000.
(((((((((((number=number+1
Program design
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
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.
5.
6.
BEGIN
DISPLAY This program will calculate the average age
of the students
INPUT numberOfStudents
studentCount = 0
totalAge = 0
INPUT age
___________________________________________
10
studentCount = ______________________________
ENDWHILE
11
averageAge = _______________________________
12
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.
94
Student activity 2
Complete the desk check table in Figure 5.11 with test data given in Question 7 in Student
Activity 1. (You may use the Excel spreadsheet in the app in Figure 5.12.)
totalAge
DOWHILE condition
age
averageAge
DISPLAY
1
2
3
4
5
6
7
8
9
10
11
12
95
96
S ECTION 3
97
Body
true
Pseudocode
C++ syntax
DO
Block of Statements
do
{
Statement;
Statement;
..
..
WHILE <expression>
} while (expression);
Expression
false
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
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
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
4.
Student activity 3
1.
2.
3.
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.
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
2.
3.
102
Body
End FOR
*Only one of the operations, increment or decrement, can
be applied in one loop statement.
counter=intital_value2
condition
Body
true
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
103
104
4.
Practice quiz
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
<http://bulldog2.redlands.edu/facultyfolder/patriciacornez/
cs110/quiz7.html>
5.
Student activity 4
1.
2.
3.
9
8
7
6
5
4
3
2
1
0
6.
105
S ECTION 5
Practice quiz
Click on the link below and complete the questions in the
online quiz:
<http://bulldog2.redlands.edu/facultyfolder/
patriciacornez/cs110/quiz8.html>
2.
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.
questions
107
C HAPTER 6
Modularisation
Chapter overview
6 hours
data types
Reading resources
UWSCollege 2014, Introductory Programming
Workbook, UWSCollege, Sydney.
Introductory Programming vUWS site.
Source: www.tenouk.com/Module4.html
108
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.
110
Student activity 1
Play a game in the cargo-bot app and create a solution using modularisation. Discuss the benefits of your approach.
111
S ECTION 2
112
Structure charts
The following weblink explains the structure charts in detail.
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.
Functions
114
115
S ECTION 4
Review questions
Chapter 6: Review quiz 1
Multiple choice questions
1.
2.
global
internal
static
dynamic, or
none of these.
3.
4.
c = a + 2;
a = a * 3;
b = c + a;
}
a.
b.
c.
d.
e.
116
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.
117
5.
#include <iostream>
using namespace std;
Programming challenge
void doSomething(int&);
int main ( )
{
int x = 2;
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.
Rectangle data
Length: xxxx
Width: xxxx
Area: xxxx
118
Geometry calculator
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?
Geometry calculator
3. Quit
119