Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: Structured Programming with C++
Description: Structured Programming with C++

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


Structured Programming with
C++
Kjell Bäckman

Download free books at



Kjell Bäckman

Structured Programming with C++

Download free eBooks at bookboon
...
com
ISBN 978-87-403-0099-4

Download free eBooks at bookboon
...
1

What Does It Mean to Program

13

1
...
3

Compiling and linking

16

1
...
1 Introduction

24

2
...
3

Declaring Variables

25

2
...
5

26

Initiating Variables

2
...
7

More about Assignment of Values

27

2
...
9

Input and Output

29

2
...
sylvania
...

Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges
...
Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths
...
Come and join us in reinventing
light every day
...
com

4

Click on the ad to read more

Structured Programming with C++



2
...
12

Invoice Program

35

2
...
14

Type Conversion

39

2
...
16

Game Program

41

2
...
18 Exercises

42

3

45

Selections and Loops

3
...
2 Selection

45

3
...
4

Price Calculation Program

46

3
...
6

Even or Odd

3
...
8

and (&&), or (||)

3
...
10

The switch statement

3
...


48
49
49
50
51
52
52

3
...


360°
thinking


...
deloitte
...


Discover the truth at www
...
ca/careers

© Deloitte & Touche LLP and affiliated entities
...
com
© Deloitte & Touche LLP and affiliated entities
...
deloitte
...


D

Structured Programming with C++



3
...
14

The for Loop

57

3
...
16

Double Loop

60

3
...
18

Two Dice Roll

63

3
...
20 Pools

65

3
...
22

69

Interrupting a Loop - break

3
...
24 Exercises

70

4 Arrays

73

4
...
2

Why Arrays

73

4
...
4

Initiating an Array

75

4
...
6

Comparing Arrays

76

4
...
8

80

Sales Statistics

We will turn your CV into
an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand?
We will appreciate and reward both your enthusiasm and talent
...
You will be surprised where it can take you
...
employerforlife
...
com

6

Click on the ad to read more

Structured Programming with C++



4
...
10

Two-Dimensional Array

85

4
...
12

90

Searching a Sorted Array

4
...
14 Exercises

94

5 Strings

96

5
...
2

Data Type char

96

5
...
4

Menu Program with Loop

98

5
...
6

int - char

103

5
...
8

String Array, char[]

103

5
...
10

Upper/Lower Case

106

5
...
12

Comparing Two Strings

108

5
...
14

Array with String Arrays

109

AXA Global
Graduate Program
Find out more and apply

Download free eBooks at bookboon
...
15



Sorting Strings

110

5
...
17

Concatenating Strings

112

5
...
19 Encryption

115

5
...
21

Translation Table

117

5
...
23 Exercises

120

6 Functions

123

6
...
2

123

What Is a Function

6
...
4

Calling a Function

124

6
...
6

Least of Three Numbers

127

6
...
8

Array As Parameter

130

6
...
10

Function without Return Value

135

6
...
com/Mitas
www
...
com

M

Month 16
I was a construction
M
supervisor ina cons
I was
the North Sea supe
advising and the N
he
helping foremen advis
s Real work
solve problems
he
helping
International
Internationa opportunities
al
�ree wo placements
work
or
s
solve p

Download free eBooks at bookboon
...
12

Declaration Space

138

6
...
14

Override Functions

140

6
...
16

Header Files

143

6
...
18

Parameters with Default Values

147

6
...
20 Summary

150

6
...
1 Introduction

153

7
...
3

Reading from a Stream

154

7
...
5

Attaching a File to a Stream

155

7
...
7

A Complete Reading Program

158

7
...
9

Products and Prices

161

7
...
11

Sorting a File in Memory

165

7
...
13

Copying Files

171

7
...
15 Exercises

172

8 Pointers

174

8
...
2

What Is a Pointer

174

8
...
4

Assigning Values to Pointers

175

8
...
6

cout and char Pointers

178

8
...
8

Pointer Arithmetics

179

8
...
10

Functions and Pointers

182

8
...
12 Summary

190

8
...
com

9

Structured Programming with C++



9 Structures

192

9
...
2

What Is a Structure

192

9
...
4

Declaring and Initiating Structure Variables

193

9
...
6

A Structure Program

194

9
...
8

Pointer to Structure

197

9
...
10

Structure As Function Parameter

199

9
...
12 Exercises

206

10 Answers

207

10
...
2

219

Selections and Loops

10
...
4 Strings

229

10
...
6 Files

240

10
...
8 Structures

245

Download free eBooks at bookboon
...
It contains
eight chapters, one for each lecture of the course
...
Introduction to programming
...

You will be introduced to the development tool Microsoft Visual C++ and build your first programs
...
Variables
...
You will learn what
variables are and how they are used for storing of values needed in the program
...
Selections and loops
...
The programs will also be able to repeat
operations any number of times
...
Arrays
...

5
...
Texts (strings) are handled in a special and tricky way in C++
...

6
...
In this chapter, when our programs are getting to some size, we divide the code into subroutines
or functions
...
Files
...
Here we will learn the basics of file management
...
Pointers
...

9
...
Data is often organized into structures, which means easier input and output of structured data
...

Each chapter contains theoretical parts and programming examples
...
At the end of the book you will find solutions to the exercises
...
Therefore, my recommendation is that you as far as possible try to manage without the solutions
...
Therefore, I will emphasize how to focus on the problem solution and prepare the coding
...
You will
learn how to use JSP to build your solution
...

Primarily, this is a beginner’s course in C, but we will utilize some C++ tools for e
...
input and output
...
It requires long-term and patient work with reading, coding, testing and
debugging
...

I would also like to stress that, when you write your programs, you will make many mistakes
...
No
programmer writes the correct code already from the beginning
...


Download free eBooks at bookboon
...

Kjell Bäckman
Department of Economy and Informatics
University West, Trollhättan
Sweden

Download free eBooks at bookboon
...
1

What Does It Mean to Program

1
...
1 Algorithm
Programming is not only coding
...
When refined to a level deep enough, you have created an algorithm
...

Suppose you have a problem that needs to be solved
...
Then you start from the beginning again and focus on one operation
at a time and find out whether the operation needs to be refined to more detailed steps
...
This refinement process goes on until you arrive at a level deep enough to start coding
...
Many people
do the mistake of starting to code at once, which makes you focus on code details and forget the actual problem to be
solved
...

That’s why we emphasize that you structure your logic train of thought and construct a good algorithm before starting
to code
...
1
...
JSP is an abbreviation for Jackson Structured Programming and is a commonly
Structured Programming with C++
Department of Economy and Informatics
used instrument for logic structuring
...

You are supposed to create a program that calculates the price of a product to be bought by a customer
...
Thediscount, should then calculate the relevant discount, add tax and
calculate the relevant program add tax and show the customer price
...
A JSP graph could look as look as follows:

Price

Enter information

Deduct discount

Add tax

Print

The upper box is the name of the program
...
We at an split the solutionYou read the stepsan overview level
...
into four steps at from left to
right
...
As you probably realize the algorithm is too rough tois too roughwrite code
...
So we proceed by refining the solution to the next level:
refining the solution to the next level:
Price

Enter information

Deduct discount

Add tax

Download free eBooks at bookboon
...
We have split the solution
into four steps at an overview level
...
As you probably realize the algorithm is too rough to be able to
write code
...
In the same way we have refined the box “Deduct discount”
...
In the
instructions to the user” and “Read
same way we have refined the box “Deduct discount”
...
The shadowed boxes in
We could refine the algorithm further, but let us say that we are
the graph are the end points at the lowest level, the “leaves of the tree”
...
The These are boxes in to graph are
the end points at the lowest level, the “leaves of the tree”
...

the boxes to be used for coding, from left to right
...
the program examples of
We will the program examples JSP graphs in

1
...
3

the course
...

• Sequence – the program performs instructions in sequence, one
after the other
...
com Selection – the program selects one of several operations

depending on the prerequisites
...

on
• Iteration – the program repeats a series of instructions a certain
number of times
...
For instance, a sequence of

Structured Programming with C++

1

Introduction to Programming

• Selection – the program selects one of several operations depending on the prerequisites
...

• Iteration – the program repeats a series of instructions a certain number of times
...
For instance, a sequence of instructions can be repeated a number of times if a
specific condition is satisfied, otherwise another sequence of instructions should be performed a specific number of times
...
If you have built up your algorithm in a correct way, it is
only a question of selecting a programming language when the coding is to take place
...

In the JSP graph above the box “Calculate gross price” is refined in a sequence of three operations, from left to right:
• Look for the product in product file
• Pick the product’s price
• Multiply by quantity
The box ”Look for the product in product file” could suggest an iteration, e
...
“Read next product id until we find the
product id stated by the user”
...

• If the gross price is between 500:- and 1000:- the customer will get 8% discount
...

Here the program must do a selection
...
2 Coding
When you have refined your algorithm to a level detailed enough, it is time to write code
...
The code must of course follow the rules in effect for the programming language in question, it must follow
the syntax
...

You can in principle use any word processor or text editor you like, such as the program Notepad, Wordpad or Word
...
txt)
...
The advantage
is that you will get some support when coding
...
e
...
e
...

There are other development tools for C++ like Borland and Dev C++
...
You can use any tool, the important thing is that you learn to “think” structured programming
...
com and all program examples are tested in this environment
...
Furthermore, windows programming in the graphic Windows environment is supported
...
In this course, however, we will stick to basic structured programming
...
This means that C++ code looks complicated
to the novice
...
Programs written in C++ are very rapid due
to the fact that the compiler optimizes them to each specific processor type
...


1
...
e
...
That is the level understood by the processor
...
Thus the compilation is made in two steps, first from source code to object code, and then from object code
to machine code
...

When writing a program, you often split the code into several files of source code
...
When all source code has been compiled the different parts of the program must be linked together to one
single executable program (exe file)
...
In Visual C++ the
linking is taken care of automatically directly after the compilation
...
ie
...
admissions@ie
...
Experience: 1 YEAR
Language: ENGLISH / SPANISH
Format: FULL-TIME
Intakes: SEPT / FEB

55 Nationalities

in class

Follow us on IE MIM Experience

Download free eBooks at bookboon
...
4

1

Introduction to Programming

The First Steps with Visual C++

We will start with creating a program that prints ’Hello World’ on the screen
...
4
...
com

17

Structured Programming with C++

1
...
2

1

Introduction to Programming

File – New – New project

A window is displayed:

Select as shown by the window above
...
com

18

Structured Programming with C++

1
...
3

1

Introduction to Programming

Win32 – Win32 Console Application

Also specify the name of the program, for instance Hello, in the box after ’Name’, and indicate a suitable folder with the
’Browse’ button, where the programme is to be stored
...

Click ’OK’
...

The project is now created but contains no code files yet
...
com

19

Structured Programming with C++

1
...
4

1

Introduction to Programming

Project – Add New Item

A window is displayed:

Download free eBooks at bookboon
...

Enter a name of the file to be created in the box after ’Name’
...

A code window is displayed where you can enter code:

We will not explain all details in this program
...
The main thing is that you get started
with the system and are able to write and compile code and run programs
...
h in include statements, it should be:
#include

However, in some include statements the
...
get();

which makes the program stop and you will get an opportunity to view the console window with the
displayed output
...
get() –statements are needed:
cin
...
get();

Compile and run the program by clicking the arrow icon:

Download free eBooks at bookboon
...
It is the cin
...

We will create another program that asks the user for the unit price of a product and the quantity, and then calculates
the total price
...

One thing you should remember is that each program takes 5-6 Mbyte disk space, due to that a lot of extra files and a Debug
folder is created, which is necessary for using the debug function
...
The only thing to be saved
is the cpp file where your source code is stored, which in our example has the name Hello
...

Start a new program like in the Hello example and enter the following code:
#include ...
com

double dblPrice, dblTotal;

22

Structured Programming with C++

1

Introduction to Programming



cout << "Enter price per unit ";



cout << "Enter quantity ";






}

cin >> dblPrice;
cin >> iNo;

dblTotal = dblPrice * iNo;

cout << "The total price is " <
We will not explain all details in this program
...
We will only touch the main steps of the
program
...

The cout-line outputs a text to the screen
...
This is repeated for the quantity of the product
...

The last line outputs the total price
...
Then you will get a list of compilation errors
in the window at the bottom of the screen
...

Correct the error
...
You might need to recompile a number of times
...


1
...
5

Where Is the Program

You can in Explorer examine the folder where you saved your program
...
If you open it you will find the exe-file
...

You can also put your program at the start menu
...
Push the mouse
button on the exe-file and hold it down, draw the mouse pointer to the Start button and release the mouse button
...


Download free eBooks at bookboon
...
1 Introduction
In this chapter you will learn what a variable is, how to declare a variable, i
...
tell the computer that there is a variable in
the program, and how to assign values to variables
...
We will also present a number of programming examples with JSP graphs
...
2

Why Variables

A variable is used by the program to store a calculated or entered value
...
Example:
Variable name

Variable value

dTaxpercent 0
...
25
...
When the variable name appears in a calculation
the value will automatically be used, for example:
1500 * dTaxpercent
means that 1500 will be multiplied by 0
...

Excellent Economics and Business programmes at:

“The perfect start
of a successful,
international career
...
rug
...
com

24

Click on the ad to read more

Structured Programming with C++

2
...
The
declaration:
int iNo;
tells that we have a variable with the name iNo and that is of integer type (int)
...
An integer might for instance require 4 bytes while a decimal value might require 16
bytes
...
Different operating systems use different amounts
of bytes for the different data types
...
Also, a standard used by many people is to
allocate 1-3 leading characters to denote the data type (i for integer)
...

Below we declare a variable of decimal type:
double dUnitPrice;
double means decimal number with double precision
...
Since double
requires twice as many bytes, a double variable can of course store many more decimals, which might be wise in
technical calculations which require high precision
...

Note that C++ is case sensitive, i
...
a ‘B’ and ‘b’ are considered different characters
...


2
...
25;
iNo = 5;
Download free eBooks at bookboon
...
25, the variable iNo the value 5 and the variable dUnitprice the value 12
...
Suppose that the next statement is:
dTotal = iNo * dUnitprice;
In this statement the variable iNo represents the value 5 and dUnitprice the value 12
...

This value is then assigned to the variable dTotal
...
In programming the equal sign means that something happens, namely that the right
part is first calculated, and then the variable to the left is assigned that value
...
In the statement:
dToBePaid = dTotal + dTotal * dTaxpercent;
the multiplication dTotal * dTaxpercent will first be performed, which makes 60 * 0
...
The value 15 will
then be added to dTotal which makes 60 + 15 = 75
...


If C++ would perform the operations in the stated order, we would get the erroneous value 60 + 60, which makes 120,
multiplied by 0
...

If you need to perform an addition before a multiplication, you must use parentheses:
dToBePaid = dTotal * (1 + dTaxpercent);
Here the parenthesis is calculated first, which gives 1
...
This is then multiplied by 60, which gives the correct value 75
...
5

Initiating Variables

It is possible to initiate a variable, i
...
give it a start value, directly in the declaration:
double dTaxpercent = 0
...
25
...
25, dTotal, dToBePaid;
In addition to assigning the dTaxpercent a value, we have also declared the variables dTotal and dToBePaid, which not
yet have any values
...


Download free eBooks at bookboon
...
6 Constants
Sometimes a programmer wants to ensure that a variable does not change its value in the program
...
But when there are several programmers in
the same project, or if a program is to be maintained by another programmer, it might be safe to declare a variable as a
constant
...
25;
The key word const ensures that the constant dTaxpercent does not change its value
...
26;
A constant must be initiated directly by the declaration, i
...
be given a value in the declaration statement
...
7

More about Assignment of Values

We have seen how a variable can be initiated in the declaration and how the variable can be assigned a value in other
parts of the program
...

A variable can furthermore be changed by originating from the current value of the variable
...
Suppose
that the variable iNo from the beginning has the value 5
...
3 is then assigned to the
variable to the left, i
...
iNo
...
e
...


Download free eBooks at bookboon
...
The operator += works
in the same way
...

The operator *= implies that the variable on the left side is multiplied by the value on the right side
...
10, i
...
it is increased by 10%:
dDiscount *= 1
...

In many situations the value of a variable should be increased by 1
...

Here are two variants of code how this can be made:
iNo = iNo + 1;
iNo += 1;

Still another way:
iNo++;
Here we use the operator ++ which increases the value of the variable by 1
...

Increasing a value by 1 is called incrementation
...
e
...
Example:
iNo--;

2
...
Now we will step back a little and look
at the entire program
...
com

28

Structured Programming with C++

2 Variables

To be able to run (execute) a program, a function called main()must exist
...
Usually a program consists of several functions, but one of them must have the name main(), and the
very execution is started in main()
...
The parenthesis after main indicates that it is a function
...


A function is supposed to return a value, which could be the result of calculations or a signal that the function turned out
successfully or failed
...
In our environment it is
the operating system Windows that starts the function main()
...
void means that the function will not return any value
...
So for now you don’t need to bother
about all details, only that you write void main() in the beginning of your programs
...
It is also good programming conventions to indent the code between the curly brackets as shown
by the example above
...
When you have typed a left curly
bracket and pressed Enter, the next and subsequent lines will be automatically indented
...
9

Input and Output

A program mostly needs data to be entered from the keyboard and results to be displayed on the screen
...

The first thing to be done in this program is that the integer variable iNo is declared
...

Then, the text
Specify quantity:
will be displayed on the screen
...
With console we mean the keyboard and screen
together
...
The characters
<< are called stream operator and indicates that each character is streamed to the console
...


Download free eBooks at bookboon
...
You can regard it as an arrow directed towards
the console, i
...
the characters are streamed out to the console
...
The program stops and waits for the user to enter a value and press Enter
...

The stream operator >> is here in the opposite direction and indicates that the entered value is streamed the other way,
i
...
in to the program
...
This
implies that also the space character is streamed to the screen
...
Write
the program and run it, and experiment with space characters and different texts
...
9
...
Therefore we must tell the compiler that these functions are defined in
an external file called iostream
...
It
will then read iostream and insert the code for how cout and cin should be executed
...

Some external files use the extension
...
Another name of such a file is include
file
...


American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:

▶▶ enroll by September 30th, 2014 and
▶▶ save up to 16% on the tuition!
▶▶ pay in 10 installments / 2 years
▶▶ Interactive Online education
▶▶ visit www
...
com to
find out more!

Note: LIGS University is not accredited by any
nationally recognized accrediting agency listed
by the US Secretary of Education
...

Download free eBooks at bookboon
...
Another name of such a file is include file
...


namespace

Structured Programming with C++ 2 Variables
Some development tools, like for instance modern versions of Visual
C++, store their include files and classes with code in namespaces
...
9
...
To notify
Visual C++ about the versions of Visual used, reside in include files
Some development tools, like for instance moderninclude files to be C++, store theirthe standard and classes with code
namespace, we use (which is outside of this course) it is possible to store your own classes
in namespaces
...
TousingVisual C++ about the include files to be used, reside in the standard namespace, we
notify namespace std;
use the statement

Anusing namespace std;
Entry Program
2
...

which number the user wrote
...


The upper box shows the name of the program (Entry Program)
...
The program three boxes which

are read from left to right
...
The
three boxes which are read from left to right
...
The user will then have the opportunity
user will confirmation opportunity to enter a number
...
Last, we will show athen have the about which number the user entered
...
The
program will look like this:
#include
using namespace std;

#include
void main()
using namespace std;
{
void main()
int iNo;
{
int "Specify quantity: ";
cout <cout << ”Specify quantity: ”;
cin >> iNo;
cin >> iNo;
cout << << ”You entered: ”;
cout "You entered: ";
cout iNo;
cout << << iNo;
}
}
Copyright

Page: 24

First we must include iostream since we are going to read from and write to the console, and indicate the standard
namespace to be used
...
The cin statement implies that the program halts and waits for keyboard entry
...
Then the program continues with displaying the text “You
entered: “ followed by the value of the variable iNo
...
Write the program and run it
...

Download free eBooks at bookboon
...

We will now expand the program so that the user can enter a quantity and a price:
#include ...

Note that, when entering a decimal value, you must use a decimal point, not decimal comma
...
We have split the statement on two lines, but
you can write the whole statement on one single line
...

You could also combine the entry of quantity and price in the following way:
cout << "Specify quantity and unit price: ";
cin >> iNo >> dPrice;

First the text prompt is displayed to the user
...
The first entered value is stored in the variable iNo and the
second in dPrice
...
You must also
enter the unit price before the program can continue the execution
...
45

Download free eBooks at bookboon
...
11

2 Variables

Formatted Output

When programming for a DOS window, which we have done so far and will do during the rest of the course, there are very
limited possibilities for a nice layout of printed information, especially if you compare to common Windows environment
...
We will discuss the following:
• Fixed / floating decimal point
...
For instance the number 9 560 000 000 (fixed) might be printed as 9
...
56 x 109 (floating decimal point)
...
Many times we want to control this ourselves
...

• Number of screen positions allocated for data
...
h
...
11
...
It must reside in a
cout statement:
cout << setiosflags(ios::fixed);
The characters io in setiosflags represent input/output
...
The double
colon :: is a class operator and is used to refer to a value defined in a certain class
...
We will not go
further into classes in this course, but it does not hurt to have basic knowledge about classes
...
com

33

Click on the ad to read more

Structured Programming with C++

2 Variables

To return to letting C++ decide when to use fixed or float format, use the following statement:
cout << resetiosflags(ios::fixed);

2
...
2 Number of Decimals
To instruct the program to use a specific number of decimals, use the following statement:
cout << setprecision(2);
which specifies two decimals to be used in subsequent outputs
...
11
...
’w’ represents width
...

Remember that setw() only applies to the next value, which implies that it must be repeated for each value to be printed
...

Here is an example of how you can combine printed data with heading texts:
cout << "Number of units: " << setw(5) <<
iNo << endl;

cout << setiosflags(ios::fixed) <<
setprecision(2);

cout << "Price per unit:

" << setw(8) <<

cout << "Total price:

" << setw(8) <<

dPrice << endl;
dTotal;

This code will render an output like this:
Number of units:

10

Download free eBooks at bookboon
...
25

122
...
That requires that the
number of positions for iNo is 3 less than for the others, which correspond to the decimal point and the two decimals
...

Note that we in the cout statementsthat we in the blanks to make the heading texts be equal make the That makes it easier
heading texts be equal in length
...
makes it easier to calculate the
number of positions required in the setw() function
...
12

Invoice Program

We will now
a program where
Invoicewriteinvoice receipt likethe user is prompted for quantity and unit price of a product, and the program should
Program this:
respond with an

We will now write a program where the user is prompted for quantity
and unit price of a product, and the program should respond with an
=======
invoice receipt like this:
Quantity: 30
INVOICE
Price per unit:
42
...
75
Price per unit:
42
...
75
Total price:
1593
...
75
The program should thus calculate the total price and tax amount
...

We start with a JSP graph:
We start with a JSP graph:
INVOICE

Invoice

Entry

Calculations

Output

First, the user will enter quantity and unit price of the product (the Entry box)
...
Last, the information will be printed (the Output box)
...
Then we will calculate the total price and tax amount (the
University West, Trollhättan
Structured Programming with
Calculations box)
...

code
...
We multiply these, which gives the price without tax
...
Input data is
box gives the tax amount
...

quantity and unit price
...
We then multiply this amount by the tax percent, which
without
gives the tax amount
...

Invoice
The detailed JSP graph will then look:

Entry

Calculate price
without tax

Calculations

Calculate tax
amount

Output

Calculate
customer price

Download free eBooks at bookboon
...
h is needed to be able to
format the output on the screen*/
#include
#include
void main()
{

//Declarations
int iNo;

double dUnitPr, dPriceExTax, dCustPrice, dTax;
const double dTaxPerc = 25
...
First the price without tax
dPriceExTax = dUnitPr * iNo;
//then the tax amount


...
com

36

Click on the ad to read more

Structured Programming with C++

2 Variables

dTax = dPriceExTax * dTaxPerc / 100;
//and finally the customer price

dCustPrice = dPriceExTax + dTax;
//Output

cout << endl << "INVOICE";

cout << endl << "=======" << endl;
cout << "Quantity:

" <<

setw(5) << iNo << endl;

cout << setprecision(2) << setiosflags(ios::fixed);

cout << "Price per unit:" << setw(8) << dUnitPr << endl;
cout << "Total price:
}

cout << "Tax:

" << setw(8) << dCustPrice <"

<
As you can see we have inserted comments in the code
...

Therefore, use comments frequently, partly to explain the operations to others, and partly as a check list at maintenance
of the program some years later
...
All text between these delimiters is treated as comments
...
Another way is to begin a comment line with //, Then only that
line will be treated as comment
...
The variable iNo is an integer, while all variables capable
of storing an amount have been declared as double
...

Compare the code to the JSP graph and you will discover that we have followed the sequence of the boxes when coding
...
13

Time Conversion Program

We will now examine a common technique, namely to use the modulus operator (%) to get the decimals of a
division, to check whether a number is evenly dividable by another number, to get an interval for random numbers
and much more
...
The remainder is zero, i
...
6%3
equals 0
...
7%3 equals 1
...
e
...
For instance 7/3 equals 2
...


Download free eBooks at bookboon
...
e
...
For instance 7/3
equals 2
...

We start with a JSP graph:

We start with a JSP graph:

Time Conv

Entry

Calculate no
...

of hours

Output

Entry and output are pretty uncomplicated, while the calculation of no
...

Entry and output are pretty uncomplicated, while the calculation of no
...
Supposei
...
63/60
...
First hours requires more number by 60, the user Since both
University West, Trollhättan
Structured Programming with C++
seconds
...
Then we First we divide the entered number by 60, i
...
63/60
...
63%60 gives the remainder 3
...
might have got so
seconds makes 1 minute and 3 seconds
...
63%60 gives the remainder 3
...
We would then originate 1 minute and 3 seconds
...
The
that 63 seconds makes from the number of minutes and in enters a
large number, we might have got so many minutes that hour
calculation is shown in the JSP graph:
calculation could be done
...
The calculation is
shown in the JSP graph: Time Conv

Entry

Calculate no
...

of hours

sec%60

min/60

Output

min%60

Here is the code:

Copyright

Page: 31

Here is the code:
#include
#include
using namespace std;std;
using namespace
voidvoid main()
main()
{
{
//Declarations
int iNoOfSec, iSecLeft, iNoOfMin, iMinLeft, iNoOfHours;
//Declarations








int iNoOfSec, iSecLeft, iNoOfMin, iMinLeft, iNoOfHours;
//Entry of no
...
of seconds: ";
cin of no
...
of seconds: ";
//Number of entire minutes:
cin >> iNoOfSec;
iNoOfMin = iNoOfSec / 60;
//Number of seconds left:
iSecLeft = iNoOfSec % 60;
//Number of entire minutes:

// iNoOfMin is now the origin of the hours calculation:
iNoOfMin = iNoOfSec / 60;
iNoOfHours = iNoOfMin
//Number of seconds left: / 60;
//and no
...
com
eBooks at "Number of seconds
}

of the
= " <<
= " <<
= " <<

hours calculation:
iNoOfHours << endl;
iMinLeft << endl;
iSecLeft << endl;

38

Compile and run the program with different input
...
of minutes left:



iMinLeft = iNoOfMin % 60;

//Output



cout << "Number of hours



= " << iNoOfHours << endl;

cout << "Number of minutes = " << iMinLeft << endl;



cout << "Number of seconds = " << iSecLeft << endl;

}

Compile and run the program with different input
...
14

Type Conversion

A problem with the division operator / is that it discards the decimals from the quotient if both the numerator and the
denominator are of integer type
...
The precision will then be bad since the decimals will get lost:
int iNumerator = 7, iDenominator = 3;
cout << iNumerator / iDenominator;

This code section will give the output 2 and not 2
...


Join the best at
the Maastricht University
School of Business and
Economics!

Top master’s programmes
•  3rd place Financial Times worldwide ranking: MSc
3
International Business
• 1st place: MSc International Business
• 1st place: MSc Financial Economics
• 2nd place: MSc Management of Learning
• 2nd place: MSc Economics
•  nd place: MSc Econometrics and Operations Research
2
•  nd place: MSc Global Supply Chain Management and
2
Change
Sources: Keuzegids Master ranking 2013; Elsevier ‘Beste Studies’ ranking 2012;
Financial Times Global Masters in Management ranking 2012

Visit us and find out why we are the best!
Master’s Open Day: 22 February 2014

Maastricht
University is
the best specialist
university in the
Netherlands
(Elsevier)

www
...
nl
Download free eBooks at bookboon
...
The output will in this case be 2
...

Many times you might have declared variables as int, but still want a division with the decimals kept
...
Here we have
put double within parentheses before the variable numerator, which makes a decimal division to be performed with the
result 2
...


2
...
Examples of such situations
are game programs, pools, dice rolling etc
...
Why just 32768? It has to do with the
binary storage of numbers
...
Half of these are dedicated for negative
numbers and half to positive = 32768
...
rand is an abbreviation of random
...
e
...
The reason why it can’t be greater is that, if for instance the remainder had been 7, then 6 could be divided once
more and the remainder had been 1
...
e
...

Each time you run a program using random numbers, it will start from the same “location”, i
...
you will always get the
same series of numbers
...
Therefore you must tell the generator to start at a random
position, which is done with the function:
srand(time(0))
srand means “start random”
...
The system clock
contains the number of milliseconds since Jan 1st 1970 (different for different processors)
...

To make this work, you must include the header files stdlib
...
h
...
h’
...
com

40

Game Program C++
Structured Programming with

2 Variables

We will now write a program that uses the random number generator
and
2
...
We will also calculate the average score
...
We will also calculate the
average score
...
h>
#include //for random generator
//for formatting of output
#include ...
h>
#include ...
com

41

Page: 34

Structured Programming with C++

2 Variables

In the statement where we calculate the average we have first added the five rolls and then made a type cast to double
before we divide with iNo to not loose decimals
...

Run the programs several times
...
Also try to extend the program to also print the
5 rolls
...
17 Summary
In this chapter we have taken our first stumbling steps in C++ programming
...
We have also learnt to read and write data, and in connection to that, also present data in
a more user-friendly way by means of formatted output
...

But above all we have practiced how to build a solution to a problem by means of algorithms and JSP graphs
...


2
...
Originate from the Entry program and extend it so that the user can enter two numbers
...

2
...


Download free eBooks at bookboon
...
Extend the previous excercise so that the program prints the sum, difference, product and quotent of the two
numbers
...
Write a program that prompts the user for 3 decimal numbers and then prints them on the screen with the
decimal points right below each other
...
Originate from the Invoice program and amend it so that:
a) the user can enter a tax percent
...

6
...
The program should
then print a gas receipt like this:
RECEIPT
Volume:

=======

45
...
56 kr/l

432
...
Write a program that prompts the user for current and previous electricity meter value in kWh and the price
per kWh
...

8
...
The program should then print:
a) the sum of the integers
b) average
c)

the sum of the squared numbers

d) the sum of the cube of the numbers
9
...

10
...
8 * tempC + 32

Create the conversation with the user in your own way
...
Originate from the TimeConv program which converts a given number of seconds to hours, minutes and
seconds
...

12
...
For simplicity, you can treat all months as having 30 days
...
Write a program that prompts the user for the distance between two cities and in what speed you intend to
drive
...

14
...
The
program should respond with the speed required for the trip
...
Change the previous program so that you can enter the speed and the time for the trip
...
com distance
...
Write a program that converts a given number of Swedish ”öre” to the number of 50-öre coins, crowns,
5-crowns, 10-crowns, 20-crown notes, 50-crown notes and 100-crown notes
...
A farmer wants to build a wooden fence around a rectangular field
...
He also decides how wide the space between each board
of the fence should be
...
Help him with a program that calculates the total length
of all boards required to be bought
...
Improve the previous program so that it also takes into account the amount of board waste (10%) at cutting
the boards to suitable length
...
Extend the previous program so that you also can enter a price per meter of the boards and have the total
price printed
...
Originate from the Game program which creates random rolls of a dice
...

21
...

Five such double-rolls should be made
...
The ”lotto” game creates random numbers in the interval 1-35
...
Create a program that provides a simple lotto game set of numbers
...

23
...
Figure out how we could get random
numbers with one decimal
...
0 - 23
...


Need help with your
dissertation?
Get in-depth feedback & advice from experts in your
topic area
...
helpmyassignment
...
uk for more info
Download free eBooks at bookboon
...
1 Introduction programs, i
...
the program can do different things depending on
different conditions (selections)
...
e
...
We will introduce new symbols in our JSP
depending on different conditions (selections)
...

or until a specific condition is fulfilled (iteration, loop)
...


Selection
3
...


3
...


if statement
if (condition)

The selection situation is in C++ coded according to the following syntax:

statement1;

else

statement2;

The selection situation is in C++ coded according to the following
syntax:

The keyword if introduces the if statement
...
If the condition is true statement1
will be performed, otherwise statement2
...
If a is greater than b, the variable greatest will get a’s value
...
e
...
The result from this code section is that the variable greatest will
contain the greatest of a and b
...
com

45

Structured Programming with C++

3

Selections and Loops

Sometimes you might want to perform more than one statement for an option
...
Example:
if (a>b)
{

}

greatest = a;

cout << "a is greatest";

else
{

}

greatest = b;

cout << "b is greatest";

If a is greater than b, the variable greatest will get a’s value and the text “a is greatest” will be printed
...

Sometimes you don’t want to do anything at all in the else case
...
Otherwise nothing will be executed and the program goes on with the statements after the last
curly bracket
...
4

Price Calculation Program

We will now create a program that calculates the total price of a product
...
com 500:- you will get 10 % discount, otherwise 0 %
...
If the total exceeds
46

We will now create a program that calculates the total price of a
product
...
If the total exceeds 500:- you will get 10 % discount,
Structured Programming with C++ 3
Selections and Loops
otherwise 0 %
...
“Calculate discount” requires a closer examination
...

All the discount ”Calculate discount” are rather simple to code
...
It has a condition
included which says that the discount is different depending on
whether gross is less or greater than 500
...
That implies that only one of the boxes will be
executed
...
Already today, SKF’s innovative knowhow is crucial to running a large proportion of the
world’s wind turbines
...
h>
Up to 25 % of the generating costs relate to maintevoid main()
nance
...
We help make it more economical to create
int iNo;
cleaner, cheaper energy out of thin air
...

cout << ”Specify quantity and unit price”;
Therefore we need the best employees who can
cin >> iNo >> dUnitPrice;
meet this challenge!

dGross = iNo * dUnitPrice;
if (dGross > dLimit)
dDisc = 10;
else
dDisc = 0;

}

The Power of Knowledge Engineering

dNet = (100- dDisc) * dGross / 100;
cout << ”Total price: ” << dNet;

Plug into The Power of Knowledge Engineering
...
skf
...
The variable iNo is used to store the entered quantity
and dUnitPrice is used for the entered unit price
...
comis common among programmers to use one or a few characters in
It

the beginning of the variable name to signify the data type of the
47
variable
...

After data entry the gross is calculated by multiplying the two entered
values (quantity * unit price)
...
That implies that only one of
the boxes will be executed
...
h>
void main()
{

const double dLimit = 500;
int iNo;

double dUnitPrice, dGross, dNet, dDisc;

cout << "Specify quantity and unit price";
cin >> iNo >> dUnitPrice;

dGross = iNo * dUnitPrice;
if (dGross > dLimit)
dDisc = 10;
else

dDisc = 0;

dNet = (100- dDisc) * dGross / 100;
}

cout << "Total price: " << dNet;

The declaration shows a constant dLimit, which later is used to check the gross value
...

It is common among programmers to use one or a few characters in the beginning of the variable name to signify the data
type of the variable
...

After data entry the gross is calculated by multiplying the two entered values (quantity * unit price)
...

The if statement then checks the value of dGross
...
e
...
dDisc contains the discount percent to be applied
...

Finally the total price is printed
...
5

Comparison Operators

In the if statements in previous example codes we have so far only used the comparison operator > (greater than)
...
com

48

Structured Programming with C++

3

Selections and Loops

>= greater than or equal to
== equal to

!= not equal to

3
...
Then the modulus
operator % is used
...
e
...

//If iNo is even, the remainder of the integer
//division by 2 equals 0:
if (iNo%2 == 0)

cout >> "The number is even";

//If the remainder of the integer division by 2
//does not equal 0, the number is not dividable
//by 2:

if University West, Trollhättan
(iNo%2 != 0)

Structured Programming with C++

Department of Economy and Informatics

cout >> "The number is odd";

//Short way of codeing
...

//to 0 is regarded as false, otherwise number is odd”;
//If iNo is odd, iNo%2 gives a non zero value:

else if"The
cout >>

if (iNo%2)

3
...

Suppose the following conditions prevail:
We will now study an example of a more complicated situation
...

Otherwise if get 20% discount
...
e
...
e
...
Otherwise, i
...
if the quantity is below 50, no discount is
interval 50-100, he will get 10%
...
e
...
The situation is shown
given
...
com

49
The code for this will be:

if (iNo>100)

No
qty > 50

No
disc = 0%
message

Structured Programming with C++

3

Selections and Loops

The code for this will be:
if (iNo>100)

dDisc = 20;

else if (iNo>50)
dDisc = 10;

else
{

}

dDisc = 0;

cout << "No discount";

Here we use the keyword else if
...


3
...
In common English it can be expressed like this:
If the quantity is less than 100 and the quantity is greater than 50, the customer will get 10% discount
...
com

50

Click on the ad to read more

Structured Programming with C++

3

Selections and Loops

and
- and the quantity is greater than 50
The combination of the conditions means that the quantity lies in the interval 50-100
...
The conditions are combined with “and” which is a logical operator
...
The
code will then be:
if (iNo<100 && iNo>50)
dDisc = 10;

Suppose the situation is this:
If the quantity is greater than 100 or the total order sum is greater than 1000, the customer will get 20% discount
...
One of the conditions is sufficient to get
that discount
...
The code for this
situation will be:
if (iNo>100 || dSum>1000)
dDisc = 20;

3
...
It might happen that the user enters characters when the
program expects integers, or that he does not enter anything at all but just press Enter
...


To understand how this code works you must know that cin is a function that returns a value
...
Here is a code section that shows how it
can be used:
cout << "Specify quantity: ";
if (cin >> iNo)

dTotal = iNo * dUnitPrice;

else
{

cout << "Input error";
cin
...
get();

First we prompt the user for a quantity
...
If data entry turned out well,
Download free eBooks at bookboon
...


51

Structured Programming with C++

3

Selections and Loops

If the data entry failed, i
...
if the user entered letters or just pressed Enter, the condition is false and the statements after else
are executed
...
clear()) and the next character
in the queue is read (cin
...
This clean-up procedure must be performed to be able to enter new values to the program
...
10

The switch statement

In addition to the if statement there is another tool that allows you to perform different tasks depending on the
circumstances
...
A good example is a menu where the user enters a menu option (1, 2, 3
...
) to
make the program do different things depending on the user’s choice
...
Within parenthesis after switch there is the variable to be checked
...
If for instance opt has the value ‘A’, i
...
opt is a char variable in the example
above, then the statements below case ‘A’ are executed
...
If break is omitted, the program will continue into the next case block
...
The default block takes care of all other options, i
...
if the variable opt does not contain any of the
values ‘A’, ‘B’ etc
...
The entire switch block should be surrounded
by curly brackets
...
11

Menu Program

We will now write a menu program that illustrates how the switch statement can be used
...
The screen will look like this:
Enter 2 numbers:
1
...


7 5

Average

2
...
com

52

1
...

3
...
Then a menu isselect 1, 2 or 3, depending
numbers user 5
...

wants to view
...
the user enters two numbers
...
Finally the
First, Then the menu is displayed on the the menu the user selects an

screen and the user selects an option
...

performed
...

msg
...

The four options contain some logic, so we break down the JSP graph
further:

Menu prog

Enter values

Show menu

Show
greatest

dNo1 >
Show dNo1

dNo2 >
Show dNol2

Download free eBooks at bookboon
...

msg
...
The “Show least” is
analoguous
...


Show
greatest
Structured Programming with C++

Show
least

Show
average

3

Err
...

Selections and Loops

Since we have a selection situation where only one of the options
should be performed, of indicate this with be performed, we indicate
Since we have a selection situation where only one wethe options should a circle in the upper right this with a circle in
corner in each selection box
...

The four options contain some logic, so we break down the JSP graph
further:
The four options contain some logic, so we break down the JSP graph further:
Menu prog

Enter values

Show menu

Show
greatest

dNo1 >
Show dNo1

dNo2 >
Show dNol2

Select

Show
least

dNo1 <
Show dNo1

Perform action

Show
average

dNo2 <
Show dNo2

Err
...


dNo1+dNo2
/2

In the “Show greatest” case we perform a check: if iNo1 is the greatest, we print it, otherwise we print iNo2
...

least” is analoguous
...
The “Show least” is
analoguous
...

The code will be this:

The code will be this:

#include ...
h>
void main()
{

Copyright

Page: 48

int iOpt;

double dNo1, dNo2;

cout << "Enter 2 numbers: ";
cin >> dNo1 >> dNo2;
system("cls");
cout << "1
...


Average" << endl;

cout << "2
...
com

54

Structured Programming with C++

3

Selections and Loops

cout << dNo1;
else

cout << dNo2;

cout << " is the greatest";
break;

case 2:

if (dNo1
cout << dNo1;
else

cout << dNo2;

cout << " is the least";
break;

case 3:

cout << "The average is " << (dNo1+dNo2)/2;
break;

default:

cout << "Wrong choice";

}

}

break;

The header file stdlib
...
Then we print the menu on the screen and the user enters his choice (1, 2 eller 3) to the variable iOpt
...
If it is 1, the statements after “case 1” are executed
...
In the same way the least number is printed under “case 2”
...
If the user has entered anything else, the default statements are executed
...
12 Loops
We will now continue with another powerful tool within programming, that can make the program perform a series of
operations a specific number of times
...
We begin with an example:
We want to print a list of the numbers 1-10 and their squares:
1 1
2 4
3 9
etc
...
We print it and the square of it
...
e
...
Then we increase iNo again etc
...


Download free eBooks at bookboon
...

We have a variable, iNo, which first has the value 1
...
Then we increase the value of iNo by 1 and repeat the
process, 3
Structured Programming with C++ i
...
we print iNo and the square of iNo
...
This goes on until iNo = 10
...
A repetition is called a loop
...

a loop
...
Then a loop “Print values until iNo=10” is started
...

First the variable iNo is set = 1
...
The fact that it is a loop is shown by the
The loop consists of three boxes, which in turn print the value of iNo, the valueright corner
...
e
...
The loop goes on until iNo has reached the value 10
...
e
...
The loop goes on until iNo has reached the value 10
...
com

56

Click on the ad to read more

The while Loop
Structured Programming with C++ is a code section that performs the task:
Here 3

3
...
Then the loop follows starting
<< the * iNo << endl;
with the keyword while, followed by a condition within parenthesis
...


The while line loop follows starting as iNo keyword while, followed
First the variable iNo gets the value 1
...
For each turn of the loop iNo and iNo*iNo are printed on the
within parenthesis
...
At the the while condition
...

The while line can be read: ”As long as iNo is less than or equal to 10”
...
At the end of the loop iNo is increased by 1
...
14

The task was solved by the while loop above
...
The for loop is another
type of loop:
for (iNo=1; iNo <= 10; iNo++)
for (iNo=1; iNo <= 10; iNo++)
{
{
cout << iNo << " " <iNo * iNo << " "
}
}
This loop does exactly the same thing, namely prints the numbers 1-10 and their squares
...
The actual increase of the iNo value is managed by the parenthesis after the keyword for
...
The code block however contains only one
statement
...

parenthesis after the keyword

The parenthesis contains three parts, separated by semicolons:
for (iNo=1; iNo <= 10; iNo++)
for (iNo=1; iNo <= 10; iNo++)
initiation

condition

increase

The initiation part sets a start value ofinitiation part sets a start value of a variable, controls when to interrupt the loop
...
When the condition is the loop
...
The increase
part changes the value of some variable; mostly it is the loop variable that is increased by 1
...
The following code example shows how

the variable iNo from start is set to 2
...
com

57

while or for
When should you use the while loop and when the for loop? Many
Structured Programming with C++ 3
Selections and Loops
times you can solve the problem with both loop types, and many times
it is a question about personal preference
...
14
...
If there is an unpredictable situation, e
...
if the loop goes on until
the loop and when the for loop? that times you number the problem with both loop
When should you use the while user enters a specific value, orManythe random can solvegenerator
provides a specific number, use the while loop
...
personal preference
...
If there is an unpredictable situation, e
...
if the loop goes on until the user
enters a specific value, or that the random number generator provides a specific number, use the while loop
...

Addition Program

3
...
The user should
to the the integers 1 + 2 the user
...
requestedwill use a loop that goes from 1 to that limit and1sums the numbers
...
Then we will use a loop that goes from to that limit
and sums the numbers
...

of of accumulater, which stores the sum
...
The following loop goes from 1 to limit with the loop variable i
...
e
...
Finally we print the accumulated sum
...


#include ...
The variable i is used as loop variable, iLimit is used for storage of the user
specified limit, and iSum the accumulated sum
...
com

58

Structured Programming with C++

3

Selections and Loops

start value
...
That is why we must initiate it
with 0
...

The user will then enter a value to be stored in the variable iLimit
...
The for-condition is that i is not allowed to exceed iLimit
...

That means that the value stated by the user controls the number of turns of the loop
...
Therefore we don’t need any curly brackets surrounding
the loop
...

Compare the if statement, which works in the same way
...
This means that the variable iSum will
contain the sum 1 + 2 + 3 + …
Finally the value of iSum is printed
...
The variable should then not be declared earlier in the program
...
com

59

Click on the ad to read more

Structured Programming with C++

3

Selections and Loops

Still another way of coding:
for (int i=1; i<=iLimit; iSum+=i++);
Here the increase part of the for statement contains the code iSum+=i++
...
This means that we don’t need any repetition
code block, so we put a semicolon directly after the parenthesis
...


3
...
e
...
The inner loop will then do all its loop turns for
each turn of the outer loop
...

We will write a program that figures out all combinations of two integers whose product is 36:
1 x 36
2 x 18
3 x 12
etc
...
For each value of the first factor we will go through
Department of Economy and Informatics
the values 1-36 for the second factor and check if the product equals 36
...

First we give a JSP graph:

Product

Write text

Check product

i = 1-36

j = 1-36

*
*

Product = 36

o
Print factors

---

o

Under “Check product” we have an outer loop with the loop variable i and an inner loop with loop variable j
...
product” we are printed
...
Inside the loop we check if the
product of i and j makes 36
...


Here’s the code:
Download free eBooks at bookboon
...
h>
void main()
60
{
int i, j;
cout << "Calculation of produdt" << endl;
for (i=1; i<=36; i++)

Structured Programming with C++

3

Selections and Loops

Here’s the code:
#include ...

In the double for loop the variable i gets the value 1
...
For each
value of j we check if i*j makes 36
...
When the inner loop has finished, the next turn of

the outer loop
Roll Dice will start where i is set =2, and the inner loop starts once again and lets j run from 1 to 36
...
17 Roll Dice

So far we have mainly used the for loop
...
We will now look at a few situations where the while loop is preferred
...
We will write a program
write a program that rolls a dice until diceget 6
...
is printed
...
Then the rolls is of rolls
Here we cannot predict how long the loop will run
...
That depends on the numbers being generated
...
Therefore, the while loop is perfect
...

Let us first create a JSP graph:
Let us first create a JSP graph:

Dice

Initiate
random no
generator

Roll until 6

Roll

*

Print

*
Increase no
...
ForThen the loop is repeated
selected start position
...


until we get 6
...
When 6 has
each the of the loop the dice once more more and increase the
been achieved, the loop is number of rolls the 1
...
Here’s loop is
Download free eBooks at bookboon
...
Here’s the code:
terminated and
61

#include ...
h>
#include ...
h>
#include ...
h>
void main()
{

int iRoll=0, iNoOfRolls=0;
srand(time(0));

while (iRoll != 6)
{

}
}

iRoll = rand()%6+1;
iNoOfRolls++;

cout << iNoOfRolls;

The header file stdlib
...
h is needed for the function time(0) at
initiation of the generator
...
The reason for initiating it with 0 at the declaration is that it must hold a
value when the while loop starts
...
Any other
value will do
...

RUN LONGER
...
GAITEYE
...
com
1349906_A6_4+0
...
It must be initiated to 0, since it is increased by 1 all the time
...

The while loop contains the condition that iRoll must not be 6
...

For each turn we make another roll stored in iRoll, and the variable iNoOfRolls is increased by 1
...
The variable iNoOfRolls then contains the number
of rolls, which is printed
...
h>
#include ...
h>
void main()
{

int iRoll, iNoOfRolls=0;
srand(time(0));
do
{

iRoll = rand()%6+1;
iNoOfRolls++;

} while (iRoll != 6);
}

cout << iNoOfRolls;

The big difference is that the loop has its condition after
University West, Trollhättan
Department of Economy and Informatics
least one turn of the loop is executed before the condition

the loop body instead of before
...
This also means that the variable iRoll needs not be

initialized to 0
...


Two have a semicolon immediately after the condition
...
You

3
...
When two equal rolls have been
We will now write a program which repeatedly rolls terminated and the numbertwo“double” rolls isWhen two equal rolls
achieved, the process is two dice and checks if the of rolls are equal
...
We start and the number
have been achieved, the process is terminatedwith a JSP graph: of “double” rolls is printed
...

generator
Roll
Download free eBooks at bookboon
...


63
When having initiated the random number generator to a random start
position, the loop begins
...
When the two rolls are equal

Structured Programming with C++

3

Selections and Loops

When having initiated the random number generator to a random start position, the loop begins
...
When the two rolls are equal the loop is terminated and
the number of “double” rolls is printed
...
h>
#include ...
h>
void main()
{

int iRoll1, iRoll2, iCounter=0;

srand(time(0));
do
{




iRoll1 = rand()%6+1;
iRoll2 = rand()%6+1;

iCounter++;


} while (iRoll1 != iRoll2);



cout << "Number of attempts = " << iCounter << endl;



cout << "The rolls were " << iRoll1 << endl;

}

The program is similar to the previous with the difference that here we have two variables which store the rolls
...

Since the while condition comes after the loop body, at least one loop turn will be executed
...
If they are equal the loop is terminated and the dice score and the number of rolls are printed
...
19

Breaking Entry with Ctrl-Z

We will now use the while loop condition to contain a user input with cin
...
The entered numbers are summed
...
Here is the code:

#include ...
com

64

Structured Programming with C++

3

Selections and Loops

}

}

cout << "Average = " << (double)iSum/i << endl;

The variable iSum is used to store the sum of the entered numbers
...

The while condition contains input of a number from the user
...
One turn of the loop is then executed
...
At the end of the loop the user is prompted for yet another value
...
e
...
As
long as the user enters numbers, a new loop turn is run
...
Then the average is printed, which is calculated by dividing the sum by the number
of values
...


3
...
Since we know that a pools line contains 13 matches, we use a for loop
...
com

65

Click on the ad to read more

Pools
Programming a pools line (1, X or 2) with 13 football matches is
Structured Programming with C++ 3 of how to use the random number generator in a
Selections and Loops
another example
loop
...
First we create a JSP graph:
Pools

Initiate
random no
...
We
When having intitated the random number generator, the loop begins
do that by create a random number which is 0, 1X or 2Iffor is 0,matches
...
If it was 2, we print
which should create 1, or 2
...
do was 1, we print
random number which is 0, 1 or 2
...
If it was 1,
’2’
...
If it was 2, we print ’2’
...
h>
#include ...
h>
#include ...
h>
#include ...
com

66

Page: 60

Structured Programming with C++

3

Selections and Loops

When having initiated the random number generator with srand(), the for loop runs from 1 to 13
...
It is then checked
by the switch statement
...
For the value 0, we print ‘1’
...
For the value 2, we print
‘2’ preceded by some more blanks
...
21 Equation
We will now solve a math problem, namely to solve an equation of 2nd degree
...
The equation is:
x2 - 6x + 8 = 0
Since it is of the 2nd degree it has two roots
...
e
...

equal to 0 in our
Department of Economy and Informatics

Structured Programming with C++

We create a loop which in turn tests the values 1, 2, 3 … up to 100
...
Then we replace x by 2 and repeat the process until we find two values that match the equation
or until 100 has been reached
...
LP

Calculate roots utnil
iNo=2 or iRoot>100

*

Incr
...
iRoot

o

The count the number of roots to the equation that we have equation
The variable iNo is used tovariable iNo is used to count the number of roots to thegot
...
The variable iRoot is the x value in the equation
in the equation which which in each loop turn is used to calculate LP
...
The value of iRoot starts with
each loop turn
...

starts with = 0, we increased by 1 for each and turn
...

Here is the code:
#include ...
com
{
int iNo=0, iRoot=1, LP;
67
while ((iNo<2) && (iRoot<=100))
{
LP = iRoot * iRoot - 6 * iRoot + 8;
if (LP==0)

Structured Programming with C++

3

Selections and Loops

Here is the code:
#include ...
The first root value to be tested
is 1 (iRoot=1)
...
,
www
...
com

We do not reinvent
the wheel we reinvent
light
...

An environment in which your expertise is in high
demand
...
Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future
...


Light is OSRAM

Download free eBooks at bookboon
...
This is the actual definition of the equation
(x2 - 6x + 8)
...

Then we increase the root value by 1
...
22

Interrupting a Loop - break

Many times you don’t want to set an upper limit on the number of loop turns
...
Therefore we need a possibility to,
from inside the loop body, interrupt it, i
...
jump out of it and continue with the first statement after the loop
...
We will write a program where the user repeatedly is prompted for a number,
and the program will respond with the square root of the number
...
If so, the loop is interrupted
...
h>

#include ...
h, which contains code for a large number of math functions
...
e
...
Inside the loop body the
user is first prompted for a number
...
If the number is 0 or
positive, the loop goes on with calculating and printing the square root
...

Of course you could solve this problem without using an infinite loop, but regard this as an alternative to create loops
...
com

69

Structured Programming with C++

3

Selections and Loops

3
...
We have also learnt
how if statements can be used to check different situations and perform different tasks depending on the circumstances
...
We have also
learnt how to use the modulus operator % and how to perform conditional input of values from the user by placing the
input statement with cin inside the if condition
...

We have in this chapter also introduced loops, which are used to perform a series of operations a repeated number of
times
...

We have also extended our knowledge about the random number generator, which has been used to roll a dice and play
pools game
...


3
...
Write a program that prompts the user for two values and prints the least of them
...
Write a program that prompts the user for his age
...
Otherwise the text ”You are allowed to drive moped” should be
printed
...
Improve the previous program so that it also pays attention to the driving license age of 18
...
Write a program that prompts the user for three numbers and prints the greatest of them
...
Start from the Price Calculation program earlier in this chapter and apply a new discount of 5% if the gross
value exceeds 250:-
...
Continue with the previous program and write code for tax calculation, which is performed so that the user
is asked for whether it is food or other products that he has bought
...
The program should then add 12% tax for food, or 25% for other products
...

7
...

b) For income of 10 000 and more the base tax is always 50%
...

d) For income over 100 000 there is an extra tax addition of


20% of the portion exceeding 100 000
...

8
...

9
...

10
...
The program should then print the total value
...
Write a program that prompts the user for a price
...
com

70

Structured Programming with C++

3

Selections and Loops

500-1000 8%
1000-2000 10%
2000-5000 15%
over 5000

18%

12
...
If the quantity exceeds
20 and the total price exceeds 1000 kr, the user will get 20% discount
...
In all other cases no discount will be
given
...

13
...
Exit
14
...
Product
i
...
the numbers should be multiplied
...
Write a menu program that prompts the user for three numbers and then displays the following menu:
1
...
Greatest
3
...

16
...

17
...

18
...

19
...

20
...
This is repeated until the entered value equals 0
...
Write a program that prompts the user for integers until the entered value is evenly dividable by 3
...
In many sports the competitors get scores which are the sum of the scores given by each judge after the
highest and lowest score has been deducted
...
The entry is interrupted with Ctrl-Z
...

23
...
Change it to let the user enter the product to be used
...
Write a program that calculates the quotient of two numbers
...
All numbers up to and including 100 should be examined
...
Start from the Roll Dice earlier in this chapter
...

26
...

27
...
Complete it with a printout of all pair or rolls
...
Change the previous program to roll the dice until the sum of two rolls is 12
...
Start from the Pools program earlier in this chapter
...
g
...


X
1

2

1

2
X

1

X

1
2

Download free eBooks at bookboon
...
Write a program that randomly prints the numbers 0 and 1
...

31
...
The colour and value of the card should be printed
...
Start from the equation program earlier in this chapter
...
Write a program that solves the equation of 3rd degree (3 roots):
x3 - 9x2 + 23x - 15 = 0

360°
thinking


...


360°
thinking


...
deloitte
...


Discover the truth at www
...
ca/careers

© Deloitte & Touche LLP and affiliated entities
...
com
© Deloitte & Touche LLP and affiliated entities
...
deloitte
...


D

Structured Programming with C++

4 Arrays

4 Arrays
4
...
We will begin by declaring an array and assign values to it
...

Arrays is a fundamental concept within programming which will frequently be used in the future
...
2

Why Arrays

An array is, as already mentioned, a method of storing many values of the same data type and usage under a single variable
name
...
5
10
...
1
11
...
1

...
5
tempb = 10
...
1
tempd = 11
...
1

...
Then you would need
to write a huge program statement for the sum of the 30 variables
...
e
...
5
temp[2] = 10
...
1
temp[4] = 11
...
1

...
com

73

Structured Programming with C++

4 Arrays

The name of the array is temp
...

In this way we can use a loop, where the loop variable represents the index, and do a repeated calculation on each of the
temperatures:
for (i=1; i<=30; i++)
{
}

//Do something with temp[i];

The loop variable i goes from 1 to 30
...
e
...
In the second turn of the loop i has the value 2 and temp[i] represents the second
temperature
...
The only thing
to be modified is the number of turns that the for loop must execute
...
The loop goes from 1 to 30,
i
...
equal to the number of elements in the array
...
When the loop has completed, all temperatures have been accumulated in iSum
...


4
...
Below we declare the array temp:
double temp[31];
The number within square brackets indicates how many items the array can hold, 31 in our example
...
The indeces will automatically be counted from 0
...
If you need temperatures for the month April, which has 30 days, you have two options:
1
...
1st of April will correspond to index 0,
2nd of April to index 1 etc
...
The index lies consequently one step
after the actual date
...
Declare temp[31]
...
30th of April will
correspond to index 30
...
This means that the item temp[0] is
created ”in vain” and will never be used
...
com

74

Structured Programming with C++

4 Arrays

It is no big deal which of the methods you use, but you will have to be conscious about the method selected, because it
affects the code you write
...

Note that, in the declaration:
double temp[31];
all elements are of the same data type, namely double
...


4
...
g
...

The enumeration of the values must be within curly brackets, separated by commas
...
Therefore you could as well write:
int iNo[] = {23, 12, 15, 19, 21};
An enumeration within curly brackets can only be written in the declaration of an array
...

Send us your CV
...


Send us your CV on
www
...
com

Download free eBooks at bookboon
...
3, 14
...
7, 13
...
The loop then goes from 0 to 10
...
e
...
In the second turn of the loop i is =1 and iSquare[1] gets
the value 1*1, i
...
1
...
e
...
Each item will contain a
value equal to the square of the index
...
4
...
The result could be disastrous if you wrote:
temp[35] = 23
...
5 in the primary memory at an adress that does not belong to the array, but might
belong to a memory area used for other data or program code
...


4
...
You cannot
copy an entire array in this way:
dblTempJune = dblTempApr;
You will have to copy the values item by item by means of a loop:
for (int i=1; i<=30; i++)
{
}

dblTempJune[i] = dblTempApr[i];

Here the loop goes from 1 to 30 and we copy item by item for each turn of the loop
...
6

Comparing Arrays

What is meant by comparing whether two arrays are equal? They must contain item values that are equal in pairs
...
com

76

Structured Programming with C++
{

4 Arrays

if (dblTempJune[i] != dblTempApr[i])
eq = 0;

}

Here we let the variable eq reflect whether the two arrays are equal, where the value 1 corresponds to ”equal” and 0 ”not
equal”
...
e
...
Then in the loop we go through
item by item in the two arrays and checks if they are equal in pairs
...
If so,
the variable eq is set to 0, otherwise nothing is changed
...
If however all pairs of items are equal, the statement:
eq = 0;
will never be executed, and the variable eq will remain =1
...


4
...
The program should then print the average and all temperatures exceeding the average
...

Since describes the procedure
...
We choose to sum the temperatures at the time of entry,
Since we will calculate an average, wewhich themade of allloop:
need is sum in a temperatures
...
com

Average
77

Enter temp

Calculate
average

Print

We have made an overview JSP that mainly describes the procedure
...
We choose to sum the temperatures at the time of entry,
which is made in a loop:
Structured Programming with C++ 4 Arrays

Average

Enter temp

Enter
temp no
...
i
> avg ?

*

o
Print
temp no
...
We don’t have to detail it
...
First we print
the calculated average
...
item don’t have to detail theHowever average
...
calculated
thethe average, little more complicated
...
i
...
Then we write a loop which in turn checks each item of the
array against the calculated average
...
i
...
com

78

Click on the ad to read more

Structured Programming with C++

4 Arrays

Here is the code:
#include ...
: "<
}

}

"<
First we declare a constant iNoOfDays which is set to 30 and is used later in loops and average calculation
...
The variable dSum is initiated to 0 since it will be increased by the
value of each entered temperature
...
The item with index 0 will consequently not be used
...

The first loop takes care of entry of the temperatures
...
The variable dSum is increased by the entered temperature
...

The printout starts with the average
...
For each turn of the loop we
check whether temperature number i exceeds the average
...

Download free eBooks at bookboon
...
8

Sales Statistics

Sales Statistics

We will now give an example that shows how to use arrays and conditional input in a while statement
...
When a salesman has sold for
a specific amount, he enters his salesman number and the sales amount
...

Ctrl-Z
...
The situation is this:

A company has a number of salesmen, each with a salesman number
Furthermore, a fee per salesman should the interval 1-100
...
If the sales amount is has sold for a the fee amount,
amount
...
This goes on the amount
salesman will get a fee which is 10% of the first 50000:- plus 15% of
untilamount is 70000:- the fee with Ctrl-Z
...
If for instance the sales you terminate the entry is 10% of 50000:- a summary should be
printed with one line per salesman showing total sales amount
...
The total fee will in this case be 8000:-
...
If the sales
amount is this:
An entry from different salesmen could look likebelow 50000:- the fee is 10% of the sales amount
...
If for instance the
78 10000
sales amount is 70000:- the fee is 10% of 50000:- which gives 5000:32 500
plus 15% of the exceeding 20000:- which is 3000:-
...

2 12000
100 25000

An entry from different salesmen could look like this:

78 60000

78 10000
32 500
2 1000
2 12000
5 60000
100 25000
78 60000
2 1000
5 60000
The printout will then be:
Number

Amount

Fee printout will then be:
The
======
======
=====
Number
Amount
======
======
2 13000 1300
2
13000
5 60000 6500
5
60000
32
500
50 32
500
70000
78 70000 8000 78
100
25000
100
25000
2500
We begin with a JSP graph:

Fee
=====
1300
6500
50
8000
2500

We begin with a JSP graph:

Sales

Initialize sales

Entry

Print

We will use an array called sales with 100 items, where each item corresponds to a certain salesman
...
Therefore we
must initialize the entire array, i
...
set all its items = 0 so each salesman’s accumulated amount starts with 0
...
The declaration only allocates memory space
...
com

80

array item corresponding to the salesman number should be increased
by the entered amount
...
e
...
Note that in C++ the items of an array are not automatically set
Structured Programming with C++ 4 Arrays
to 0 at the declaration
...

Any unpredictable values present in these memory addresses will be
retained until you initialize them
...

Then we read salesman number and sales amount
...
We
Then we read salesman number and sales amount
...
We break down the “Entry” box: “Entry” box:
Sales

Initialize sales

Entry

*
Read
no and
amount

OK?

Print

*

Print
heading

Print
sales

o
Increase
sales
We read a salesman time
...
salesman number is
We read a salesman number and sales amount, one at a number and box “OK?” we one at that theIn the
box “OK?” we check that the salesman number is between 1 and 100
between 1 and 100 and that the salesand that the sales amount is not negative
...

amount is not negative
...

�e Graduate Programme

I joined MITAS because
for Engineers and Geoscientists
The box ”Print”
heading and
I wanted real responsibili� has been detailed by first printing thewww
...
com
Maersk
...
because with the printing we check that the
sales amount is not 0
...
We break down the box “Print sales”
further:

Copyright

Real work
International
Internationa opportunities
al
�ree wo placements
work
or

M

Month 16
I was a construction
M
supervisor ina cons
I was
Page: 76
the North Sea supe
advising and the N
he
helping foremen advis
s Real work
solve problems
he
helping
International
Internationa opportunities
al
�ree wo placements
work
or
s
solve p

Download free eBooks at bookboon
...
For each entered sales amount the
array item corresponding to the salesman number should be increased
by the entered amount
...
e
...
Note that in C++ the items of an array are not automatically set
Structured Programming with C++ to4 Arrays
0 at the declaration
...

Any unpredictable values present in these memory addresses will be
retained until you initialize them
...
Inis made in a with the printing
connection
Then we read salesman number and sales amount
...

we check that the sales amount is not 0
...
We
break down the “Entry” box:

We break down the box “Print sales” further:

Sales

Initialize sales

Entry

*
Read
no and
amount

OK?

Print

*

Print
heading

Print
sales

o
Increase
sales
University West, Trollhättan

Structured Programming with C++

Department of Economy and Informatics
If the sales amount exceeds 0, we calculateread fee and print one line in the summary
...
In the we will now pay
We the a salesman number and sales amount, one at fee calculation

box “OK?” we check which gives still another between 1 and
attention to whether the amount exceeds the limit 50000:-,that the salesman number isdetailed level: 100

Initialize sales

and that the sales amount is not negative
...

Sales
The box ”Print” has been detailed by first printing the heading and
then the sales values
...
Salesmen having sold nothing should not be
included in the printed summary
...
Otherwise the greater percent 15% will be applied to
the
Download free eBooks at bookboon
...
When the fee calculation is finished, the fee
and sales amount are printed
...
h>
#include ...
Otherwise the greater percent 15%
will be applied to the exceeding amount
...

Here is the code:
#include ...
h>
void main()
{

const int iMaxNo=100;

const double dLimit=50000, perc1=0
...
15;
double sales[iMaxNo], dAmount, dFee;
int i, nr;

//Initialize array

for (i=0;isales[i] = 0;

//Enter salesman info

while (cin>>nr && cin>>dAmount)
{

if (nr<1 || nr>iMaxNo || dAmount<0)
cout << "Input error" << endl;

else

sales[nr-1] += dAmount;

}

//Print summary
cout << endl

<< "Number
<< "======

Amount
======

for (i=0; i{

Fee" << endl

=====" << endl;

if (sales[i] > 0)
{

if (sales[i] <= dLimit)

dFee = perc1 * sales[i];

else

dFee = perc1*dLimit + perc2*(sales[i]-dLimit);

cout << setw(4) << (i+1) <<

setprecision(0) << setiosflags(ios::fixed) <<

setw(13) << sales[i] << setw(10) <<
dFee << endl;

} // end if

} // end for-loop

} // end main

Download free eBooks at bookboon
...
The constand dLimit =
50000 is used for the fee calculation
...

The array is declared to contain 100 items with the index 0-99
...
1 will correspond to index 0, salesman
no
...

The variable dAmount is used for entry of sales amounts and the variable dFee for fee calculation
...

Then the sales array is initialized, where we set all items to 0
...
If entry is successful, the loop continues
...

Inside the loop the program checks if the salesman number is less than 1 or greater than 100
...
In addition, the program also checks if the sales amount is less than 0
...
If everything is OK, the sales item is increased by the entered
amount
...

At loop completion (Ctrl-Z), the program goes on with printing the summary heading
...
First in the loop, we check the sales total to be
greater than 0, otherwise no line for that salesman is printed
...
If
so, the fee is calculated as the lower percent multiplied by the sales total
...


Download free eBooks at bookboon
...
Note that, when we print the salesman number, we must use the index value
increased by 1, since the index value all the time is 1 less than the salesman number
...
h to get a nice layout with straight columns
...
9

Product File, Search

We will now examine a situation where we use several arrays in parallel
...
We will organize it so that a product in the product
id array with for instance index 73 has its price in the price array at the same index position, i
...
73:
Prodid

Price

2304

152,50

3126

26,80

2415

...

Suppose we want to be able to enter a product id and get the corresponding price
...

Look at the following code section:
while (cin >> iProd)
{

for (i=1; i<=100; i++)
{

if (iProd == iProdid[i])

cout << "The price is: " << dPrice[i] <<

}

}

endl;

In the while condition we read a product id to the variable iProd
...

The inner loop goes from 1 to 100 and checks one item at a time in the product id array to equal the entered product id
...
Note that we use the same i-value in the price array as in the product id array
...


4
...
Different customer segments will then get different discount profiles
...
com

85

Structured Programming with C++

4 Arrays

Example:
Product group
1

2

3

Customer 1

10

12

13

3

14

16

17

group 2


13

14

15

If for example a customer of customer group 3 orders a product from product group 2, he will get 16% discount
...
Such an array has two indeces,
where the first index could be thought of as representing the lines in the matrix, and the second index the columns:
double dDiscount[5][8];
Here we have declared a two-dimensional array named dDiscount with 5 lines (index 0-4) and 8 columns (index 0-7)
...


Note that we all the time must use two indeces for dDiscount
...
The variable cgrp will get the value 3 and pgrp
the value 2
...
If we use the values from the discount
matrix above, we will get the printout:
Discount: 16
Let us now turn the problem the other way so that the user enters a discount percent and that the program responds
with corresponding customer group and product group
...
The code will be:
cout << "Enter percent: ";
cin >> dPerc;

for (i=1; i<=5; i++)
{

Download free eBooks at bookboon
...
A double loop then performs the search for
the entered percent, where the outer loop goes through the lines of the matrix and the inner loop through the columns
of the matrx
...
The inner loop goes through all
its values before the outer loop changes its value, which means that the matrix is searched one line at a time, where all
items in the line are checked
...

If equal, the corresponding loop counters i and j are printed, which correspond to customer group and product group
...
11 Sorting
Many times it is easier to work with an array if the items are sorted, especially when searching for a specific value
...
We will therefore discuss array sorting
...
ie
...
admissions@ie
...
Experience: 1 YEAR
Language: ENGLISH / SPANISH
Format: FULL-TIME
Intakes: SEPT / FEB

55 Nationalities

in class

Follow us on IE MIM Experience

Download free eBooks at bookboon
...
We want to write a program that sorts them by size
...
We have to write code
that systematically compares two values in turn and interchange their positions in the array
...
l means “left” and r “right”
...
The variable l has from the beginning the value 0 and r the value 1, i
...
they
point on the two first items of the array
...
9 is not less than 3, so no interchange is made
...
We increase r by 1 again
...
7 is greater than 2, so the items remain:
0
2

1

2

3

4

5

5

9

8

3

7

l

r

Now r has gone through all values, and as result we have got the least item on index position 0 in the array
...

Now we increase l by 1 and perform a new series of comparisons, where r goes from index position 2 to 5:
0
2

1

2

3

4

5

5

9

8

3

7

l
r
Download free eBooks at bookboon
...
When r arrives at index position 4, the right item (3) is less
than the lef t (5), so we interchange them
...
This is
repeated until we compare the two last items of the array:
0

1

2

2

3

4

5

3

5

7

8

9

l

r

After completion of the last comparison, the entire array is sorted
...
We use an outer loop for the l-values and an inner for the r-values:
for (l=0; l<=4; l++)
{

for (r=l+1; r<=5; r++)
{

}

}

//Check if right is less than left
//and in that case interchange

l goes from 0 (first position of the array) to 4 (next last position), while r goes from l+1 (the position to the right of l) to
5 (last position)
...
We cannot directly let two variables change values
...
e
...
This triangular exchange has the
effect that the two array items interchange their values
...


Download free eBooks at bookboon
...


4
...
For a small array with only 6 items like in the previous example, there is no big deal
...
Then the search time would be considerable and our
program would be regarded as having bad performance
...
com

90

Structured Programming with C++

4 Arrays

We will use a more refined method, namely to halve the index interval repeatedly
...
When having selected which half to continue with, we halve that
part again
...
The execution time will be reduced considerably
...


2314 2345 3123

15


...

Suppose we are searching for product id 5321
...
If so we go on with the left interval, otherwise the right
...
We check whether the searched
product id 5231 is greater or less than the product id on position 22, etc
...

We will now discuss the code for this
...
l is the left end point of the interval, which from the beginning is
0
...

The variable iFound is used to indicate whether or not the searched product id has been found
...

The variable iPos is the index for the found product id
...
com

91

Structured Programming with C++

4 Arrays

As long as the product id has not been found, we will divide the interval:
while (!iFound)
{

First we calculate the middle of the interval:
int iMid = l + (int)((r-l)/2);
From the beginning r is =30 och l=0
...
Since this division might give a decimal number, we perform
a type cast with (int) within parenthesis in front of the division
...

This half interval is added to the value of l
...
e
...

Then we check if there is a match to the middle item of the interval:
if (iSrch == iProdid[iMid])
{

}

iFound = 1;

iPos = iMid;

If the searched product id equals the product id at the position given by the variable iMid in the product array iProdid,
there is a match, and the variable iFound is set =1 and the found position is stored in the variable iPos
...
Otherwise we focus on the left half of the interval and we let the right endpoint
(the variable r) get the value of iMid
...

By the time the loop has divided the interval so many times that we certainly get a match in the statement:
if (iSrch == iProdid[iMid])
provided that the user has entered a product id that is present in the array
...
h>
void main()

Download free eBooks at bookboon
...
6745};
cout << "Enter the searched product id: ";
cin >> iSrch;

if (iSrch == iProdid[0])
{

}

iPos = 0;

iFound = 1;

if (iSrch == iProdid[30])
{

}

iPos = 30;

iFound = 1;

while (!iFound)
{

int iMid = l + (int)((r-l)/2);
if (iSrch == iProdid[iMid])
{

}

iFound = 1;

iPos = iMid;

Download free eBooks at bookboon
...
13 Summary
In this chapter we have learnt about arrays
...
We have also seen
the advantage with using loops in connection with arrays
...
You should try to really understand the algorithm
...

A sorted array is very efficient when searching for a particular value
...
The search method presented here is often called binary search
...
14 Exercises
1
...
The program should then:
a) print the first, the fifth and the tenth item
...

c) print the numbers in reversed order
...

e) ask for a number and then print all numbers less than that number
...

g) ask for a number and print the index of that number
...


h) move the first item to the last position of the array
...
Write a program that prompts the user for a month number and prints the number of days of that month
...
Write a program that creates random temperatures between 15 and 25 degrees, one temperature per day of
the month July
...
The program should then create a new array for
August and copy the July values (see the section ’Copying an Array’)
...

4
...

5
...

6
...
The program
should also print all temperatures greater than the average
...
Declare an array that contains the following nine densities for metal alloys:
1
...
8 4
...
com

94

Structured Programming with C++

4 Arrays

5
...
9 8
...
6 8
...
9
Write a program that prompts the user for a density and prints the one closest below the entered density
...
Write a program that fills an array with 25 integers between 0-9
...

9
...

10
...

11
...

12
...
Write a
program that prompts the user for a product id and prints the corresponding price
...

13
...

14
...

The user should be able to enter a product group and a customer group, and the corresponding discount
should be deducted
...
Write a program that creates 10 random rolls of a dice and stores them in an array
...

16
...
Complete the program with
initialization of the array with as many product id:s as required, and run it
...
Go on with the previous program and make it print the index position of the found product id
...
Improve the previous program so that if you enter a product id not existing in the array, a suitable message
should be printed
...
Expand the previous program with a price array that contains the prices of each product, and with a
printout of the price of the found product id
...
com

95

Structured Programming with C++

5 Strings

5 Strings
5
...
e
...
String handling is a little tricky
in C++, so we have dedicated an separate chapter to this subject
...

There are a number of string handling functions
...

In programming, string handling is important, since a user often enters information in text form which is taken care of
by the program
...


5
...
To store one character
in a variable we use the data type char
...
We can assign a value to the variable:
cLetter = 'A';
University West, Trollhättan

Structured Programming with C++

Note that we use single quotes for the character
...
3

Menu Program

Our first program user to select handle option
...
The program will first display a menu:
display a menu:
Menu
====
A
...
Invoice
C
...
Finance
Select:
Here the user can enter one of the letters A, B, CHere thechoose anenter one will not build A,full-featured order/invoice/
or D to user can item
...
We print a text about the selected order/invoice/warehouse/
warehouse/ finance system, but we will only let the program will not build a full-featuredchoice
...
We start with a JSP graph:
Download free eBooks at bookboon
...
We will not build a full-featured order/invoice/warehouse/
finance system, but we will only let the program print a text about the
selected 5 Strings
Structured Programming with C++choice
...
Then the user is prompted for a choice by means of the letters A-D
...
Then the user is
the requested option is executed, i
...
a simple text message will be printed
...
Finally the
an error message is printed
...
e
...
If the user enters another character than A-D, an error
message is printed
...
h>
void main()
#include ...
Order" << endl;
cout << "A
...
Invoice" << endl;

cout << "B
...
Warehouse" << endl;

cout << "C
...
Finance" << endl;

cout << "D
...
com

97

Structured Programming with C++

5 Strings

First a char variable is declared named cSel, and then the menu is printed with a number of cout statements
...
The
switch statement contains one case section for each option
...
The default section takes care of all characters other
than A, B, C or D
...
4

Menu Program with Loop
University West, Trollhättan

Structured Programming with C++

We will now improveEconomy and Informatics the user repeatedly can enter different options without terminating the
Department of our menu program so that
program
...
The JSP graph will then be:

Menu

Loop until 'X'

*
Clear screen

*
Display menu

A

*
Select option
o

B

o

C

o

*
Perform task

D

o

X

o

Error

o

Excellent Economics and Business programmes at:
We complete the menu with still another option, X – Exit
...
Furthermore we also
clean the screen before the menu is displayed, which is the first
operation of the loop
...
h>
#include ...
Order" << endl;
cout << "B
...
Warehouse" << endl;
cout << "D
...
Exit" << endl;
cout << "Select: ";
to discover why both socially
cin >> cSel;
and academically the University
switch (cSel)
{
of Groningen is one of the best
case 'A':
places for a student to be
cout << "You
www
...
nl/feb/education selected Order";
break;
case 'B':
Download free eBooks at bookboon
...

CLICK HERE

Structured Programming with C++

5 Strings

We complete the menu with still another option, X – Exit
...

Furthermore we also clean the screen before the menu is displayed, which is the first operation of the loop
...
h>
#include ...
Order" << endl;

===" << endl;

cout << "B
...
Warehouse" << endl;
cout << "D
...
Exit" << endl;
cout << "Select: ";
cin >> cSel;

switch (cSel)
{

case 'A':

cout << "You selected Order";
break;

case 'B':

cout << "You selected Invoice";
break;

case 'C':

cout << "You selected Warehouse";
break;

case 'D':

cout << "You selected Finance";
break;

case 'X':

cout << "You selected to exit";
break;

default:

cout << "Erroneous choice";

}

break;

cout << endl << "Press a key to continue";

Download free eBooks at bookboon
...
h
...

The first action in the loop is to clear the screen with system(“cls”)
...
e
...
That variable is checked in the switch statement, where a
text is printed corresponding the selected option
...

The method of letting the user enter an extra character to the variable temp at the end of the loop is a relatively unconvenient
solution, but it has the advantage of avoiding to struggle with special C++ features regarding input, which we don’t go
into here
...
5

Christmas Tree

We will now create a logically rather complex program that uses char variables to print a number of ’X’ on the screen
with the shape of a Christmas tree:
X

XXX

XXXXX

XXXXXXX

XXXXXXXXX

XXXXXXXXXXX

XXXXXXXXXXXXX

XXXXXXXXXXXXXXX

XXXXXXXXXXXXXXXXX

XXXXXXXXXXXXXXXXXXX

XXXXXXXXXXXXXXXXXXXXX
X
X

As you can see the tree has eleven branches and two ’X’:s to the trunk
...
Each branch consists of a number of ‘X’:s, different depending on which branch
being printed
...
We therefore need two inner loops, one that prints the leading blanks
and one that prints the ‘X’:s for each branch
...
We start with a JSP graph:

Download free eBooks at bookboon
...
Furthermore we
will have to print a suitable number of blanks before the ‘X’:s, so that
the branches are centered symmetrically around the middle trunk
...
After completion of the
C++ 5 Strings
branches we need a loop that runs two turns and that prints the ‘X’:s
for the trunk
...
We then
The JSP graph tells us that there is one outer loop for the branches,
have one inner loop that prints where eachnumber theblanks and one inner loopthen have one inner The same is true
the correct turn of of loop prints a branch
...

for the trunk where we have an loop that prints the correct number of blanks one line of the loop that one inner loop
outer loop where each turn of the loop prints and one inner trunk, and
prints the ‘X’:s
...
The code is as follows:
loop where each turn of the loop prints one line of the trunk, and one
inner loop that prints the blanks before one single ‘X’ is printed
...
h>
void main()
{
int i, j;
char x = 'X', blank = ' ';
for (i=10; i>=0; i--) //first outer for-loop
{
for (j=0; jis currently enrolling in the //first inner for-loop
cout << blank;
Interactive Online BBA, MBA, MSc,
cout << x;
DBA for (j=0;programs:j++) //second inner for-loop
and PhD j<10-i;
cout << x << x;
cout << endl;

American online
LIGS University

▶▶ enroll by September 30th, 2014 and
▶▶ save up to 16% on the tuition!
Copyright
▶▶ pay in 10 installments / 2 years
▶▶ Interactive Online education
▶▶ visit www
...
com to

Page: 97

find out more!

Note: LIGS University is not accredited by any
nationally recognized accrediting agency listed
by the US Secretary of Education
...

Download free eBooks at bookboon
...
h>
void main()
{

int i, j;

char x = 'X', blank = ' ';
for (i=10; i>=0; i--)

//first outer for-loop

for (j=0; j
//first inner for-loop

{

cout << blank;

cout << x;

for (j=0; j<10-i; j++)
cout << x << x;

}

cout << endl;

for (i=0; i<2; i++)
{

//second outer for-loop

for (j=0; j<10; j++)
cout << blank;

}

}

//second inner for-loop

//inner for-loop

cout << x << endl;

We declare a variable named x that correspond to the ’X’, and a variable named blank corresponding to the blank character
...
We have selected to let the values run
backwards to make the subsequent math easier
...

The first inner loop has a j as loop counter and goes from 0 to i
...

Since i is counted reversed, the number of blanks will decrease for each branch
...

After completion of the blanks for a bransch, first an ’X’ is printed
...

The second inner for-loop prints the ’X’:s with two ’X’:s for each turn of the loop
...
This means that according to the decrease of i, the number of printed ‘X’:s increases
...

The second outer for-loop, which builds the trunk of the tree, has i as loop counter and goes from 0 to 1 (two turns)
...
After the inner loop, an
‘X’ is printed
...
You could preferably write a scheme of how i and j changes
their values, and in that way follow the progress of the program
...
com

102

Structured Programming with C++

5
...
E
...
the character A has the code 65, B has 66 tec
...
Here is an example:
int iNo = 65;
char cChr;

//The code for A

cChr = iNo;

cout << cChr;
First we declare an integer variable, iNo, and give it the value 65
...
On the third line cChr gets the same value as iNo, i
...
65
...


5
...
e
...
The Swedish
characters Å, Ä and Ö don’t follow that pattern
...
If you for instance want to print the word ’från’, write as
follows:
cout << "fr\x86n";
If you want to assign the char variable cChr the value Ö, write this:
cChr = '\x99';

5
...
Many times you want to store a longer text
in a variable like a customer name or a product description
...
A string array works in
the same way as any other array, i
...
it has a variable name and an index value that indicates an item of the array, i
...
a
specific character of the string
...

Suppose we want the user to enter a name to the array cName:

Download free eBooks at bookboon
...
These four characters are then stored in the cName array, where the first item cName[0]
contains the character ‘J’, the second item cName[1] the character ‘o’, cName[2] the character ‘h’ and cName[3] the
character ‘n’
...
It is the so-called null character ‘\0’, which
is stored in the fifth position in the item cName[4]
...
Note that when an entire string array is printed, you don’t need
to specify any indeces in the cout statement
...

Suppose that the user in the program section above enters his entire name ’John Smith’
...
The reason to this is that when text is entered from the keyboard, only
characters up to the first blank will be stored in the array
...

A solution to this problem is to use another input function instead of cin:
char cName[30];

cout << "Enter your name: ";
cin
...
com

104

Structured Programming with C++

5 Strings

Here we use the function cin
...
This has the effect that, if the user enters ‘John Smith’, the
printout from the cout statement will be ‘Your name is John Smith’
...
The
input is not interrupted at the first blank, but the entire text line entered by the user will be stored in the variable cName
...
The reason for using 29 is to allocate space for the null character at
the end of the string as the 30th character
...
If the user enters more than 29 characters, only the first 29 are accepted
...
9

Length of a String

We will now create a little program that calculates the length of a string, i
...
the number of characters contained in the
string
...
h>
#include ...
getline(cName,29);

cout << "Your name is " << cName << endl;

cout << "Your name is " << strlen(cName) <<
" characters long" << endl;

cout << "The entire string is " << sizeof cName <<
}

" characters long" << endl;

To be able to use string functions like strlen() we must include the header file string
...

In the program we first declare a string array called cName with 29 positions plus the null character, totally 30 characters
...

In the next last cout statement the text ’Your name is 10 characters long’ is printed, provided that we have used a name
of 10 characters like ‘John Smith’
...
Here we use the operator sizeof,
which gives the declared length of the string array cName, irrespective of how many characters actually have been stored
...


Download free eBooks at bookboon
...
10

5 Strings

Upper/Lower Case

We have previously mentioned that the character codes for the letters A-Z start with 65 and go upwards
...
Lower case letters a-z have the same pattern starting with 97, i
...
32 greater than the upper case
letters
...

We will now create a program that reads a text in lower case and converts it to upper case and prints it:
#include ...
h>
void main()
{

int i;

char cName[30];

cout << "Enter your name in lower case: ";
cin >> cName;

int iLen = strlen(cName);
for (i=0; i
cout << (char)(cName[i] - 32);

}

cout << endl;

As usual in string handling we must include the header file string
...

We declare the variable i to be used as loop counter, and a string array named cName with space for 29 characters
...

We then calculate the length of the input string, which is stored in the variable iLen
...

Inside the for-loop we take the ith character from the string cName (cName[i]) and decrease it by 32
...
This value is
then type cast to char by placing char within parenthesis in front of the subtraction
...

Thus, we have taken character by character from the input string, all in lower case, decreased the character code by 32,
which gives the corresponding upper case character, and printed it
...
11 Initials
In most computer systems the programming work is to a large extent focused on checking and processing texts entered
by users
...

In our next program example we will extract the initials from a name entered by the user
...
Then we search for the blank between the first name and the surname
...

Download free eBooks at bookboon
...
Therefore,
we will study some text processing examples
...
The process is to extract the first letter from the
Structured Programming with C++ 5 Strings
name
...
In the next position the first letter of the surname is found
...
We detail the
‘Search for blank, take time box:
To search for the blank implies taking one character at anext’ from the beginning of the input name and check if it is a
blank
...
i
= blank ?

Take char
no i+1

o

Print

*

---

o

Searching for the blank is made in a loop
...
For each turn of the loop we check if character no
...
If so, we take
check if character no
...
If so, we take character no
...
i+1 as the second initial
...
Here is
#include #include ...
h>
#include ...
h>
void main()
void main()
{
int i;
{
int i; char cName[30], cInit[3];
cout << "Enter your name: ";
char cName[30], cInit[3];
cin
...
getline(cName,29);
for (i=1; iint iLen =if (cName[i] == ' ')
strlen(cName);
cInit[1]
cInit[0] = cName[0]; = cName[i+1];
cInit[2] = '\0';
for (i=1; icout << "Your
if (cName[i] == ' ')
}
cInit[1] = cName[i+1];

We declare the string array cName, which is to contain the input
name, and cInit to contain the initials
...


Download free eBooks at bookboon
...
The reason for
declaring 3 positions for cInit is to make space for the 2 initials plus the null character
...

The first character of cName (cName[0]) is stored in the first position of cInit
...
For each turn of the loop we check if the character is a blank
...

At completion of the loop we put the null character in the third position of cInit and print cInit
...
12

Comparing Two Strings

In the Arrays chapter you learnt that, when comparing two arrays, you must compare each item of the arrays
...
The function
strcmp(str1, str2)
• gives a negative result if str1 < str2, i
...
if str1 comes before str2 in alphabetic order

Download free eBooks at bookboon
...
e
...
h>
#include ...
The user enters two names
...
How would you do to allow blanks?
The if statement checks if cName1 comes before cName2 in alphabetic order
...
Otherwise the names are printed in reversed order
...
13

Copying Strings

In the Arrays chapter we copied an array’s values to another array by copying each item singly
...
If for instance the string array str2 contains the string
‘John Smith’ and we execute the statement:
strcpy(str1, str2);
then str1 will also contain the string ’John Smith’
...
14

Array with String Arrays

Suppose that we want to store a number of names in an array, where each name is itself a string array
...
Below we declare a two-dimensional array with space for 5 names with 30 positions each (29
characters plus the null character):
char cNames[5][30];

Download free eBooks at bookboon
...
g
...
The program
prints the characters from the beginning of the string until the null character is found
...
e
...
In the example above we
used indes=2, which gives the printout ‘Bob’
...
The statement:
cout << cNames[1][4];
prints the character with index 4 from the name with index 1, i
...
‘r’ in ‘Edward’
...
15

Sorting Strings

We want to sort the string matrix above, i
...
the names should be reorganized into alphabetic order
...
There we compared the items in pairs and interchanged
their positions if the right item was less than the left
...

We first prompt the user for five names to be stored in the string matrix
...
h>
#include ...
Press Enter after each" << endl;
for (int i=0; i<5; i++)
cin >> cNames[i];

for (i=0;i<4;i++)

for (int j=i+1; j<5; j++)

Download free eBooks at bookboon
...

The first for-loop reads five names to the string matrix cNames
...
The outer for-loop goes from 0 to 3 (next last name) with the loop counter i
...

The if statement compares the two names indicated by the indeces i and j
...

The interchange is made by means of strcpy() by copying cNames[i] to the temporary string array temp
...
Finally we copy the temp name (the old name in position i) to position j
...


Download free eBooks at bookboon
...


5
...
Then we will get use of the strncpy() function,
which copies a given number of characters from one string to another
...

If you want to copy a number of characters from a given position and not from the beginning of cStr2, use this variant:
strncpy(cStr1, cStr2 + i, iNo);
This statement copies the number of characters given by the variable iNo counted from position i of cStr2 and stores this
substring in cStr1
...
A pointer is a variable that points
to a certain memory address
...
e
...
If we write cStr2+1, it is interpreted as a pointer that points to the character
with index=1 in cStr2
...

Enough with pointers for this time
...


5
...
The statement
strcat(cStr1, cStr2);
concatenates cStr1 and cStr2 and puts the result in cStr1, i
...
cStr2 is added at the end of cStr1
...


5
...
The program
will then interchange them so that the surname is printed first
...
With the strncpy() function we can then separate the
first name and surname, and then with the strcat() function put the substrings together with the surname first
...
com

112

them so that the surname is printed first
...
With
the strncpy() function we can then separate the first name and
surname, and then with the strcat() function put the substrings together
Structured Programming with C++ 5 Strings
with the surname first
...
Then we search for the
First we read the name from the user input
...
any of them is blank
...

if When a blank is found we save its position
...
Finally
substrings consisting of first name and surname
...

together print them
...
h>
Copyright

Page: 108

#include ...
getline(cName,29);

for (int i=0; i<29; i++)
if (cName[i] == ' ')
break;

strncpy(cFirst,cName,i);
cFirst[i] = '\0';

strcpy(cSur, cName + i + 1);
strcat(cSur, " ");

strcat(cSur, cFirst);

cout << cSur << endl;
}

cout << strrev(cSur) << endl; //reversed name

Download free eBooks at bookboon
...

The string array cFirst will be used for the first name and the string array cSur to the surname
...

The user is prompted for his name to be stored in the array cName
...
It goes from 0 to 28, i
...
it takes character by character from the name
...

If the user enters ‘John Smith’, i will have the value 4 when the loop is interrupted, and that is the position of the blank
...
In the case of John Smith the first 4
characters will be copied, i
...
‘John’
...

Then we use the function strcpy() to copy the characters from cName to cSur starting on position i+1
...
In the case of John Smith i is =4
...
e
...
Note that the copy is performed character by character
until the null character is found
...
e
...
Then
we concatenate surname + blank with the first name
...

The last statement has actually nothing to do with our task
...
It prints the entire
name in reversed order
...


Download free eBooks at bookboon
...
We have
only included it for curiosity
...
The function strrev() reverses a string
...
19 Encryption

We will text, i
...
distorts it to that encrypts a text, i
...
doing this is
We will now write a program that encrypts anow write a program unreadability
...
The way of doing this is to take character by character
by character of the text entered by of the text entered by the character increase1
...
This is
the user and increase the user and code by the becomes code by 1
...
This is a very simple encryption when encrypting
algorithm, but gives a hint about how different encryption algorithms
mail and other information
...

We start with a JSP graph:

We start with a JSP graph:
Encrypt

Input

Encrypt text

Print

*
Increase
char no
...
The encryption takes character by
character from the string array and increases the character code by 1
...
The encryptionthe encrypted message
...
Finally we print the encrypted message
...
h>
#include ...
h>
void main()
#include ...
getline(cName,29);
char cName[30], cEncrypt[30];
iLen = strlen(cName);
for (int i=0; icout << "Enter your name: " << endl;
cEncrypt[i] = cName[i] + 1;
cin
...
The
user is prompted for his name, which is stored in the string array cName
...

The for-loop goes from the first to the last character of the entered string and increases the character code for each
character with 1
...

Download free eBooks at bookboon
...


Random Password

Structured Programming with C++

5 Strings

As the last character we insert the null character at the correct position in cEncrypt, which then is printed
...
20 Random Passwordprevent unauthorized access to a computer system
...
We
Passwords should, as you probably will write difficult to guess to prevent unauthorized to create passwords system
...
We will write a program that makes the
good way of creating passwords is to let the computer randomly create (A-Z)
...
You can then
computer able to create passwords only consistinginclude lower case letters and digits
...
This is of We start with a JSP
graph:
the logic to be followed
...
We start with a JSP graph:

Password

Random

Random word

Print

*
Random
character no i
We begin with creating a random length of the password, which we in
this example will limit to between example will limit to between 5-7 characters
...
Then we create as
many characters in the interval A-Z (character codes 65-90)
...
Here is the The password is then printed
...
code:
#include ...
h>
#include ...
h>
void main()
{

int iLen, i;

Copyright cPw[30];
char

Page: 111

srand(time(0));

iLen = rand() % 3 + 5;
for (i=0; i
cPw[i] = rand() % 26 + 65;

cPw[iLen] = '\0';
}

cout << "Password: " << cPw << endl;

We declare the loop variable i, the variable iLen to contain the length of the password, and the string array cPw to contain
the random password
...


Download free eBooks at bookboon
...
Then we create the random length of the password
with the modulus operator %, which gives a length in the interval 5-7
...
By adding 5 we transform the interval to 5-7
...

The for-loop then goes from 0 to iLen-1, i
...
as many turns as the number of letters in the password
...
Each
character code is stored in the string array cPw at position i, i
...
cPw is built up with one more character for each turn of
the loop
...
cPw is then printed
...
21

Translation Table

We will now show another method of encrypting a message, namely by means of a translation table
...
Thus, the characters are not in alphabetic order
...

Suppose we have got the following translation table:
DGZCW…
where D is in position 0, G in position 1 etc
...
each character in the
original message will consequently be translated to another character:

ABCDE…


...
com

117

Click on the ad to read more

ABCDE…
Structured Programming with C++

5 Strings

DGZCW…

DGZCW…

The JSP graph below shows the logic:
The JSP graph below shows the logic:
Key

Define
key

Random order
of key

Replace char
no
...


Random
char no
...
to key

Entry

Char code
for char no i

Triangular
interchange

*

Decr
...

position no

*

*

‘Define key’ means that we define a string containing the characters A-Z
...
the characters of the key, which is done by looping through the characters and
we mix

‘Random order of key
...
In
which is done by looping through the characters and create a random
that way all characters will interchange its position with some other character
...
These two characters will
then interchange their positions
...
with some other character
...
to key’ is made by taking the character prompted for the message in upper case
...
This value gives the index in the for for
the code by 65
...
to key’ is made by taking the character code key one the character to
substitute the original character
...
A will then get the value 0, B the value 1 etc
...

If we use the key:
If we use the key:
DGZCW…
DGZCW…
like index 0 in the key, G index 1 etc
...
If the original message contains a B (character code 66), it is
code 66), it is decreased by 65 to the value 1
...

decreased by 65 to the value 1
...

Here is the code:
#include ...
h>
#include ...
h>
void main()
{

Download free eBooks at bookboon
...
getline(cText,49);
iLen = strlen(cText);

for (i=0; i
cEncrypt[i] = cKey[cText[i] - 65];

cEncrypt[iLen] = '\0';
}

cout << "Encrypted: " << cEncrypt << endl;

First we declare some supporting variables; i, j and iLen, the latter being used for the length of the entered message
...
The string array cKey is initated
with the characters A-Z
...

The first for-loop performs the mixing of the characters of the array cKey
...
A j value is randomly created to be used as index to the character to be interchanged
with the i-character
...
At completion of the loop all
characters in cKey has been interchanged with some other character, which makes cKey now be well-mixed
...
The length of the message is calculated and
stored in the variable iLen
...
The loop counter i goes from 0 to iLen-1, i
...
as
many turns as there are characters in the input string
...
This value is decreased by 65, and since it is a math operation, the result is of
integer type
...
This value is now
used as index in cKey and gives the character from cKey that corresponds to the original position of B, for instance G
...
The array cEncrypt is thus built up by one character at
a time from the array cText, translated via cKey
...

Download free eBooks at bookboon
...
The array cEncrypt containing the encrypted message is
then printed
...
22 Summary
In this chapter we have introduced the char data type
...
We have also learnt
how to use string arrays or string variables to store texts consisting of more than one character
...

Blanks is a problem at entry of texts, which is solved by using the function getline()
...
h contains a number of nice functions for text management, for instance to calculated the length of
a text, copy texts, concatenate texts and extract substrings of texts
...

We have also worked through a number of programming examples to extract initials from a name, sort a list of names,
where we got use of two-dimensional arrays (matrices), interchange first name and surname, encrypt messages and create
random passwords
...
23 Exercises
1
...
Statistics

Complete the switch statement with a suitable text
...
mastersopenday
...
com

120

Click on the ad to read more

Structured Programming with C++

5 Strings

2
...
It should be performed with a loop so that you
repeatedly can select from the menu until you enter X to exit the program
...
Write a program that asks for a character and then prints the character 10 times at the same line
...
Change the previous program so that the program prints the character once at the first line, twice at the
second line etc
...

5
...
The program should then print the
character as many times as given by the entered integer
...
Change the Christmas Tree program in this chapter so that it prints 15 branches instead of 11
...
Write a program that prompts the user for a character and prints the corresponding character code
...
Complete the previous program with entry of a character code and a printout of the corresponding
character
...
Write a program that prints the text ‘Här går vi över ån efter vatten’ with the Swedish characters å, ä and ö in
a correct way
...
Write a program that reads a text from the keyboard and prints the length of the text as well as the entire
declared size of the string variable
...
Start with the Upper/Lower Case program and change it so that it reads a text in upper case and prints it in
lower case
...
Explain why the printout is the way it is
...
Write a program that prompts the user for a word and prints each character doubled (twice)
...
Write a program that prompts the user for a word and prints it reversed, first by using the strrev() function,
and then without strrev()
...
Start from the Initials program in this chapter and complete it so that the user can enter first name, middle
name and surname and get all three initials printed
...
Complete the previous program so that, if you enter the names with leading lower case characters, the
printout will still be with the initials in upper case
...
Write a program that prompts the user for two characters and prints all characters in between
...

17
...

18
...
The program should respond with the
number of vowels in the word, Don’t include å, ä or ö
...
The Robbery language is spoken by doubling each consonant and putting an ‘o’ in between
...
Write a program that reads a word and prints it in the Robbery language
...
Write a program where the user can enter 6 product names
...

21
...
The printout
should contain the correct price for each product, right-aligned with two decimals
...
Write a program where the user can enter his first name and surname
...

23
...
The program should then check whether there
is an @ in the address
...
Complete the previous program so that, if there is no @, the text ’@htu
...

25
...
g
...
smith@htu
...
com

121

Structured Programming with C++

5 Strings

Write a program that reads an e-mail address and prints the name in the correct way, e
...
:
John Smith
with upper case first character in both first and surname and with a blank in between
...
Start with the Encryption program in this chapter
...

27
...

28
...

29
...
e
...

30
...
Complete it with also taking lower case characters
and digits into account
...
Change the previous program so that the password will be 6-10 characters in size
...
Originate from the Translation Table program in this chapter
...

33
...


Download free eBooks at bookboon
...
1 Introduction
When working with bigger programs, or programs performing many different tasks, it is important to divide the code
into small limited pieces, which makes it easier to grasp and maintain
...
A function
is a part of the program well marked off that performs a particular task
...

A function, when completed and tested, is like a black box that always works as expected
...
You give it a number of input values, and it does its job
...
He pushes the accelerator and the car accelerates
...
He knows that the same thing
always happens when pushing the accelerator
...
The programmer initiates the function from
his code and the function always performs the same task without having to bother about the details
...

In this chapterEconomy and Informatics

We will learn how to declare and define functions and we will study how to use header files in connection with functions
...
We

What Is a Function

will also get in touch with recursive functions, i
...
functions calling themselves
...
2

What Is a Function

A function is written to perform Aspecific task
...
returns the result from the task being
a function is It might perform a values and it It might need input
values and it returns the result from the task being performed:
performed:

Input

Function

Output

The programmer to make the function perform its to make the function perform its task must supply
The programmer task must supply required input and receive the supplied output
...


Examples of function tasks are:
• Calculate average the detailed values for supply the detailed
• Calculate average – here you will have to supply – here you will have tothe average calculation, and receive
values for the average calculation, and receive the average value
the average value delivered by the function
...

• Sort an array – here the function must know which array to sort
...

• Sort an array – here the function must know the sorted array
...


Download free eBooks at bookboon
...
It returns the item found
...
The output is the calculated
order price
...
It returns the item
found
...
The output is
the calculated order price
...
3 Average
We will write a function which calculates the average of two numbers
...

The task is to add the two numbers and divide the sum by 2
...
The statement to calculate the average is then:
av = (x1 + x2) / 2;
The variable av now contains the calculated average
...
The required input values are enumerated within parenthesis after the function name
...
Furthermore, you specify the data type in question
...
The data type is given in front of each parameter, and the parameters are separated by comma
...
In our case the result is
of the double type
...
The first line is called function
header
...
This section is called the
function body and consists of three statements
...
At
the second line we perform the average calculation
...
At the third line we return
that value to the caller
...
A return statement also has the effect that the function is
terminated
...


6
...
Furthermore, the parameters x1 and x2 don’t
have any values, so the statement with the average calculation is meaningless so far
...

Download free eBooks at bookboon
...

Calling a function means three things:
• Write the function name
• Supply input to the function
• Receive the return value
The following statement calls the function dAverage:
dAvg = dAverage(dNo1, dNo2);
This statement implies that the function dAverage is initiated and that the values contained by the variables dNo1 and
dNo2 are supplied as input to the function
...
The variables dNo1 and dNo1 are called actual parameters, since they
contain actual values
...
The function header:
double dAverage(double x1, double x2)
tells us that there are two formal parameters x1 and x2
...
x1 will get the value of dNo1 and x2 the value of dNo2
...

In the function body the variable av is declared, the average is calculated and stored in av, which is returned
...


Need help with your
dissertation?
Get in-depth feedback & advice from experts in your
topic area
...
helpmyassignment
...
uk for more info
Download free eBooks at bookboon
...
At completion of the
statement the variable dAvg has got the value returned by the function, namely the average of dNo1 and dNo1
...
h>

double dAverage(double x1, double x2)
{

double av;

av = (x1 + x2)/2;
}

return av;

void main()
{

double dNo1, dNo2, dAvg;

cout << "Enter two numbers: ";
cin >> dNo1 >> dNo2;

dAvg = dAverage(dNo1, dNo2);
}

cout << "The average is " << dAvg;

The execution of a program always starts with the main() function, and here the variables dNo1, dNo2 and dAvg are declared
...
Then comes the statement:
dAvg = dAverage(dNo1, dNo2);
which calls the function dAverage and supplies the two entered values
...
The last statement prints the calculated average
...
The reason is that
the compiler must know about the function dAverage before it is called from the main() function
...
We will discuss this more later in this chapter
...
5

Several return Statements

A function might need to return different values depending on the circumstances
...
However, it is always only one return statement performed by the function at execution
...
Here is an example of a function with two return statements:
int min(int x, int y)
{

Download free eBooks at bookboon
...
By examining the function header (the first line) we figure out that the
function takes two integers stored in the formal parameters x and y and that it returns an integer
...
If so, x is returned, otherwise y is returned
...


6
...

Since the function min() only can compare two numbers, we will have to call it twice
...
That integer is then compared to the third number, which
again gives the least of them
...
Here is the code:
int a, b, c, m;

cout << "Enter three integers: ";
cin >> a >> b >> c;
m = min(a,b);
m = min(m,c);
cout << m;

We declare the three variables a, b and c for storing of the input values, and a variable m used for storing of the value
returned from the function min()
...
The least of these two is returned and stored in the variable
m
...
The least of these two is returned and stored in
the variable m, which now contains the least of the three integers
...

Here is the entire program:
#include ...
com

127

Structured Programming with C++

6 Functions

int a, b, c, m;

cout << "Enter three integers: ";
cin >> a >> b >> c;
m = min(a,b);
m = min(m,c);
}

cout << m;

As mentioned, the execution starts in main()
...

An alternative to calling the function min() in two different statements is given here:
cout << min(min(a,b),c) << " is the least";
This statement replaces the three last statements of the preceding program
...
But since the first actual parameter is not an ordinary variable value, the program must calculate it, and is then
forced to execute the inner min() call
...
The second actual parameter to the outer min() call is the variable c
...


Brain power

By 2020, wind could provide one-tenth of our planet’s
electricity needs
...

Up to 25 % of the generating costs relate to maintenance
...
We help make it more economical to create
cleaner, cheaper energy out of thin air
...

Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering
...
skf
...
com

128

Click on the ad to read more

returns the least of the three integers, which is printed by the cout
statement
...
7

6 Functions

Least Item of an Array

We will now use the min() function in a program that finds the least of
the items of an integer array
...
The logic is similar
We will now use the min() function in a program that finds theThe logic is items ofto that of the
previous program
...
The first two items of the array are sent to min(), which returns the least of these two
which returns the least of these two integers
...
This integer and the next itemof the array is again sent to min() which returns the least of them
...
As a result we willthe array have been array items
...
As a result we will get the least of the array items
...
i

Print m

Send m and
next item to
min()

*

Entry of values is made in a loop
...
In the loop ‘Find least’
we send m and the next item to the function min()
...
Since we use m to store
Entry of values is made in a loop
...
Programming withthe loop we print
University West, Trollhättan
Structured At completion of
the first item of the array
...
The return value is stored in the
next all array items
...
Since we use m to store the returned value, m will all the
time contain the the of the items compared that it is function
...
Atacompletion of create a separate
the loop we print the m value, which now is the least of all array
JSP graph for the function:
items
...
We create a separate JSP graph for the
min(x,y)
function:

x
Return x

o

Return y

o

As shown by the JSP the function As shownparameters, the function checks whether x is less than y, If so, x is returned,
takes two by the JSP x and y, and takes two parameters, x and y
...


Here is the program code:

Page: 125

checks whether x is less than y
...

Here is the program code:

#include ...
h> x, int y)
int min(int
{
int min(int x, int y)
if (x{
return x;
else
Download free eBooks at bookboon
...
" << i+1 << ": ";
cin >> iNos[i];

m=iNos[0];

for (i=1; i<=4; i++)
{
}
}

m=min(iNos[i],m);

cout << m << " is the least integer" << endl;

In main() we declare the array iNos with 5 items
...
Then we
assign the first array item to the variable m
...
The returned
value is stored in m
...


6
...
The function
header for such a function could look like this:
int iLgth(char s[])
The function iLgth takes a parameter of char type
...
The empty square bracket indicates
that it is an array
...

The reason is that the function should be able to manage arrays of any size, so we don’t want to lock the function to any
fixed array size
...

The calculation of the length is made by the function body:
int iLgth(char s[])
{

int n=0;

Download free eBooks at bookboon
...
The while loop
has the condition that the nth character must not be the null character, i
...
it proceeds until the end of the string
...

When the function iLgth is called with an array as actual parameter, you don’t specify any square brackets:
iLen = iLgth(cWord);
Here, cWord is a string array that contains a number of characters
...

Below is a program that tests the function iLgth:
#include ...
com

131

University West, Trollhättan
Department of Economy and Informatics

Structured Programming with C++

Structured Programming with C++

6 Functions

return n; void main()
{
}
char cWord[30];
void main()
int iLen;
cout << "Enter a word: ";
{
cin
...
getline(cWord,29);
iLen = iLgth(cWord);

In main() we declare the string array cWord with max 30 characters,
cout << "The length ofand the word is " << iLen << endl;
the integer variable iLen, which later will contain the string
length
...
Then the function iLgth() is
}
called with the entered string as actual parameter
...

In main() we declare the string array cWord with max 30 characters, and the integer variable iLen, which later will contain
the string length
...
Then the function iLgth() is called with the entered string as actual

Function and Subfunction

parameter
...


6
...
This is rather
It is possible to write functions to be called by other functions providing a hierarchy of functions and subfunctions
...

and well defined task
...
The percent is then used by dPrice() to
which calculates and returns a discount percent
...
used by dPrice() to calculate the discounted price
...
number of units and the unit price
...
The discount
0
...
The line price is calculated as to 0
...
The line price is calculated
as number of units times unit price
...
Later, the price
...
The function dDiscount returns a discount percentquantity and line price
...

net price, which is returned by dPrice()
...

There are some thicker side lines indicating are some thicker side lines indicating functions
...
com

132

University West, Trollhättan
Department of Economy and Informatics

Structured Programming with C++

Structured Programming with C++

6 Functions

The JSP graph for the dDiscount() function looks like this:
dDiscount(iQty, dLinePrice)

dLinePrice > 1000

Return 15%

o

Line price > 500
or iQty > 10

Return 10%

o

o

Return 0%

o

The function dDiscount()The function dDiscount() takes price as parameters
...
(i
...
line price exceeds 1000, the equal to 1000),
discount 15 % is returned
...
Otherwise (i
...
the line price is less than or equal to 1000),
exceeds 500 or the quantity exceeds 10
...
In other cases there will be no discount and
we check if the line price exceeds 500 or the quantity exceeds 10
...

Then 10 % is returned
...

We begin the coding with the dDiscount() function
...
When writing
the functions at the bottomprograms with functions it is convenient to start with the functions at
of the hierarchy
...

double dDiscount(int iQty, double dLinePrice)
{

}

double dDiscount(int iQty, double dLinePrice)
if (dLinePrice>1000)
{
return 0
...
15;
else if (dLinePrice>500 || iQty>10)
return 0
...
10;
else
else
return 0;
return 0;
}

The function dDiscount() takesfunction dDiscount() takes the quantity as parameter, which is
The the quantity as parameter, which is stored in the formal parameter iQty, and the line
stored in the formal parameter iQty, the values and returns a in the
price stored in the parameter dLinePrice
...

parameter dLinePrice
...


double dPrice(int iNo, double dUnitPrice)
{

const double dTax = 0
...
com

133

Page: 129

Structured Programming with C++

6 Functions

The function dPrice() takes the quantity and unit price as parameters
...
Then
variables for the line price and discount percent are declared
...

Then the function dDiscount() is called with quantity and line price as actual parameters
...
Finally, the discounted net price of double type is returned, where we deduct the
discount percentage and add the tax percentage
...
h>

double dDiscount(int iQty, double dLinePrice)
{

if (dLinePrice>1000)
return 0
...
10;

else
}

return 0;

double dPrice(int iNo, double dUnitPrice)
{

const double dTax = 0
...
com

134

Click on the ad to read more

Structured Programming with C++

6 Functions

dLinePr = iNo * dUnitPrice;

dDiscPerc = dDiscount(iNo, dLinePr);
}

return dLinePr * (1-dDiscPerc)*(1+dTax);

void main()
{



int iQuantity;



cout << "Enter quantity and unit price: ";



double dUnitPrice;

cin >> iQuantity >> dUnitPrice;
cout << "To be paid: "

<< dPrice(iQuantity, dUnitPrice)<
}

In main() we declare the variables iQuantity and dUnitPrice, which store the entered values
...
As return value we get the discounted net price, which is
printed by the cout statement
...
10

Function without Return Value

Some functions are supposed to perform a task but don’t need to return any value
...

We will create a function that prints the character ‘=’ a specific number of times
...
We use the name underline for the function:
void underline(int n)
{

}

for (int i=1; i<=n; i++)
cout << "=";

A function that does not return any value has ’void’ in front of the function name
...

The function underline() takes an integer as parameter
...

We can now use this function in a program to underline a text:
char s[7] = "Prices";
cout << s << endl;

underline(strlen(s));
This code section defines a string array s with the string ‘Prices’
...
This gives the output:
Download free eBooks at bookboon
...
The for-loop goes from 1 to the number of characters in
the string and prints as many equality signs
...


6
...

We call it replace:
void replace(char s[], char c, char cnew)
{

int n = 0;

while (s[n] != '\0')
{

if (s[n] == c)

s[n] = cnew;

}
}

n++;

cout << s << endl;

The function takes three parameters, a string array - s, the character to be replaced – c, and the replacing character – cnew
...
The while loop
has the condition that the character must not be the null character, i
...
we proceed from the first to the last character of
the string
...
If so, that character iw
replaced by cny
...

Finally the modified string is printed by the cout statement
...
com

136

Structured Programming with C++

6 Functions

Here is an entire program that tests the replace() function:
#include ...
com

137

Click on the ad to read more

Structured Programming with C++

6 Functions

In main() we define a string array a which is printed
...
The printout will be:
C:/Mydocuments/Sheets
C:-Mydocuments-Sheets

6
...
The same applies to the formal parameters
...

You can neither use a variable in replace() that is declared in main()
...


Structured Programming with C++

A variable is valid only in the function where it is declared
...


6
...
e
...
e
...
The function
only contains the characters a-z or A-Z
...
We start
checked
...
i
letter ?

Increase i

o

Return 1

*

Return 0

o

The function begins by calculating character’ goes through character by
The function begins by calculating the string length
...
The loop ‘Check character and
character’ goes through character by character and checks if it is in the
checks if it is in the interval a-z or A-Z
...
Otherwise we return the value 0 and
interval a-z or A-Z
...

the function is terminated
...

characters we return
loop 0 and the function is terminated
...

We now give a JSP graph for the program calling the word() function:
We now give a JSP graph for the program calling the word() function:

Download free eBooks at bookboon
...
For each turn of the loop we read a string from the keyboard
...
If 1 is returned by the function, we print ‘A word’
...

Here is the code:
#include ...
h>

The program has a loop ’Check string’
...
The string is sent to the function
word()
...
If 0 is
returned, we print ‘No word’
...
h>
{
#include ...
com

139

Structured Programming with C++

6 Functions

The function word() begins by calculating the length of the string s and storing it in the variable j
...
Character number i is
copied to the char variable c
...
If this condition is satisfied,
the character is a letter and i is increased by 1
...

If the while loop is allowed to complete, all characters are letters and the value 1 is returned
...
The while loop has the condition of a successful string entry, i
...
the user has
not pressed Ctrl-Z
...
If the function returns
1 (it is a word), the condition is true and the text ‘A word’ is printed
...


6
...
For instance, it can perform a task with different data sets
...
If the number of parameters or the data types of the parameters are different, it
is considered different function shapes, or override functions
...
Here are two
examples of override functions:
void prt(int i, int width)
void prt(char s[])

Download free eBooks at bookboon
...
The purpose of the functions is to print something
on the screen
...
The second function should print the string s
...

The second function prints the string sent to the function
...
Depending on the actual parameters sent
to the function, the program will select the appropriate function variant
...
If we combine these statements:
prt("The number:");
int k = 8;
prt(k, 3);

we will get the printout:
The number:

8

with two blanks in front of the 8, since we set width to 3, totally three positions
...


6
...
com
be able to recognize it when called from main()
...
In main() we call dAvg() with
the actual parameters no1 and no2, which we assume to have been assigned values previously in the program
...
It is exactly identical to the function header, followed by a semicolon
...

The definition of the function, i
...
the function header plus the function body, can then be positioned anywhere in the
program
...

This way of first declaring functions and placing the definitions afterwards is common by programmers and provides the
advantage of having main() first, which is logical since the execution starts there
...
However, the function header of the
function definition must be complete with formal parameter names
...
com

142

Structured Programming with C++

6
...

The header file must then be included in the program using the functions
...
Suppose we name it myfunc
...
The function
declarations are stored in the header file myfunc
...

When writing the program in still another cpp file, which will call the functions, myfunc
...

Here is a set of functions that we have used previously in this chapter:
// myfunc
...
h> // Necessary for cout
void underline(int n)
{

}

for (int i=1; i<=n; i++)
cout << "=";

double dDiscount(int iQty, double dLinePrice)
{

if (dLinePrice>1000)
return 0
...

RUN LONGER
...
GAITEYE
...
com
1349906_A6_4+0
...
10;

else
}

return 0;

double dPrice(int iNo, double dUnitPrice)
{

const double dTax = 0
...
h

void underline(int n);

double dDiscount(int iQty, double dLinePrice);
double dPrice(int iNo, double dUnitPrice);

// price
...
h>
#include "myfunc
...
cpp program we have included the file myfunc
...
The compiler will look in myfunc
...
h
...
That implies that the compiler
looks in different folders to find the header files
...
h and myfunc
...
cpp, while iostream
...


Download free eBooks at bookboon
...
16
...
Do
as follows:
• Select File - New and indicate the Projects tab
...
Click
OK
...
Click Finish
...
Click OK
...

• Mark the option C++ Source File and enter a name of the cpp file
...

• The code window is displayed
...

• Add the file to the project by selecting Project - Add To Project - Files
...

When creating a new header file, do as follows:
• Select File - New and indicate the Files folder
...
Click OK
...

University West,code window is displayed
...
Mark the file and click OK
...

Run the program by clicking the Execute Program
Reference Parameters button (the same button as used for running a program so far)
...
17

Reference Parameters

When calling a function with actual parameters, the value for the
When calling a function with actual parameters, the value for the acutal parameter is copied from its memory area to
acutal parameter is copied from its memory area to another memory
another memory area used by the function’s formal parameter:
area used by the function’s formal parameter:

x=5;
func1(x);

5

5

The variable x has the value 5 stored in a memory location
...
com
by the function
...
When
func1() is called, that value is copied to another memory location used
The variable x has the value 5 stored in by the function
...
When func1() is called, that value change to value
location used by the function
...

Sometimes this is good, but sometimes you also want the original
Another disadvantage is when a lot of value to be changed
...
g
...
A lot of memory is then consumed and it

function, e
...
at object oriented programming when an object
takes time to copy huge amounts of data
...
A
The solution is to use a reference parameter
...
com

146

Click on the ad to read more

amounts of data
...
No copying of data is
amounts of data
...
No copying of data is
parameter
to
memory location:
Structured Programming with C++ made,pointthe the sameactual parameter and the function’s formal
then 6 Functions
but
original
parameter point to the same memory location:
5

x=5;
func1(x);
x=5;
func1(x);

5

If the function func1() changes the value, it also affects the value of
the original variable the
If the function func1() changes the value, it also affectsx: value of the original variable x:
If the function func1() changes the value, it also affects the value of
the original variable x:
6

x=5;
func1(x);
x=5;
func1(x);

6

Defining a function parameter asDefining aparameter parameter as reference& character is made by type:
reference function is made by placing an parameter after the data

placing an & character after the data type:
void underline(int& n)Defining a function parameter as reference parameter is made by
void underline(int&the data type:
placing an & character after n)
{
{
void underline(int& n)
//…
//…
{
}
}
//…
The
} parameter n is here a reference parameter
...

You call the function in the usual way:
The parameter n is here a reference parameter
...
18

Sometimes an actual parameter when calling a function
...
This function must by itself bethe formal
capable
be capable of assigning a value to the formalit a function
...
This is accomplished by
when calling a function
...
e
...
of is an example:
defining the formal call,
a default gets a i
...
if no value is
assigning a value to the formal parameter
...
e
...
HereiNo=1)
supplied by the function call, the formal parameter gets a standard
{
value
...
It takes a character c and an integer iNo as
parameters
...

The for-loop goes from 1 to iNo and prints c for each turn of the loop
...
com

147

Structured Programming with C++

6 Functions

The parameter iNo has the default value 1, which means that if no integer value is sent to the function, iNo will get the
value 1
...
Here is one:
print_many ('x', 4);
This call sends the character ‘x’ and the number 4 to the function
...
The output will be:
xxxx
Here is the other way of calling the function:
print_many ('y');
Here, we don’t send any integer value, so the default value 1 will be used
...
This is the way it should be written:
void print_many (char c, int iNo=1);
void main()
{
}

//…

void print_many (char c, int iNo)
{
}

//…

Furthermore, the parameter with the default value must be the last one in the parameter list
...


6
...
e
...
This may sound as an infinite loop
...

Here is the basic logic for a recursive function:
func()
{

//misc code

Download free eBooks at bookboon
...
This call will be performed as long the if condition is
true, repeatedly
...
Then the
value 1 is returned and the recursive function calls are interrupted
...
We will create a recursive function which calculates
the faculty of the number sent to the function
...
Faculty is identified by !
...
You
start with the number and repeatedly multiply by the number that is 1 less until you arrive at 1
...
We will consequently multiply n by n-1, n-2, n-3 etc
...
We will call nfac() with the number that is 1 less than the number used in the previous call
...
If so, the number 1 should be returned, otherwise the
function should be called again, this time with n-1 as actual parameter
...
sylvania
...

Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges
...
Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths
...
Come and join us in reinventing
light every day
...
com

149

Click on the ad to read more

Structured Programming with C++

6 Functions

Here is the code:
int nfac(int n)
{

if (n<=1)

return 1;

else
}

return n * nfac(n-1);

The function has an if statement which checks if the supplied parameter is 1 or less
...
Otherwise the
product of n and the result of the call to the same function with parameter n-1 is returned
...

Since 4 is greater than 1, this multiplication is performed: 4 * nfac(3)
...

The call nfac(2) gives the multiplication 2 * nfac(1)
...

Thus, the resulting multiplication is 4 * 3 * 2 * 1, which is stored in the receiving variable iFaculty
...
20 Summary
In this chapter we have learnt to write functions
...

We have learnt how to send values to, and receive the result from a function
...

We have made a brief introduction to reference parameters – an efficient tool to save memory and improve program
performance
...


6
...
Write a function which calculates and returns the average of three numbers
...

2
...
Test the function with a call from main()
and complete with suitable printouts
...
Complete the previous program so that it can calculate the greatest of three numbers by means of the
function max()
...
Start from the program ’Least Item of an Array’ and complete it with printing of the greatest item of the
array by means of the function max()
...
com

150

Structured Programming with C++

6 Functions

5
...

6
...
From
main(), read the number n from the user
...
Write a function printLine(int n, char c) which prints the character c at a line as many times as specified by
the integer n
...

8
...
E
...
the word Data is printed as D a t a
...

9
...


-

void revers(char str[]) which interchanges the first and surname of str and prints it
...


-

void back(char str[]) which prints the name backwards
...


Use the functions in a main() program
...
Start from the program with the price calculation in the section ’Function and Subfunction’
...
Ensure that the function takes erroneous entry
into account
...
Save this program, we will
use it in later exercises
...
Write a program for calculation of car rent
...
The calculation of the kilometerage is
made by a subfunction which prompts the user for start and end odometer value and returns the number of
kilometers driven
...
27 per litre)
...

12
...
The function takes a string
as parameter, searches for the letter combinations aa, ae and oe, end replaces them by å, ä and ö respectively
...
To make it work, the user must enter the
word ‘båda’ as ‘baada’
...
Start from the ‘Word program’ earlier in this chapter
...
e
...

14
...
Use the function in a main() program
...
Improve the previous function to also take a colour parameter (1-4) and prints ’hearts’, ’clubs’, ’diamonds’ or
’spades’
...
com

151

Structured Programming with C++

6 Functions

16
...


-

bool divable(int a, int b) which returns true if a is evenly dividable by b
...


-

bool letter(char c[]) which returns true if the first character of c is a letter
...

17
...
There should be one main() function which reads the
calculation, for instance 5 * 3, and four functions, one for each type of calculation + - * /
...
Write a program that calculates the average score for a student
...
These two
values are multiplied
...
The course scores of all courses are
added
...
The
transfer between score (for instance VG) to value (15) is made by a function
...
Change the price calculation program in exercise 10 above, so that you get two override functions for
discount calculation with the same function names
...
The entry of customer group from the user
must then be made in the dPrice() function
...
Modify the previous program so that you place the function declarations first and the function definitions
after main()
...
Start from exercise 11 and put all code in a project with the function definitions in a separate cpp file, the
function declarations in corresponding header file and main() in a separate cpp file
...
Modify the previous exercise so that the parameters of the functions are used as reference parameters
...
Change the function for calculation of the fuel price in the previous exercise so that it takes the litre price as
parameter
...
32
...
Write a function which creates a number of random rolls of a dice
...
The function should return the average of the rolls
...
Store the program in a
project with separate cpp files for the function and main() and a header file with the function declaration
...
Expand the previous exercise so that the program runs the function using the default value, i
...
without
sending the number of rolls to the function
...
Improve the previous exercise so that you play against the computer and the program informs you about
who won
...

27
...

28
...

29
...
Use it in a main() program
...
Change the previous function so that it every other time adds and subtracts, for instance 6-5+4-3+2-1
...
com

152

Structured Programming with C++

7 Files

7 Files
7
...
The data entered to the program is gone when running the program the next time
...
We must have the possibility to save data entered or calculated during one run, so we can continue where
we stopped last time
...

In this chapter we will go through the basic concepts about file management and how to read from and write to files in C++
...
A lot of special code is
however required in C++ to do that, which is outside the scope of this course
...


360°
thinking

To be able to handle files in C++ we need some knowledge about streams, which we will first go through in this chapter
...


We will then show how to declare a file, open it, save data in it, read from it and close it
...
If the system would break down
while a file is open, the result might be a corrupt file not possible to read from
...


360°
thinking


...


Discover the truth at www
...
ca/careers

© Deloitte & Touche LLP and affiliated entities
...
deloitte
...


Download free eBooks at bookboon
...


153
Discover the truth at www
...
ca/careers the ad to read more
Click on

© Deloitte & Touche LLP and affiliated entities
...
2 Streams
When files are processed in C++ the communication goes between hard disk file and program via a stream:

Program
Infile
Outstream
Instream

Outfile

When data is to be read from a disk file (infile) to a program, it goes via an intermediary store (instream) which works
as a buffer between the hard disk and the program, where data is queued to be read to the program
...

program
...
The operating
Similarly, when data is to be written from the program to a disk file
system takes care of the physical reading(outfile), it ison the disk file
...


7
...
The operating system takes care
of the physical reading and writing on the disk file
...
e
...
But actually, the data has been transferred
via an instream called cin
...
Suppose that we have an instream called is and that it islike:
cin >> cName;
particular disk file
...
e
...
But actually, the data has been transferred via an instream
called cin
...
Suppose that we have
Reading data from an instream with the >> operator is called ‘formatted input’, because the data from the instream is
an instream called is and that it is connected to a particular disk file
...

type of read data from the instream with statements like:
is >> cName;
In some situations it is not possible to accommodate the data to a specific data type, for instance if you try to read letters
is >> dAmount;
to an integer variable
...

Reading data from an instream with the >> operator is called
'formatted input', because the data from the instream is
You can also use ‘unformatted input’, which means that characters are read from the file exactly as they are stored,
without any accommodation
...
com

154

Structured Programming with C++

7 Files

char cName[30];

is
...

The read operation continues until the end line character is reached
...
Then one line at a time is read
...

If there are more than 29 characters at the line in question in the file, the input is interrupted after 29 characters
...


7
...
The statement
implies that the characters in the variable cName are written to the outstream
...
Compare the ‘Variables’ chapter, where we discussed formatted output
...
put(c);

os
...
The write()
function writes 30 characters from the variable cName to the outstream os
...
5

Attaching a File to a Stream

Before being able to use an instream or outstream, it must be declared and attached to a disk file
...
txt");
declares the instream infile and attaches it to the disk file named address
...

ifstream is the short for ‘input file stream’
...
But actually,
ifstream is a class from which we derive an object of the ifstream type with the object name infile
...


Download free eBooks at bookboon
...
txt");
The stream is called outfile and is connected to a disk file named newadr
...
ofstream is short for ‘output file stream’
...

At completion of this statement the outstream is ready for write operations
...
txt exists, it will be deleted and a new file with the same name is created
...
The outstream is then declared as follows:
ofstream outfile("newadr
...

To make the stream declarations above work you must include the file fstream
...
h>
To allow for reading from and writing to streams, you must as usual include the file iostream
...
h>
At completion of reading from or writing to the streams, you close the streams::
infile
...
close();

We will turn your CV into
an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand?
We will appreciate and reward both your enthusiasm and talent
...
You will be surprised where it can take you
...
employerforlife
...
com

156

Click on the ad to read more

University West, Trollhättan
Department of Economy and Informatics

Structured Programming with C++

Structured Programming with C++

7 Files

A Complete Write Program
7
...
The program will read
for writing of data them in a file named prodfile
...
The program will read product names from
the user (keyboard) and store them in a file named prodfile
...
txt
...
txt
...
As soon as a product Entry of product namesby the the keyboard is made in outstream
...
As soon
as a product name has been entered by the user, it is written to the
we close the outstream
...
At entry completion, we close the outstream
...
h>
#include ...
h>
#include ...
txt");
char cProd[30] =endl << ”Enter product, (only Enter to exit): ";
cout << "";
ofstreamcin
...
txt");
while(cProd[0]!='\0')
cout << endl << "Enter product, (only Enter to exit): ";
{
cin
...
getline(cProd,29);
{
}
outfile << cProd << endl;
outfile
...
getline(cProd,29);

outfile
...
h (to allow for input and
output) and fstream
...


First we include the two header files iostream
...
h (to allow for stream

Copyright

Page: 154

management)
...
com

157

Structured Programming with C++

7 Files

In main() we declare the string variable cProd used for storage of product names in the program
...
txt
...
getline() function before the
while loop starts
...

The while condition checks that the first character of the string variable cProd (cProd[0]) is not the null character
...

The first statement in the loop prints the product name to the outstream outfile
...

The loop is terminated when the user presses Enter without entering any product name
...
The file prodfile
...

When having run the program you would probably like to examine the result
...
txt,
which is in the project folder where the cpp file is saved, or maybe in the ‘Debug’ subfolder, depending on your Visual
Studio settings
...
7

A Complete Reading Program

We will now create a new program that reads data from prodfile
...
txt and prints the with a JSP graph: screen
...
We start information on the
with a JSP graph:

Reading

Create instream

Print products

Read product

Download free eBooks at bookboon
...
txt file
...
At
completion, we close the instream
...
txt file
...
At completion, we close the instream
...
h>
#include ...
txt");
while(infile
...
close();

We include the same header files as in the previous progarm
...
Then we declare the
instream infile and attach it to the disk file prodfile
...

The while loop has the condition of a successful reading from the instream
...

When there is no more data in the file, the read operation is unsuccessful and the loop is terminated
...


AXA Global
Graduate Program
Find out more and apply

Download free eBooks at bookboon
...
8

Structured Programming with C++

7 Files

New Item at the End of the File
New Item at the End of the File

We will now show how to add one more product at the end of the file
We will now show how to add one more product at the end of the file prodfile
...
The solution is given by the following
prodfile
...
The solution is given by the following JSP graph:
JSP graph:

New item

Read product

Create outstream

Print product

Close outstream

This program reads only one more product
...
But, products
...
txt,
First we read the product name from the user, then we create the outstreamallowattach it toof any number of print the
products
...

First we read the product name from the user, then we create the
outstream and attach it to the file prodfile
...

#include ...
h>

void main() #include ...
h>
{
void main()
char cProd[30] = "";
{
cout << "Enter new product:= ";
char cProd[30]
"";
cout << "Enter new product: ";
cin
...
getline(cProd,29);
ofstream outfile("prodfile
...
txt",ios::app);
outfile endl;
outfile << cProd << << cProd << endl;
outfile
...
close();
}
}

We use the same include files as previously
...
In main() we prompt the user for a new product
...
Then we to make existing data be kept and
outfile and attach it to the disk file prodfile
...
a newthat we use ios::appdeclare the outstream outfile and new data be
attach it to the disk file prodfile
...
Note that we use ios::app to make
added at the end of the file
...

existing data be kept and new outstream and close end of the file
...
txt in Notepad, you will see one more product having been added at the end:
outstream
...
txt in Notepad, you will see one more
product having been added at the end:

Copyright

Page: 157

Download free eBooks at bookboon
...
9

7 Files

Products and Prices

We will now recreate the prodfile
...
The structure of the
file will be:
Product id
Price
Product id
Price
etc
...

The program will be similar to the one used for writing to file:
#include ...
h>
void main()
{

int iProdId = 1;
double dPrice;

ofstream outfile("prodfile
...
and price: ";
cin >> dPrice;

if(iProdId > 0)
}
}

outfile << iProdId << endl << dPrice << endl;

outfile
...

In main() we declare the variable iProdId used for storage of the product id:s in the program
...
The variable dPrice will hold the product prices
...
txt
...
The while condition checks
that there is a valid product id different from zero
...
If the product
id is greater than zero, the information is written to the outstream outfile
...
This way of storing data in a file facilitates printing and
reading from a eBooks at bookboon
...
Avoid several values per line!
Download free
161

Structured Programming with C++

7 Files

At completion of the loop the outstream is closed
...
5
...


I joined MITAS because
I wanted real responsibili�
I joined MITAS because
I wanted real responsibili�

Real work
International
Internationa opportunities
al
�ree wo placements
work
or

�e Graduate Programme
for Engineers and Geoscientists

Maersk
...
discovermitas
...
com

162


for Engin

Click on the ad to read more

7 Files
Search for a Product Price

Structured Programming with C++

7
...
txt to find the price of a product
We

specified by the user
...
txt to find thewe alwaysproduct specified byfromuser
...
Thenfile until we find the correct product
...

we also easily can find the corresponding price
...
is prompted for the
First prompted for the searched product user

searched product id
...
If it is the searched product id, the
The loop ’Search prod’ reads one product id and price at a time from
price is printed
...
If it is the searched product id, the price is printed
...
If not, an the correct printed
...
If not,instream
...
Finally we close the instream
...
h>
#include ...
h>
#include ...
txt");
double dPrice; cout << "Enter product id: ";
ifstream infile("prodfile
...
com

163

Structured Programming with C++

7 Files

iFound=1;

}

}

break;

if (!iFound)

cout << "Product missing";

}

infile
...
The
value 0 means that we have not found the correct product, and 1 means that we have found it
...

Then the instream is created and attached to the disk file prodfile
...

The searched product id is read from the user and stored in the variable iSrch
...
The while condition reads one product id and the corresponding
price from the instream
...

When a product and a price has been read, the if statement checks if it equals the searched product id
...


93%

OF MIM STUDENTS ARE
WORKING IN THEIR SECTOR 3 MONTHS
FOLLOWING GRADUATION

MASTER IN MANAGEMENT
• STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES
THAT THE CAPITAL OF SPAIN OFFERS
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
PROFESSIONAL GOALS
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
EXPERIENCE

5 Specializations

Personalize your program

www
...
edu/master-management

#10 WORLDWIDE
MASTER IN MANAGEMENT
FINANCIAL TIMES

mim
...
edu

Length: 1O MONTHS
Av
...
com

164

Click on the ad to read more

Structured Programming with C++

7 Files

University West, Trollhättan
Department of Economy and Informatics

Structured Programming with C++

If the loop is allowed to complete, i
...
if all products have been read without finding the correct id, the variable iFound
will still have the value 0
...
iFound=1 means ‘true’, iFound=0 means ‘false’, !iFound=1 (not

Sorting a File in Memory

found) means ‘true’
...

Finally the instream is closed
...
11

We can’t
Sorting a File in Memory presume the products to be sorted in the file
...
We will create
We can’t presume the products to be a program which But inallprintout on the screen we want a sorts the of products
...
reads a products in the file to an array, sorted list
array, and then prints the sorted array
...

We now return to the first product file, namely the one only
containing product names
...
You will probably with smaller
amendments achieve the same result with the later file version
...

The program will read all product names to an array (two-dimensional
char an array (two-dimensional char array)
...
The sorting is performed by a function
...

by the function, the main() function will print the sorted list
...

Here is first a JSP graph for the main() function:
Here is first a JSP graph for the main() function:

Sorting

Create instream

Read to array

Read product
First we create the instream
...


*

Print array

*
Print prod no
...


Reading of products to the array is number a items for each single read
...
By doing so we keep track
so we keep track of the number of products read
...

of the number of products read
...

The printing of the sorted array is also made in a loop
...


Download free eBooks at bookboon
...
-1

h = v+1 to no
...

You probably recognize the sort algorithm from the Arrays chapter
...


You probably recognize the sort algorithm from the Arrays chapter
...


#include ...
h>
...
h>
#include ...
h>
void sort(char cList[][30], int n); int n);
void sort(char cList[][30],
void main()
void main()
{
{
int i=0, j, iNo;
int i=0, char iNo;
j, cProd[50][30];
ifstream infile("prodfile
...
getline(cProd[i],29))
ifstream infile("prodfile
...
getline(cProd[i],29))
infile
...
close(); << cProd[j] << endl;
}
sort(cProd,iNo);
void sort(char cList[][30], int n)
for(j=0; j{
int v,h;
cout << cProd[j] << endl;
char temp[30];
}
for(v=0; vvoid sort(char cList[][30], int n)
{

Copyright v,h;
int

Page: 163

Download free eBooks at bookboon
...
h for input and output, fstream
...
h for the string functions
...

In main() we declare the variable i, which is initialized to 0 and which will accumulate the number of products read, the
variable j used as loop counter, and the variable iNo which finally stores the number of products
...
We also create the instream infile,
which is attached to the disk file prodfile
...


Download free eBooks at bookboon
...
The while condition is true as long as there is data to
read from the instream
...

Therefore, the first product is stored in the item cProd[0]
...

After the loop we save the value of i, i
...
the number of products read, in the variable iNo, and then we close the instream
...
After the sort operation we print the array in the last for-loop
...
Note that n is the index of the last item of
the array
...
We also declare the
string array temp, which is used in the triangular exchange of array items
...
e
...
The
inner for-loop goes from the position after v to the last position of the array
...
In that case the items will exchange positions, which is made in the triangular exchange by
means of the string array temp
...

Remember that, when an array is sent as parameter to a function, it is always done as reference parameter, so the function
operates on the same memory area as used by the array in main()
...


7
...
The reason is that you can only
read a file from start to end
...

As a consequence you will have the original file as input file and a new file as output file
...
When arriving at the position in the file to be changed, after having read the input information,
you change the value and print to the outfile
...
Finally you delete the original file and change the name of the new file
to equal the name of the original file
...

We now presume that our product file contains product id:s and prices for each product
...


Download free eBooks at bookboon
...
The information has then
been updated
...
The user is prompted for a product id and a new
Structured Programming with C++ 7 Files
price for that product
...


Read id
and price

*

Read,
update, print

Prod id=
searched?

Enter new price

*

Close
streams

Print prod
...
The user

the new, which by now is empty
...

product id to be updated
...
The product id is comparedoriginal
Then we use a loop to read product id:s and prices from the to the one entered
file
...
If equal, the user is prompted for a new price, otherwise the old price will be used
...
If id and price
are then printed to the outstream
...


Here is the program code:
#include ...
h>
#include ...
txt");
ofstream outfile("temp
...
com

169

Structured Programming with C++

7 Files

}
}

outfile << iProdId << endl << dPrice << endl;

infile
...
close();

remove("prodfile
...
txt", "prodfile
...
h to be able to delete and rename files
...

Then we create the instream, which is attached to the original file prodfile
...
txt
...

The while loop reads product id and price from the instream as long as there is data
...
If equal, the user is prompted for a new price, which is stored in the
variable dPrice, i
...
the old price is replaced by the new one
...
At
completion of the while loop all products have been transferred to the new file and the requested price has been updated
...
txt is
renamed to prodfile
...

Excellent Economics and Business programmes at:

“The perfect start
of a successful,
international career
...
rug
...
com

170

Click on the ad to read more

the remove() function and the new file temp
...
txt by the rename() function
...
13

7 Files

Copying Files

Copying a file could be done according to the same method as used by
Copying a file could be done according to the same method as used by the previousprice is updated and
the previous program with the exception that no program with the exception that no
that file is not deleted
...
We will however show copying a file with the file
of copying a file with the file name specified by the user
...

The copy of data is made by the function rdbuf(), which in one single
operation reads all data from the operation reads all data need of
The copy of data is made by the function rdbuf(), which in one singleoriginal file without thefrom the original file without
the need of picking item by item picking item by item in a loop
...

First we give a JSP graph:

First we give a JSP graph:

Copy file

Enter new
file name

Create instream
and outstream

Error msg

Is the file name
incorrect?
o

Copy data

Close
stream
o

First the user is prompted for theFirst the user is Then we create the instream for the original file and the outstream for
new file name
...
Then we create the
instream for the original file and the outstream for the new file
...


We then check if the outstream creation was successful
...
It might happen that the user file names
...
In case of an error message
...
If so, we would get a run time error
...
If, however, everything is OK, we copy all data
...
Finally we close the streams
...

Here is the program code:

Here is the program code:

#include #include ...
h>
#include ...
h>
#include ...
h>
{
void main()
char cNewName[12];
{
cout << "Specify new file name: ";
cin >> cNewName;
char cNewName[12];
cout << "Specify new file name: ";

cin >> cNewName;

Copyright

Page: 167

ifstream infile("prodfile
...
com

171

Structured Programming with C++

7 Files

else
{
}

outfile << infile
...
close();

}

infile
...
h for input and output, fstream
...
h to allow for using
the function rdbuf()
...
Then we create the
instream, which is attached to the disk file prodfile
...
Note that cNewName is not enclosed in quotes, since it is a variable and not a specific string
...
If so, the variable outfile contains an address to the outfile
object
...
That means that !outfile is true if the address is 0
...
Otherwise, i
...
if the outstream could be created, we use the function rdbuf() to copy all data
in one single operation from the infile to the outfile
...

Having run the program you can by means of ’Explore’ check the new file
...
14 Summary
In this chapter we have learnt the basics of file management
...
You have also learnt that you communicate with the streams, and not directly with the disk files
...
You are now able to write programs
where the user can enter information to be stored in a file, and read information from a file and present it on the screen
...


7
...
Start with the program in the section ‘A Complete Write Program’
...
Check with the Notepad
program that the file contains the expected information
...
Start with the program in the section ‘A Complete Reading Program’ and modify it so it also will be capable
of reading the warehouse locations entered in the previous exercise
...
Start with the program in the section ‘New Item at the End of the File’ and modify it so that you also can
enter the warehouse location of the new product
...
Then
run the program in exercise and check the existence of the new product in the output
...
com

172

Structured Programming with C++

7 Files

4
...

5
...
Use the same file as created in the previous exercise
...
Start with the program in the section ‘Sorting a File in Memory’ and accommodate it to also be able to
manage the file with product names and warehouse locations created in the first exercise
...
Start with the program in the section ‘Updating File Content’ and modify it so that the user will be able to
update the quantity in stock
...

8
...
These should be saved in a file
...

9
...

10
...
The first and surname must then be entered from
the keyboard
...

11
...
The first and surname of the person must then
be entered
...
Create a program which sorts the names of the file by surname
...

13
...
The new file name should be entered by the user
...
Write a menu program where you gather the tasks from the latest exercises
...
Enter information
2
...
Update city
4
...
Sort
6
...
Exit
Select 0-6:

Download free eBooks at bookboon
...
1 Introduction
A pointer is a special kind of variable which contains a memory address to for instance a number instead of directly refer
to the number
...

This might sound unnecessarily complicated, but implies a number of advantages like for instance more efficient program
code, faster execution and memory saving
...
Object oriented programming is however beyond the scope of this course
...
It is for instance not present in the programming languages Visual Basic or Java
...

In this chapter we will aqcuire basic knowledge about pointers
...
We will examine the anology between pointers and arrays and how to use
pointers as parameters to functions
...


8
...
This memory
location in turn contains a value of some kind
...
ligsuniversity
...

More info here
...
com

174

Click on the ad to read more

What Is a Pointer
A pointer is a variable of a special kind which only can contain a
memory 8 Pointers
Structured Programming with C++ address of the primary memory
...

Le tus first study the situation for
University first study the situation for a common variable:
Le tus West, Trollhättan
Department of Economy and Informatics

a common variable:
Structured Programming with C++

iNumber

34
In the figure above we have the variable iNumber which contains the
actual value of the variable, in our the actual value of the variable, in our example 34
...

Let us now focus on the corresponding pointer:
Let us now focus on the corresponding pointer:
Copyright

Page: 171

Address to value

23

pNumber
In the figure above we have a pointer named pNumber
...
If we go to that
In the figure above we have a pointer named pNumber
...

in our in the primary memory
...


8
...
int* means that it is a pointer to an integer value
...
Below we declare a pointer to a double value:

The asterisc (*) indicates that it is a pointer
...
You must always specify the data type
pointed to by the pointer variable
...
The
declarations above could be written:

char *pChr;

int *pNumber;
double *pPrice;
char *pChr;

Below we declare a pointer to a char value:
You can as well place the space in front of the asterisc
...


8
...


Assigning Values to Pointers

Assigning Values to Pointers
int iNo = 23;

An ordinary variable, say iNo, is assigned a value in the usual way:

An iNo, we variable, say iNo, The expression &iNo the the address
To get the address to the variable ordinaryuse the & operator
...

int iNo = 23;
In the declaration you can specify the memory location to be pointed at by a pointer variable:
Download free eBooks at bookboon
...
The variable iNo and
the pointer variable pNumber now points to the same memory location, which means the value 23
...
However, when pNumber has got its memory
address, we can change the value in the location indicated by pNumber:
*pNumber = 25;
Here we must remember to use the asterisc together with the name of the pointer variable
...

Compare this to this erroneous statement:
pNumber = 25;

//wrong

This would mean that we updated the address pointed to by pNumber
...

We have introduced two operators in connection with pointers:
*

means ‘the content of ’

&

means ‘the address to’

In the same way we can write:
//ordinary variable:

double dPrice = 34
...
25;

// ordinary variable:
char cChr = 'x';

//pointer with the same address as cChr:
char* pChr = &cChr;

//change the character:
*pChr = 'y';

When printing a value pointed to by a pointer variable, you use:
cout << *pNumber;

//prints 25

This means ‘print the content of pNumber’
...
com
176

Structured Programming with C++

8 Pointers

To print the address pointed to by a pointer variable you write:
cout << pNumber;

//prints the address, e
...
0x0066FDF0
The printed address is in hexadecimal format
...
The only thing
to remember is whether we mean ‘the address to’ or ‘the content of ’
...
5

Addresses and char Pointers

We will now take a look at how pointers work in connection with string variables, i
...
arrays of char type
...

char* pName = cName;
Why didn’t we use the & operator in front of cName like in the previous example? The explanation is that an array actually
is a pointer
...
So when
writing the statement:
pName = cName;
it means that we let the pointer pName get the same address as the pointer (array) cName
...
com

177

Click on the ad to read more

Structured Programming with C++

8
...
The statement:
cout << pName;
should actually print the address in hexadecimal format of pName
...
It takes the
content in the memory location pointed to by pName, i
...
the character ‘J’, and prints character by character until the null
character is found
...
Compare the statement:
cout << cNamn;
University West, Trollhättan

which gives the same result, which we discussed in the Strings chapter
...
This means
pName, but it pointed to by character
...

that only ‘J’ is printed
...


The in which
prints the address of the memory locationstatement pName is stored
...

cout << &cName;
prints the address of the memory location where the name ’John Smith’ is stored
...
7

We will now create a program which reads quantitycreate a program which reads quantity and unit price of of the user
...
The programscreen
...

note on the screen
...


The logical process
The logical process is given by the following JSP graph: is given by the following JSP graph:

Price

Enter name,
qty and price

Calculate
total

Print price
note

Here is the code:
Download free eBooks at bookboon
...
h>

void main()
178
{
//Declare variables and corresponding pointers
//Set the pointers to point to the address of the
//corresponding variable

Structured Programming with C++

8 Pointers

Here is the code:
#include ...
getline(pName, 19);

cout << "Enter quantity and unit price: ";
cin >> *pNo >> *pPrice;
//Calculate total

*pTotal = *pNo * *pPrice;
//Printout of personal price note

cout << "Dear " << pName << ", your price is " <<
}

*pTotal << " kr
...
Then the printout will be:
Dear John Smith, your price is 60 kr
...
8

Pointer Arithmetics

By pointer arithmetics we mean how to increment and decrement a pointer, i
...
how to make a pointer to an array move
stepwise from item to item
...
com

179

Structured Programming with C++

8 Pointers

Here we have declared the array iNos to contain six items
...
If
the first integer (5) is stored in memory address 2000, then the next integer (12) will be stored in memory address 2004,
the third in 2008 etc
...

We can now perform the following pointer arithmetic:
pNos++;
which means that pNos is increased by 1
...
But
that is not the case
...
This implies that pNos now
points to the second item of the array
...

As a consequence the data type pointed to by a pointer is of ultimate importance when using pointer arithmetics
...


Download free eBooks at bookboon
...

Structured Programming with C++ a8 Pointers
As consequence the data type pointed to by a pointer is of ultimate
importance when using pointer arithmetics
...
printing the second, third item etc
...
with a parenthesis, so the

pNos+1, pNos+2, etc
...
e
...

first item of the array, would be increased by 1, taking the asterisk (‘the content of’) into account,
otherwise the content of pNos, i
...
the first item of the array, would be
increased
We may as well use a loop for the printout: by 1, 2 etc
...
e
...
e
...
For each turn
turns as there are items in the array
...
e
...
e
...

item of the array
...
9

Tax Program

Tax Program

We will not create a full-featured tax calculation program, but only calculate the tax deduction for a number of monthly
salaries based on fix tax percentages
...
We multiply each salary
calculate the and corresponding number of monthly salaries based on
fix tax percentages
...
Each salary and tax percent are then printed
University West, Trollhättan

Structured Programming with C++

We store a number of monthly salaries in an array and corresponding
Department of Economy and Informatics
in table format
...
We multiply each salary by corresponding
tax percentage, which in the arrays
...
Each salary and
tax percent are then printed in table format
...


Tax
Copyright

Page: 177

Initiate salary
and tax %

Print
salary no
...
com

Print table

*

Calculate and
print tax no
...
When
printing the table we go through one item at a time of the arrays and
print salary and corresponding tax, which is calculated by multiplying

Structured Programming with C++

8 Pointers

First we initiate the arrays with salaries and tax percentages
...
Then
we increase both pointers to proceed to the next salary and tax percentage
...
h>
#include ...
32, 0
...
35, 0
...
365, 0
...
h for input and output, and iomanip
...

In main() we initiate the array iSal with a number of salaries and the array dTax with a number of tax percentages
...

The first cout statement fixes the decimal point and states two decimals
...

The for-loop goes from 0 to 5, i
...
as many turns as there are items in the arrays
...
Note that we use asterixes in front of the pointers to get ‘the content of ’
...
e
...
The
program automatically remembers that one of the pointers is an integer pointer and the other a double, and moves them
the corresponding number of bytes in the primary memory
...
10

Functions and Pointers

Many times you use pointers as parameters to functions
...
Especially in object oriented programming when you want to send an object to a function
which is several Mbytes big, it is a great advantage to only send a memory address instead
...

Download free eBooks at bookboon
...
It is very similar to sending pointers
...

You should however keep in mind that if you send a pointer to a function, and the function updates the value, the value
will be updated also after completion of the function
...
More about this later
...
The string is sent as pointer to the function find()
...
If @ is found, a suitable text is printed on the screen
...
mastersopenday
...
com

183

Click on the ad to read more

University West, Trollhättan
Department of Economy and Informatics

Structured Programming with C++

Structured Programming with C++

8 Pointers

find

Search char
...
pointer

*

o

Here is the code:
void find(char* str)

Here is the code:

{

void
for (int p=0; p<8; p++) find(char* str)
{
{
for (int p=0; p<8; p++)
if (*str == '@')
{
if (*str == '@')
cout << "It is an email address";
cout << "It is an email address";
str++;
str++;
}
}
}
}
The function takes a parameter str which is a pointer to a char variable
...
The for-loop goes from 0 to 7, string but only the but we have
variable
...
of the string
...
character
...
At the end of
University West, Trollhättan

Structured Programming with C++

the loop the pointer is increased byandif statement checksto the next character
...
e
...
If so, the suitable text is printed
...
e
...
First a JSP graph:
pointer is the user is prompted is a text that sent next function
...
First a JSP graph:
find-prog

Enter a string

find

Here is the code:
Copyright

#include ...
com
{
char cString[9];
184
char* pString=cString;
cout << "Enter a text: ";
cin
...
h>
void find(char* str);
void main()
{

char cString[9];

char* pString=cString;

cout << "Enter a text: ";
cin
...
The pointer pString is set to point to the first character of the
string
...

We will now illustrate the risk of having the value outside the function be changed
...
If we would print the email address in main() after completion of the
function find() with the purpose of having the original email address printed, then we would get a wrong result
...
com of @
...
Many
programmers use const in this way to clearly indicate that the value is not changed in the function
...
11

Dynamic Memory

When declaring an array in Visual C++ we have until now been forced to specify the number of items of the array to
allocate the correct memory space
...

Many times we cannot in advance predict the number of items needed for the array, for instance when reading a number
of product id:s to an array from a file, where the number of products is unknown
...
The dynamic memory area is capable of assigning space during
the execution of the program and not at the compilation
...
A disadvantage is however that the program cannot guarantee that the requested amount of memory
is available
...

To allocate dynamic memory you use the keyword new
...
com

186

Click on the ad to read more

Structured Programming with C++

8 Pointers

cout << "How many products will be entered? ";
cin >> iNumber;

pNo = new int[iNumber];
Here we declare a pointer to int, pNo, and a common int variable iNumber
...
This value is used as the number of items of the array declared in the last statement
...
Therefore,
we insert a check by means of the following:
if ( (pNo = new int[iNumber]) == 0)
{

}

cerr << "Not sufficient memory
...
If there is not enough memory, the result of the
declaration will be equal to 0
...

If there is enough memory the value of the condition is not 0, and the program continues with subsequent statements
...
Don’t
forget to include the header file stdlib
...

After the if statement we can now continue with product entry to the array:
for (int i=0; i{

}

cin >> *pNo ;
pNo++;

The loop performs as many turns as the number of items of the array
...
pNo is increased by 1, i
...
the pointer moves on to the next item
of the array
...
e
...
com of the program
...
We release the memory for
the array with the statements:
Structured Programming with C++ 8 Pointers
pNo=pNo-iNumber;
delete[] pNo;

pNo=pNo-iNumber;
delete[] pNo;

First we reset the pointer to its originalFirst we reset thenpointer to its original position and then we use the memory
...

We now give a JSP graph that shows the process:give a JSP graph that shows the process:
We now

Products

Enter
no
...

dyn
...
i

*

Reset
pointer

*
Incr
...
i

*

Reset
pointer

Release
memory

**
Incr
...
h>
#include ...
h>
#include ...
The program will exit!";
exit(1);
{
}
cerr << "Not sufficient memory
...
com

188

Structured Programming with C++

8 Pointers

cout << *pNo << endl;
}

pNo++;

pNo = pNo - iNumber;
}

delete[] pNo;

We will now create still another program where we instead of product id:s enter a number of names of char type and store
the names in arrays in the dynamic memory
...

We will then create a new char array with the new keyword for each name
...
Here is the code:
#include ...
h>
void main()
{

const int iNo = 5;
char temp[30];

// Number of strings to be stored

// Tempory storage of entered name

char *cNames[iNo]; // Space for 5 string pointers with

// arbitrary number of characters

cout << "Enter the names of 5 course mates" << endl;

Need help with your
dissertation?
Get in-depth feedback & advice from experts in your
topic area
...
helpmyassignment
...
uk for more info
Download free eBooks at bookboon
...
" << i + 1 << " ";
cin
...
12 Summary
In this chapter we have learnt the basics of one of the areas that makes C++ unique compared to other programming
languages
...

We have learnt to declare and assign values to pointers of different data types
...

We have also learnt to send pointers as parameters to functions and we have learnt some about dynamic memory
allocation
...
This might seem to be unnecessarily complicated from the beginner’s point of view, but provides
rich opportunities to effective programming aiming at memory minimizing programs with high performance
...


8
...
Write a little program which declares an integer variable and initiates it to the value 25
...
Print the value by means of the pointer
...
Write a program similar to the previous applying it to a string with your own name instead of an integer
...
Start from the program in the section ’Price Program with Pointers’
...
Use a pointer for the discount
...
Write a program which prompts the user for a driven number of miles and the fuel consumption for the
trip
...
Use pointers like in the
previous programs
...
com

190

Structured Programming with C++

8 Pointers

5
...

6
...
The integers should then be printed
...

7
...
Use a pointer variable for the sum
...
Start from the program in the section ‘Tax Program’ and modify it so that the user enters the salaries and
tax percentages
...
Modify the previous program to instead read the information from a file instead of from the keyboard
...
Write a program which reads product id:s and prices from a file and stores them in arrays, one array for the
product id:s and one for the prices
...
The program should then print a nice table of products
and prices
...
Modify the program in the previous exercise so that the user can enter a product id and get the
corresponding price printed
...

12
...
Modify the function so that it prints the updated string from
inside of the function
...

13
...

14
...
The string should be sent
to the function as a pointer
...
The program should print the updated string
...
Write a function which takes a pointer to an integer array and the number of items of the array as
parameters, finds the greatest item and returns it
...
The function is called and the returned greatest item is printed
...
Modify the previous exercise so that the user first enters the number of integers being entered
...

17
...
Since telephon numbers can contain blanks and hyphen (e
...
0522-23 23 23) they are of char type
...

18
...


Download free eBooks at bookboon
...
1 Introduction
When working with data from files and databases it is often convenient to process big portions of data in one lump, for
instance an entire customer record in a customer file
...
A structure is a set of
data that in some way has an intermediary relation
...

Structures are a pre-state to classes within object oriented programming
...

In this chapter we will learn how to define structures, handle information stored in structures, work with arrays of structures
and files in connection with structures
...


9
...
All this information is stored for each customer in the customer file
...
It is then gathered into a structure, which provides better organization of the program code
...
A structure behaves in the code like a data type such as
int, double or char
...
In the structure variable you can then store all
information for a particular customer
...
The array will thus contain all information for all customers
...
3

Defining a Structure

First we will learn to define a structure template, i
...
specify the shape of the structure, the structure members and the
data type of each member of the structure
...


Download free eBooks at bookboon
...
Within curly brackets you then
enumerate the members of the structure, where each member is declared in the usual way of declaring variables
...
After the last right curly bracket there must also be a semicolon
...
You can also have other structures as members of the structure, if applicable
...


9
...
e
...
You can also initiate it with values already in the declaration:
Prod prodOne = {"Olive Oil", 1001, 120
...
The
data types of the values must correspond to the definition of the members
...
5

Assigning Values to Structure Members

When updating, copying or in other ways processing the value of a structure member, you use the following way of coding:
prodOne
...
Here the
quantity in stock will be set to 251 for the ‘Oliv Oil’ product
...
cSupp, cString);
This requires that cString is a string array whose content is copied to the cSupp member
...
com

193

Structured Programming with C++

9
...
We will create a product structure according to the previous example

University West, Trollhättan
Structured Programming with C++
and two Economy and Informatics
Department of structure variables with product information
...
Finally the program should print a table of the products
...
structure code:
The logic is simple
...
handle the difficult task is to handle theHere is thein
the correct way
...
h>
#include ...
Already today, SKF’s innovative knowvoid main()
how is crucial to running a large proportion of the
{
world’s wind turbines
...
50, 250, reduced dramatically thanks to our
nance
...
We help make it more economical to create
// Declare a new Prod variable
cleaner, cheaper energy out of thin air
...

industries
cout << "Enter information for a product:" << need the best employees who can
Therefore we endl;
cout << "Start with the product name: "; challenge!
meet this
cin
...
cName, 20);
cout << "The product id: ";
The Power of Knowledge Engineering
cin >> prodTwo
...
dPrice;
cout << "How many items are there in stock? ";
cin >> prodTwo
...
get(); // clear in-buffer from new line char
cout << "Who supplies the product: ";
Plug into The Power of Knowledge Engineering
...
getline(prodTwo
...
skf
...
cName << '\t' << prodOne
...
dPrice << '\t' <<
Download free eBooks at bookboon
...
iNo << '\t' << prodOne
...
50, 250,
"Frescati Oil S/A"};

// Declare a new Prod variable
Prod prodTwo;

// Prompt the user for product information

cout << "Enter information for a product:" << endl;
cout << "Start with the product name: ";
cin
...
cName, 20);
cout << "The product id: ";
cin >> prodTwo
...
dPrice;

cout << "How many items are there in stock? ";
cin >> prodTwo
...
get();

// clear in-buffer from new line char

cout << "Who supplies the product: ";
cin
...
cSupp, 25);
cout <<"Prodname


\tProduct id \tPrice \tQuantity

\tSupplier" << endl;

cout << prodOne
...
iId

<< "\t\t" <<

prodOne
...
iNo << '\t' <<


}

// tab with \t

endl << endl;

prodOne
...
cName << '\t' << prodTwo
...
dPrice << '\t' << prodTwo
...
cSupp << endl << endl;

The definition of the structure is before main(), which makes it valid for the entire program, also inside functions
...

The first structure variable prodOne is initiated with values directly in the declaration
...
Note that we use a period between
the structure variable and member
...
com

195

Structured Programming with C++

9 Structures

The output is done by means of tabs \t
...
We could have done that more flexible by means of the text formatting
functions from chapter 1, but we used a rough method for simplicity’s sake
...
7

Array with Structure Variables

A disadvantage with the previous program is that we needed a separate structure variable (prodOne, prodTwo) for each
product
...

Below we declare a structure array sProds of the type Prod with three items:
Prod sProds[3];
We have allocated memory space for three products, but we have not yet assigned values to the structure members
...
50, 100, "Felix Ltd"},
{"Baby Oil", 102, 23
...
All three pair of brackets are surrounded by an extra pair of curly brackets
delimiting the initiation list of values
...

If you want to let the user enter values, this is preferably done in a loop:
for (int i=0; i<3; i++)
{

cout << "Enter values for product no
...
getline(sProds[i]
...
iId;

cout << "The price: ";

cin >> sProds[i]
...
iNo;

cin
...
getline(sProds[i]
...
com

196

Structured Programming with C++

9
...

The advantage is to be able to use pointer arithmetics to step through the different structure variables:
pProd++;
This statement moves to the next structure variable
...
) as delimiter between the variable and member
...
com

197

Structured Programming with C++

9 Structures

Suppose we have declared and initiated an array sProds with space for three structure variables and with values like in
the previous section:
Prod sProds[3] = {

{"Food Oil", 101, 12
...
75, 25, "Baby Prod"},

};

{"Boiler Oil", 103, 6100, 123000, "Shell"},

Then we can declare a pointer of Prod type which points to the first item of the array:
Prod* pProd = &sProds[0];
Then we can use a loop to print for example the product id:s for the three products:
for (int i=0; i<3; i++)
{

}

cout << pProd->iId << endl;
pProd++;

Note that we have used pointer arithmetics to step from product to product
...
9

Structures in the Dynamic Memory

When we at the compilation cannot predict the number of products to be stored in the array, it is convenient like for
other arrays (see the ‘Pointer’ chapter) put the structure array in the dynamic memory area
...

In the following code we prompt the user for the number of products to be entered, and then declare a pointer to an
array in the dynamic memory space:
int iQty;

cout << "How many products should be
entered? ";

cin >> iQty;

Prod *pProd = new Prod[iQty];
In the declaration of the array we must specify the number of structures to allocate memory for
...

Then, with a loop, we can let the user enter information to the requested number of products:
for (int i=0; i{

cin >> pProd->iId;

// … and the remaining structure members

Download free eBooks at bookboon
...
For each turn of the loop we increase the pointer by 1,
thus making it point to the next structure variable of the array
...
But first we must reset the pointer to the position of the first
item of the array:
pProd = pProd - iQty;

for (i=0; i{

cout << pProd->iId << endl;

// … and the remaining structure members
}

pProd++;

Also here, we use pointer arithmetics to proceed from item to item of the array
...


9
...
10
...
Suppose we want to create a
function which prints the content of the structure sent to the function
...

The first example of printOnScreen() takes a parameter that is a reference parameter (see the ’Functions’ chapter) of a
structure:
void printOnScreen(Prod & rProd)
{

cout << rProd
...
iId << "\t\t\t" <<
rProd
...
iNo << '\t' <<

}

rProd
...
It is no pointer, so we use a period as delimiter between the structure variable and member
...

Download free eBooks at bookboon
...
It is no
Structured Programming with C++ 9 Structures
pointer, so we use a period as delimiter between the structure variable
and member
...

We will create a simple program to test the function
...
Here is the JSP graph:
graph:
Product 1

Initiate
structure variable

printOnScreen

Print
members
We initiate a structure variable, which is sent to the function, where the members are printed
...
h>

We initiate a structure variable, which is sent to the function, where
the members are printed
...
h>
{
struct Prod
char cName[20];
{
int iId; char cName[20];
int iId;
double dPrice;
double dPrice;
int iNo;
char cSupp[25];
};
void printOnScreen(Prod & rProd)
{
cout << rProd
...
iId << "\t\t\t" <<

Copyright

Page: 196

Download free eBooks at bookboon
...
cName << '\t' <<

rProd
...
dPrice << <<
rProd
...
dPrice << '\t' <<
rProd
...
iNo << '\t' <<
}
rProd
...
50, 250, "Frescati
void main()
Oil S/A"};
printOnScreen(prodOne);
{
}
Prod prodOne = {"Olive Oil", 1001, 120
...
Then there is the function
printOnScreen()
...
The the function
printOnScreen() is called, to which we send prodOne as actual
First we define the structureparameter
...
In main() we declare a structure variable
Prod
...
The the function printOnScreen() is called, to which we send

Array
prodOne as actual parameter
...

Next variant of the function printOnScreen() takes a parameter which is a structure array and a parameter to the number

9
...
2 Array Parameter

Remember that, when sending an array as a parameter to a function, it
is always made on reference basis
...
Therefore, you
Remember that, when sending an array as a parameter to reference parameter by using the &
character
...

Here is the JSP graph for the function:
Here is the JSP graph for the function:
of items in the array
...
n

Here is the code:

Download free eBooks at bookboon
...
cName << '\t' <<
i++)
p[i]
...
cName << '\t' <<<< '\t' <<
p[i]
...
dPrice << '\t' <<
p[i]
...
dPrice << '\t' p[i]
...
iNo << '\t' <<
}

p[i]
...
The second parameter is
The first parameter is of Prod type and has the name p with a subsequent items of the array
...
The second
called n and corresponds to the number of square bracket to indicate
have been given the const keyword to ensure that the been given is
parameter is called n and corresponds to the number of items of the array
...

ensure that the information is not updated in the function
...
The as there is items in the array
...

the array to indicate specific items
...
The JSP graph is:
We create a simple program to test the function
...
h>
#include ...
cName << '\t' <<
{
Download free eBooks at bookboon
...
cName << '\t' <<
p[i]
...
dPrice << '\t' <<
p[i]
...
cSupp << endl << endl;

}

void main()
{

Prod sProds[3] = {

{"Food Oil", 101, 12
...
75, 25, "Baby Prod"},

};

}

{"Boiler Oil", 103, 6100, 123000, "Shell"},

printOnScreen(sProds, 3);

In main() we declare an array of Prod type with three items, which are initiated with values
...


Download free eBooks at bookboon
...
The function printOnScreen() is called, to which
we send the structure array and the number 3 as actual parameters
...
10
...

parameters
...
n

Here is the code of the function:
void printOnScreen(Prod *p , const int n)
{

for (int j=0; j{

cout << p->cName << '\t' <<
p->iId << '\t' <<

Copyright

p->dPrice << '\t' <<

Page: 199

p->iNo << '\t' <<

p->cSupp << endl << endl;

}

}

p++;

The pointer parameter has the name p and the number of products n
...
In the loop we print the members of the structure
...
At the end of the loop we use pointer arithmetics and increase p by 1, i
...
moves p to the next structure
...
com

204

In the loop we print the members of the structure
...
At the end of the
loop we use pointer arithmetics and increase p by 1, i
...
moves p to
the next structure
...
Here is the JSP
graph:
We create a simple program to test the function
...
h>
struct Prod
{

char cName[20];
int iId;

double dPrice;
int iNo;
};

char cSupp[25];

void printOnScreen(Prod *p , const int n)

{
Copyright

Page: 200

for (int j=0; j{

cout << p->cName << '\t' <<
p->iId << '\t' <<

p->dPrice << '\t' <<
p->iNo << '\t' <<

p->cSupp << endl << endl;

}

}

p++;

void main()
{

Prod sProds[3] = {

{"Food Oil", 101, 12
...
75, 25, "Baby Prod"},

};

}

{"Boiler Oil", 103, 6100, 123000, "Shell"},

Prod *pProd = &sProds[0];
printOnScreen(pProd, 3);

Download free eBooks at bookboon
...
Then we declare a Prod pointer
to point to the first item of the array (the & character means ‘the address to’)
...


9
...
We have learnt to define structures and
declare structure variables and fill the structure with values
...
When unable to predict the number of
items to be contained by the array, we have stored it in the dynamic memory area with the new keyword
...

You will now try your new knowledge in a number of exercises
...
12 Exercises
1
...
Then write a program that declares a structure variable and
initiates it with some values according to your preference
...

2
...

3
...
All three customers should then be printed
...
Change the previous program so that the user can enter an order total to be added to the member ’total
invoice amount year-to-date’
...

5
...

6
...
It should then be possible to enter information for the customer
...

7
...
Entry and printing
as before
...
Change the previous program to let the user first specify the number of customers to be entered
...

9
...
Use the Prod definition given previously in the
chapter
...
Use reference parameters
...
Examine the file
content afterwards by means of the Notepad program
...
Change the function in the previous example to print an array of structures to the file
...

11
...

12
...

Download free eBooks at bookboon
...
1 Variables
Exc
...
2
#include

using namespace std;
void main()
{

int iNo1, iNo2;

Download free eBooks at bookboon
...
3
#include

using namespace std;
void main()
{

int iNo1, iNo2;

cout << "Specify 2 numbers: ";
cin >> iNo1 >> iNo2;

cout << "Total = " << iNo1 + iNo2 << endl;

cout << "Difference = " << iNo1 - iNo2 << endl;
cout << "Product = " << iNo1 * iNo2 << endl;
}

cout << "Quotient = " << (double)iNo11/iNo2 << endl;

Exc
...
5
#include
#include

using namespace std;
void main()
{

//Declarations

Download free eBooks at bookboon
...
First the price without tax
dPriceExTax = dUnitPr * iNo;
//Discount:

dDisc = dPriceExTax * 0
...


cout << endl << "INVOICE" << endl << "=======" << endl;

Challenge the way we run

EXPERIENCE THE POWER OF
FULL ENGAGEMENT…
RUN FASTER
...

RUN EASIER…

READ MORE & PRE-ORDER TODAY
WWW
...
COM

Download free eBooks at bookboon
...
indd 1

22-08-2014 12:56:57

209

Click on the ad to read more

Structured Programming with C++

10 Answers

cout << "Quantity:" << setw(11) << iNo << endl;

cout << setprecision(2) << setiosflags(ios::fixed);

cout << "Price per unit:" << setw(8) << dUnitPr << endl;

cout << "Excl
...
6
#include
#include

using namespace std;
void main()
{

//Declarations

double dNoOfLit, dLitPrice, dTotal;
//Entry of quantity and unit price

cout<< "Enter no
...
First the price excl tax
dTotal = dNoOfLit * dLitPrice;
//Printout

cout << endl << "

RECEIPT" << endl;

cout << setprecision(2) << setiosflags(ios::fixed);

cout << "Volume:
endl;

" << setw(9) << dNoOfLit << " l" <<

cout << "Lit
...
7

#include

using namespace std;
void main()
{

double dPrev, dCur, dPricekwh, dTotal;

Download free eBooks at bookboon
...
8
#include

using namespace std;
void main()
{

int t1, t2, t3, t4, t5;

cout << "Specify 5 numbers: ";

cin >> t1 >> t2 >> t3 >> t4 >> t5;

cout << "Sum = " << t1 + t2 + t3 + t4 + t5 << endl;

cout << "Average = " << (double)(t1 + t2 + t3 + t4 +
t5)/5 << endl;

cout << "Sum of squares ="<+t4*t4+t5*t5<
cout << "Sum of cubes = " << t1*t1*t1 + t2*t2*t2 +
t3*t3*t3 + t4*t4*t4 + t5*t5*t5 << endl;

}
Exc
...
10
#include

using namespace std;
void main()

Download free eBooks at bookboon
...
8 * dTempC + 32;

cout << "Corresponding temperature in Fahrenheit is " <<
dTempF << endl;

}
Exc
...
com

212

Click on the ad to read more

Structured Programming with C++

10 Answers

iNoOfHours = iNoOfMin / 60;

//and number of minutes left:
iMinLeft = iNoOfMin % 60;
//Printout

cout << "No
...
of minutes = " << iMinLeft << endl;

Exc
...
of years

= " << iNoOfYears << endl;

cout << "No
...
of months = " << iMonLeft << endl;
}

Exc
...
com

213

Structured Programming with C++

10 Answers

cin >> s >> v;
t = s/v;
}

cout << "The trip takes " << t << " hours" << endl;

Exc
...
15
#include

using namespace std;
void main()
{

double s, v, t;

// distance, velocity, time

cout << "Enter average speed in km/h and time in hours: ";
cin >> v >> t;
s = t*v;
}

cout << "The distance is " << s << " km" << endl;

Exc
...
com

214

Structured Programming with C++

10 Answers

iOre50Left = iOre50%2;
iKr5 = iKr/5;

iKrLeft = iKr%5;
iKr10 = iKr5/2;

iKr5Left = iKr5%2;

//Take 50kr values before 20, since 20 is not possible
//to evenly divide in 50
iKr50 = iKr10/5;

iKr10Left = iKr10%5;

iKr20 = iKr10Left / 2;

iKr10Left -= (iKr20 * 2);
iKr100 = iKr50/2;

iKr50Left = iKr50%2;
cout << "No
...
of 50 kr notes

= " << iKr50Left << endl;

cout << "No
...
of 20 kr notes
cout << "No
...
of 1 kr coins

= " << iKr20 << endl;

= " << iKr5Left << endl;
= " << iKrLeft << endl;

cout << "No
...
of ore

= " << iOreLeft << endl;

Download free eBooks at bookboon
...
17
#include

using namespace std;
void main()
{

double dLen, dWidth, dHeight, dSpace, dFenceLen,
dNoOfSticks, dTotMeters;

cout << "Enter length and width of the field: ";

cin >> dLen >> dWidth;

cout << "Enter face height and space between boards
cin

in m: ";

>> dHeight >> dSpace;

dFenceLen = dLen * 2 + dWidth * 2;

//Each board takes its width 0
...
10 + dSpace);
dTotMeters = dNoOfSticks * dHeight;
}

cout << "Total board length = " << dTotMeters << endl;

Exc
...
9;
Exc
...
20
#include
#include

#include ...
h>

using namespace std;

//for formatting of printouts
//for random numbers
//for system clock

void main()
{

Download free eBooks at bookboon
...
of rolls: " << iNo << endl;
cout << setprecision(1) <<

setiosflags(ios::fixed);

cout << "Average score: " << dAvg << endl;
cout << "Roll scores: "

<< iRoll1 << iRoll2 << iRoll3 <<

iRoll4 << iRoll5;

}
Exc
...
h>
#include ...
com

217

Structured Programming with C++

10 Answers

iRoll22 = rand()%6+1;
iRoll32 = rand()%6+1;
iRoll42 = rand()%6+1;
iRoll52 = rand()%6+1;
//Printout

cout << "The double rolls are: " <
iRoll11+iRoll12<iRoll31+iRoll32<iRoll51+iRoll52<
}
Exc
...
h>
#include ...
sylvania
...

Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges
...
Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths
...
Come and join us in reinventing
light every day
...
com

218

Click on the ad to read more

Structured Programming with C++

10 Answers

L3 = rand()%35+1;
L4 = rand()%35+1;
L5 = rand()%35+1;
L6 = rand()%35+1;
L7 = rand()%35+1;

cout << "The Lotto scores are: " <
<<
}
Exc
...
h>
#include ...
2

Selections and Loops

Exc
...

Exc
...

The if statement should then check if the number is less than 15
...

Exc
...
com

219

Structured Programming with C++

10 Answers

if (iNo<15)

cout << "You'll got to stick to the bike some more time ";

else if (tal<18)

cout << "You are allowed to drive moped";

else

cout << "You may drive the car";

Exc
...
5
if (dGross > 500)
dDisc = 10;

else if (dGross > 250)
dDisc = 5;
else

dDisc = 0;
Exc
...
12;
else if (iProdType == 2)

dTaxAmount = dGross * 0
...
7
Use else if to locate different intervals
...


For 10000-50000 the tax is 0
...
For 50000-100000 the tax is
0
...
For >100000 the tax is income*0
...
2
...
8
See the code proposal in the 'Even or Odd' section
...
com

220

Structured Programming with C++

10 Answers

Exc
...


Exc
...
The
sum of the crown types is:

iNoOf1kr + iNoOf5kr * 5 + iNoOf10kr * 10

For the 50-ore coins the number of whole crowns will be:
iNoOf50ore / 2

provided that iNoOf50Ore is declared as integer
...
11
Use else if repeatedly to locate the various intervals and print corresponding
discount
...
12
if (iNo>20 && iTotal>1000)
dDisc = 0
...
1;

else

dDisc = 0;

Exc
...
com

221

Structured Programming with C++

10 Answers

Exc
...
15
Combine the method for the previous menu program and the method to compare
three numbers in a previous exercise
...
16
See the first program in the section about loops
...
17
Also print iNo*iNo*iNo inside the loop
...
18
do
{

cout << "Enter a number: ";
cin >> iNo;

}while (iNo!=0);
Exc
...
Inside the loop you

increase the sum variable by the entered value
...

Exc
...
Inside the loop you write
an if statement which checks if iNo is less than 0 and print a suitable text
...
21
do
{

cout << "Enter a number: ";
cin >> iNo;

}while (iNo%3 != 0);

Download free eBooks at bookboon
...
22
Use input of the score in the while condition:
while (cin>>iScore)

Use a sum variable to store the accumulated sum of all scores entered so far
...


Also declare two variables, iGreatest and iLeast, which store the greatest and
the least score respectively
...
If so, assign this new value
to iGreatest
...


After the loop you subtract iGreatest and iLeast from the sum before printing
the sum
...
23
Insert a statement which reads the requested product from the keyboard
...
24
Start from the program in the previous exercise
...
Inside the first loop you check if the division numerator/denominator
is 5 and if

numerator%denominator is 0
...

Exc
...

Exc
...
27
Print iRoll1 and iRoll2 from inside of the loop
...
28
while ((iRoll1 + iRoll2) != 12)
Exc
...


In the inner loop you create the random scores for the first match in the 5
different pools
...


Download free eBooks at bookboon
...
30
rand()%2 gives a random number between 0-1
...
If so, you print "heads",
otherwise "tails"
...
31
You can solve this in different ways
...
Then you can create a new random number between 1-13,
where 2-10 is the corresponding value, 11 is jack, 12 is queen, 13 is king
and 1 is ace
...
32
Change the calculation of LP to:

360°
thinking

LP = iRoot * iRoot - 8 * iRoot + 15;
Exc
...


LP = iRoot * iRoot * iRoot - 9 * iRoot * iRoot + 23 * iRoot - 15;
The while condition should check that iNo<3
...


360°
thinking


...
deloitte
...


Discover the truth at www
...
ca/careers

© Deloitte & Touche LLP and affiliated entities
...
com
© Deloitte & Touche LLP and affiliated entities
...
deloitte
...


D

Structured Programming with C++

10 Answers

10
...
1
int iNos[10];

for (int i=0; i<10; i++)
{

}

cout << "Enter integer: ";
cin >> iNos[i];

a)

cout << iNos[0] << " " << iNos[4] << " " << iNos[9];

b)

In the for-loop you increase a sum variable by the recently entered number:
iSum += iNos[i];

After the for-loop you print iSum
...
In a loop you check:
if (iNos[i] < iUserNo)

cout << iNos[i] << " ";

f)

Read a number from the user between 0-9 to the variable k
...


Download free eBooks at bookboon
...
Then write a loop which checks:
if (iNos[i] == iUserNo)
cout << i;

h)

Copy iNos[0] to a variable temp
...
2
Complete the declaration of iDaysInM
...

Exc
...

Then print dblTempAug in a loop
...
4
Code example is given in the "Comparing Arrays" section
...
5
Assign another value to one of the items of dblTempAug, e
...
:
dblTempAug[12] += 1;
Exc
...

Exc
...
Read one density from the user
...
If so, print dDens[i-1] and break the loop,
so that only one value is printed
...
8
Create a loop from 0-24 which assigns values to the items:
iNos[i] = rand()%10;

Download free eBooks at bookboon
...

Exc
...
10
Declare a new array iNoOfSales[100] which should hold the number of sales per

salesman
...
When a salesman enters a value, you
increase:

iNoOfSales[nr-1]++;

We will turn your CV into
an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand?
We will appreciate and reward both your enthusiasm and talent
...
You will be surprised where it can take you
...
employerforlife
...
com

227

Click on the ad to read more

Structured Programming with C++

10 Answers

The printout should contain an additional column where you print
iNoOfSales[i]
...
11
Add one more column to the output where you print sales[i]/iNoOfSales[i]
...
12
See code example in the "Product File, Search" section
...
13
Read a quantity from the user and multiply it by the achieved price
...
14
Declare and initiate a two-dimensional array according to the code example

in the "Two-Dimensional Array" section
...
Calculate the discount amount by multiplying the discount
percent by the total price, and subract the discount amount from the total
price
...
15
Code example for random dice rolls is given in the chapter about Selections
and Loops
...

Exc
...

Exc
...
18
if (r == l+1 && iFound == 0)

cout << "The product id was not found";

In this situation you have enclosed an interval with the distance 1 between l
and r
...

Exc
...
Use the value
of the variable iMid to get the corresponding price of the price array
...
com

228

Structured Programming with C++

10 Answers

10
...
1
Add the following statements:

cout << "E
...
2
Start from the program 'Menu Program with Loop'
...
3
Read a character from the keyboard to a char variable
...
4
Create an outer loop which goes from 1 to 10 with the loop variable i
...
Print the character i in the
inner loop
...

Exc
...
Read the

number to an integer variable for instance named i
...
Inside the loop you print cChar
...
6
The first outer loop goes from 14 to 0
...
The last inner loop goes from 0 to 13
...
7
Read the character to a char variable
...

Exc
...
Assign this value to a char
variable and print it
...
com

229

Structured Programming with C++

10 Answers

Exc
...

Exc
...
getline()
...

Exc
...


If you enter other characters, an increase by 32 gives a character that does
not correspond to the relation between upper and lower case
...
12
Read the word to a char array
...
In each turn of the loop you print a character
twice:

cout << cWord[i] << cWord[i];
Exc
...
Then create a loop which goes from 0 to the

length of the string minus 1
...
com

230

Click on the ad to read more

Structured Programming with C++

10 Answers

The other alternative is solved with:
cout << strrev(cWord);
Exc
...

Exc
...
If so, decrease the character code by 32 before inserting the character
into the initials string
...
16
Create a loop which goes from character1 to character2 and prints the
character corresponding to each character code
...
17
Use the strcmp() function which compares strings
...
18
Create a loop which goes from 0 to number of characters minus 1
...
If so, increase a
counter (integer variable) by 1
...
19
Do like in the previous exercise when checking if the character is a
consonant
...
20
See the code example in the 'Sorting Strings' section
...
21
Declare a new array with prices:

Download free eBooks at bookboon
...


Use the formatting functions setiosflags(), setprecision() and setw() for the
printout
...
22
See the example code in the "Interchanging First Name and Surname" section
...
23
Create a loop which goes through all characters of the entered string and
checks if cEmailadr[i] == '@'
...

Exc
...

Exc
...
Save the positions of these characters
...
Then

decrease the character codes of the first characters by 32 in the first and
surnames
...
26
Change to:

cEncrypt[i] = cName[i] - 1;
Exc
...
28
Increase by 3 instead of decrease
...
29
Find out the code of a character and decrease by 65, so that A corresponds

to 0, B corresponds to 1 etc
...
The encrypted character
should then have the code 90-iCope, i
...
the code for 'Z' decreased by the
value of iCode
...
30
Insert all characters into one bit string array:
char cKey[63] = "ABCD…Zabcd…z0123…9";

Then create a random position in this array:
iPos = rand() % 63;

Download free eBooks at bookboon
...
31
Change to:

iLen = rand() % 5 + 6;
Exc
...
Change the limit of the first forloop to 52
...

if(cText[i]<97)


else

cEncrypt[i] = cKey[cText[i] - 65];

cEncrypt[i] = cKey[cText[i] - 71];

I joined MITAS because
I wanted real responsibili�
I joined MITAS because
I wanted real responsibili�

Real work
International
Internationa opportunities
al
�ree wo placements
work
or

�e Graduate Programme
for Engineers and Geoscientists

Maersk
...
discovermitas
...
com

233


for Engin

Click on the ad to read more

Structured Programming with C++

10 Answers

10
...
1
double dAvg(double x1, double x2, double x3)
{

double mv;

mv = (x1 + x2 + x3)/3;
}

return mv;

Exc
...

Exc
...

Exc
...
5
double dCirc(double dLen, double cWid)
{
}

return 2 * (dLen + dWid);

double dArea(double dLen, double dWid)
{
}

return dLen * dWid;

double dPrice(double l, double b)
{
}

return dCirc(l, b) * 145 + 650;

Exc
...


Download free eBooks at bookboon
...
7
Write a for-loop in the function which goes from 1 to n and prints c
...
8
Write a for-loop in the function which goes from 0 strlen(cWord)-1 and prints:
cout << cWord[i] << " ";
Exc
...

Exc
...
A switch statement

can then return the correct factor (0
...
07 or 0
...
Also use a default
section providing a en error message about "wrong customer category" and
returns 0
...
11
In main() you read the number of days, which is sent to the function

dayCost()
...


The difference between these values is returned to dayCost()
...
27
...
4 plus the fuel cost
...
12
Create a for-loop in the function which goes from 0 to strlen(cWord)-1 and

checks if strcat(cWord[i], cWord[i+1]) equals "aa"
...
In the same way you check the

characters "ae" and "oe"
...


Try to solve this problem without looking at the code proposal below:
void check (char s[])
{



int len=strlen(s);



for (int i=0; i


char p[3];

{

p[0]=s[i];

Download free eBooks at bookboon
...
ie
...
admissions@ie
...
Experience: 1 YEAR
Language: ENGLISH / SPANISH
Format: FULL-TIME
Intakes: SEPT / FEB

55 Nationalities

in class

Follow us on IE MIM Experience

Download free eBooks at bookboon
...
13
Change to:

if ((c>='0' && c<='9') || (c=='
...
14
if ((val>=2) && (val<=10))
cout << val;

else

switch val
{

case 1:

cout "Ace";
break;

case 11:

cout << "Jack";
break;

etc
...
15

Create another switch statement which tests the other parameter and prints the
correct colour of the card
...
16
In the functions odd() and divable() you use the modulus operator %
...

Exc
...
The three variables must be
of type int, char and int
...
The functions return int (+ - *) or double (/)
...

Exc
...
Use a

switch statement that compares the first character of the parameter against

the first character of "G", "VG", "MVG" and "IG"
...
In the loop you accumulate the score *

number of hours for each course
...

After the loop you divide the total score by the total number of hours
...
com

237

Structured Programming with C++

10 Answers

Exc
...
20
See the section 'Declaration - Definition'
...
21
See the section 'Project'
...
22
Use & after the data type, for instance:
double dayCost(int& iNo)
Exc
...
32)
Exc
...
These are accumulated in the loop
...

Exc
...

Exc
...

Exc
...

Exc
...

Exc
...
com

238

Structured Programming with C++

10 Answers

else

return n + nsum(n-1);

}

Exc
...
com

239

Click on the ad to read more

Structured Programming with C++

10 Answers

10
...
1
Add the statement:

cin
...
2
Change to:

while(infile
...
getline(cWhloc,8))
cout << cProd << "

" << cWhloc << endl;

Exc
...
Also write the warehouse location to the file with endl in between
...
4
Add:

cout << "
...
5
Change to:

while(infile >> iProdId >> dPrice >> iQty)
Add:

cout << "Stock quantity is " << iQty;
Exc
...
The sort function must have an additional parameter for the

warehouse location array
...

Exc
...
In
the file output statement you must also print the stock quantity to the file
...
com

240

Structured Programming with C++

10 Answers

Exc
...

You should modify it to print first name, surname and city
...

Exc
...

Exc
...
7)
...

Exc
...
The only

difference is that, when the name from the file equals the one entered by the
user, you don't print that name to the file
...
12
Start from the program in Exc
...
You will however need an additional two-dimensional array, so
that you have one for first names, one for surnames and one for cities
...

Exc
...

Exc
...
By means of a switch statement you can

perform the requested task
...


10
...
1
See the code example in the "Assigning Values to Pointers" section
...
2
See the code example in the sections "Addresses and char Pointers" and "cout
and char Pointers"
...
com

241

Structured Programming with C++

10 Answers

Exc
...
4
It should be possible to use the program in the section "Price Program with

Pointers" as the starting point
...

Exc
...

Exc
...
Then write a
for-loop which reads the values from the user
...

CLICK HERE

to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be

www
...
nl/feb/education
Download free eBooks at bookboon
...
Write another for-loop which prints the values
...

Exc
...
Declare a pointer (pSum) which
points to the sum variable
...
8
Delete the initiation lists for iSal and dTax
...
Don't

forget to increment the pointers with the ++ operator inside the loop
...
9
First, prepare the file by writing in Notepad each second salary and each

second tax percent
...
You might also need to take
a look in the Files chapter to be able to declare an instream correctly
...
10
First prepare the file like in the previous exercise
...

Exc
...
First read the product id from the

user
...
If so, the
corresponding price is printed:

for (int i=0; i{

if (*pEnteredProdId == *pProdId)

cout << "The price is: " << *pPrice;

pProdId++;
}

pPrice++;

Download free eBooks at bookboon
...
12
First reset the pointer to the beginning of the string and then print it in
the cout statement
...
13
Before sending the pointer to the function you can create a copy of the

string, so that the copy is not modified by the function
...

Exc
...
If so,
decrease it by 32
...

Exc
...
Create a local variable, iMax, in the function to which you assign

the value of the first item
...
If any item exceeds iMax, you set iMax equal to
that item
...


In the main() program you declare an array of 8 items and a pointer which

points to the first item of the array
...
Don't forget
to increment the pointer for each turn of the loop
...
Send the pointer and the number 8
...

Exc
...
Then

declare the array dynamicly
...
Don't forget to
release the dynamic memory with delete at the end of the program
...
17
You should in principle be able to copy some of the lines in the program and
accommodate them to the telephone numbers:
char cTeltemp[15];
char *cTel[iNo];

//Temporary storage of entered tel no

// Pointer array with telno:s

cout << "Telephone number " << i + 1 << " ";
Download free eBooks at bookboon
...
getline(cTeltemp, 15);

// Temporary storage

cTel[i] = new char[strlen(cTeltemp) + 1];
// Copy the telno to the pointer array:
strcpy(cTel[i], cTeltemp);
cout << cNames[j] << "

" << cTel[j] << endl;

delete [] cTel[k];
Exc
...
A similar check is inserted at each usage of the new keyword
...
8 Structures
Exc
...

Exc
...


American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:

▶▶ enroll by September 30th, 2014 and
▶▶ save up to 16% on the tuition!
▶▶ pay in 10 installments / 2 years
▶▶ Interactive Online education
▶▶ visit www
...
com to
find out more!

Note: LIGS University is not accredited by any
nationally recognized accrediting agency listed
by the US Secretary of Education
...

Download free eBooks at bookboon
...
3
See the section "Array with Structure Variables" where code examples are
given
...
4
Create a loop which goes through each customer and prompts the user for the
invoice total
...

Exc
...

Exc
...

Exc
...

Exc
...

Exc
...


Declare an outstream with ios::app
...

Exc
...

Exc
...

Exc
...
The input goes to a structure

which is printed on the screen
...


246


Title: Structured Programming with C++
Description: Structured Programming with C++