You are on page 1of 50

C++ Tutorials

for beginners and cheapskates

First C++ Program


Hello world: introducing function main()

C++ Basics
Types, identifiers and keywords

C++ Loops
Introducing iteration in C++

C++ Random Numbers


Introducing functions rand() and srand()

Simple C++ Program Example


Temperature Conversion

Pointers Part 1
An Introduction

By Bob Jacobs
Revised 5th May 2004
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

These tutorials were written by Bob Jacobs for the benefit of novice
programmers learning C++. Written in no particular order, they are the
first in what should eventually become a set of many tutorials.

The tutorials in this document don’t (and won’t) form a complete


introductory text on the C++ language; rather they focus on small
specific areas chosen almost at random. For a complete introductory
text you can’t do any better than investing in a good quality book.

If you wish to contact the author about these tutorials your comments would be welcome.
The latest update can be downloaded from http://www.robertjacobs.fsnet.co.uk or supplied
via email on request.

Bob Jacobs
bob@robertjacobs.fsnet.co.uk

2
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

Before You Start


Conventions, compiler issues and the ISO Standard

1. Introduction

This section describes the conventions adopted in the tutorials that follow. Please read this section
before you begin any of the tutorials. If the issues described below don’t mean anything to you then
you probably need to start with the First C++ Program tutorial.

Wherever possible the tutorials reflect the ISO C++ Standard. The example code should be portable
between platforms if you’re using a relatively up-to-date compiler.

2. Header files

All of the examples in the tutorials use the header files from the ISO C++ Standard. In other words I
use, for example:

<iostream> and <vector> rather than the older <iostream.h> or <vector.h>

also:

<cstdio> and <cstdlib> rather than the deprecated <stdio.h> and <stdlib.h>

If you’re not used to using the standard headers in your code now would be a good time to start. If
your C++ book uses the older headers consider buying a more up-to-date book. If you don’t yet own a
book keep this in mind when you choose one. If your compiler doesn’t have the new headers consider
upgrading your compiler. If your professor, lecturer or tutor teaches you to use the older headers make
a formal complaint and ask for your money back.

If you still prefer to use the older headers go right ahead. Just be aware that sometimes your program
may exhibit slightly different behaviour to that described.

3. Namespace std

All of my code examples qualify the use of entities from namespace std with a using directive:

using namespace std;

This is done for convenience to keep the body of the code clear so that the reader can focus on the
subject being described. Refer also to First C++ Program, section 7, for further discussion of
namespace std.

4. Returning from main()

The return statement in function main() is optional (it defaults to return 0). Some people prefer to
include it; I omit it in my code examples unless I return something other than 0, or I have multiple
returns from main(). Refer also to First C++ Program, section 5, for further discussion of returning from
main().

If your compiler won’t accept main() without a return statement, and some older compilers won’t, by
all means add one.

3
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

5. Viewing program output

There are some programming environments, for example running a console programme under
Microsoft Windows, in which the programme window will disappear when the program terminates,
preventing you from seeing the programme output. If your environment exhibits this behaviour you can
add the following line just before the end of function main():

cin.get();

or the following two lines in some cases:

cin.ignore(1000,’n’);
cin.get();

This should keep your programme output visible until the Enter key is pressed.

I’ve added cin.get() to the examples in the First C++ Program tutorial for the benefit of those novices
who are still at the very start of the learning curve and may struggle to understand what is going on
when their window disappears. Having described this within that tutorial, it’s not included in any others.

6. ISO C++ Standard

The C++ language and the C++ Standard Library are described in the ISO Standard, published in
1998:

ISO/IEC 14882:1998(E)

An electronic copy of the standard is available in Adobe PDF format (currently $18) from the ANSI
Electronic Standard Store:

http://webstore.ansi.org/AnsiDocStore/

The standard is a large document, describing the language and library in long and boring detail. Most
people don’t need a copy. However, I recommend that you buy a good reference book that describes
the language and library as defined by the standard in terms the average human (with a programming
aptitude) can understand. Perhaps the best known is Bjarne Stroustrup’s The C++ Programming
Language, Special Edition, published in hardback by Addison Wesley, ISBN 0-201-70073-5 (also
available in softback as the Third Edition). It’s not the easiest or best book for a complete novice to
learn from but it’s a good candidate for your second C++ book.

4
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

First C++ Program


Hello world: introducing function main()

1. Introduction

The tutorial is aimed at beginners. It assumes that you have a C++ compiler installed on your
computer so that you can run the code samples provided, and that you're at least familiar with using it
to create, compile and execute a C++ program. If you’re not able to do this yet you’ll need to refer to
the manual or help that comes with your compiler during the tutorial.

The code has been written to compile on any relatively modern C++ compiler that is close to the C++
standard. If it fails to compile, and you're sure your compiler is set up correctly (and you haven't made
any typing errors) you should consider getting a more up-to-date compiler.

I would encourage you to type in and run the examples provided so that you see the output. It will help
you to understand how the programs work.

We’ll start with the traditional 'hello world' program, then go on to discuss function main() in more detail
including command line arguments. We’ll also briefly consider C++ headers and namespace std,
which you'll need a basic understanding of in order to write your C++ programs.

2. Hello world

Here's the traditional first program for newcomers to C++, the 'Hello world' example. Create a new
source file using your IDE or text editor and type in the code below.

#include <iostream>
using namespace std;

int main()
{
cout << "Hello, world" << endl;

cin.get();
return 0;
}

If you compile and run this code, you will see the words "Hello, world" output.

3. Analysing the structure of the program

Let's take a look at the above program line by line. Firstly:

#include <iostream>

This is an include statement and tells the compiler to make the contents of the <iostream> header
available to the program. The input and output streams cin and cout, used in our program to read
keyboard input and output to the display screen, are defined in <iostream>. If you try to compile the
code without including this header it will fail to compile.

The header <iostream> is a standard library header and in common with all of the standard C++
headers its contents are in namespace std. There are several ways to qualify the contents of
namespace std. I've chosen to do so with a using directive:

using namespace std;

5
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

The other methods are introduced later. Once again, if you try to compile the code without including
this line it will fail to compile.

int main()

The above line is the start of the definition of function main(). All C++ programs must have a main()
function which is the entry point to the program. A typical C++ program in the real world will have
many functions. In our simple case, we can put all of our code into the one function, main().

The opening brace, above, marks the start of a code block. In this case it marks the start of function
main(). For every opening brace in a program there will be a corresponding closing brace marking the
end of the code block.

cout << "Hello, world" << endl;

This is where the real work is done in our simple program. Here the string "Hello, world" is output via
the output stream, cout. The endl manipulator outputs a newline and then flushes the stream. Because
cout is buffered, output may not be displayed when first written. Flushing the stream forces the
contents of the buffer to be output.

cin.get();

The line above causes the program to wait for input from the cin input stream. This may not be
required, however, there are some programming environments, for instance running a console
program in a Microsoft Windows environment, where the output may disappear before you've had an
opportunity to see it when the program completes. Adding this line of code will enable you to see the
output, and then press Enter to continue. If not required for your environment you can safely remove
the line from your program.

return 0;

This is the return statement. Because main() is defined as returning an integer, the above statement
will return a status to the calling process indicating normal program termination.

The closing brace, above, marks the end of function main().

4. More about main()

It was stated above that every C++ program must have a function main() as it's starting point. That's
not strictly true in all cases. If you're writing a C++ program to run on a freestanding environment, you
don't need to include function main(). Outside of that, which for many of us will be all of the time, your
program must have one.

The ISO C++ Standard tells us that the following two definitions of main() must be accepted by any
conforming C++ compiler:

int main()

int main(int argc, char *argv[])

The first definition is that same as that in our program.

The second definition takes two function parameters. The first contains the number of command line
arguments passed to our program by the calling process; the second is an array of command line
parameters.

6
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

Note that the C++ standard permits a compiler to accept definitions of main() with additional
parameters, but these will be implementation-specific and so won't generally be portable.

5. Returning from function main()

The first thing to note is that main() returns an integer. The integer value represents the status
returned to the calling process (the operating system).

Any integer value may be returned, but the only portable values are 0 and EXIT_SUCCESS,
representing normal termination, and EXIT_FAILURE, representing abnormal termination.
EXIT_SUCCESS and EXIT_FAILURE are defined in header <cstdlib>. Any other return values return
an implementation-defined status value to the calling process.

Note that some compilers will accept the following definition of main():

void main()

This is simply incorrect and shouldn't be used. There is no advantage in using this rather than one of
the two permitted definitions; if you're in the habit of using void main() you should drop it in favour of
int main().

What happens if we don't include a return statement? If the closing brace of function main() is
encountered without a return statement, the effect is as if a return 0 statement had been encountered,
that is, by default there is a return 0 implied, indicating normal termination. The following is perfectly
valid C++:

#include <iostream>
using namespace std;

int main()
{
cout << "Hello, world" << endl;

cin.get();
}

Note that some older compilers may not accept main() without a return statement, in which case you'll
need to add one.

6. Command Line Arguments

You can pass command line arguments to your program and access them by defining main() as
follows:

int main(int argc, char *argv[])

Here, argc holds the number of command line arguments and argv is an array of strings containing the
command line arguments. Don't worry if the syntax is unfamiliar to you at this stage.

The method of passing these arguments to the program is dependent on your programming
environment. If you run your program from the command line you can type in the command line
arguments when you run the program. If you run the program from within an IDE there should be an
option or setting that enables you to enter the command line arguments. Check the documentation
that comes with your IDE.

Let us try passing a command line argument to the program. Type in and run the following code.
When you run it, pass your first name as a command line argument (from the command line or
through your IDE options/settings).

#include <iostream>

7
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

#include <cstdlib>

using namespace std;

int main(int argc, char *argv[])


{
if(argc != 2){
cout << "Invalid number of command line arguments." << endl;
cin.get();
return EXIT_FAILURE;
}

cout << "Hello, my name is " << argv[1] << endl;


cin.get();
return EXIT_SUCCESS;
}

When I run this as hello.exe and enter Bob on the command line (e.g. hello.exe Bob) it produces the
following output:

Hello, my name is Bob

The first thing our program does is check that there are two arguments. The first is the name used to
invoke the program and may include the path name. The second is your first name. If our program
doesn't find two arguments (if you forgot to add your name or if you entered more than one name) it
outputs an error message and terminates the program.

If there are two command line arguments the program uses the second, which is your first name, and
outputs it.

Note that because the program has more than one exit point I've chosen to include the return
statement at the end of main. I've also use EXIT_SUCCESS and EXIT_FAILURE as return values,
and have included the header <cstdlib> accordingly.

The code below will output all of the command line arguments that we enter. Try it, and see what the
output is like when you enter more arguments, and also when you enter none.

#include <iostream>
#include <cstdlib>

using namespace std;

int main(int argc, char *argv[])


{
for(int index=0; index < argc; index++){
cout << argv[index] << endl;
}
cin.get();
return 0;
}

7. Namespace std

As mentioned earlier, when we include headers from the C++ standard library the contents are in
namespace std. There are three ways to qualify their use so that we can use them in our program:

(a) A using directive:

using namespace std;

This is the method we used earlier and is the simplest but it has the disadvantage that it pollutes the
global namespace because it makes all of the identifiers from namespace std available globally.

8
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

(b) A using declaration:

using std::cout;

This is clearly more limited and has to be repeated for everything we wish to qualify, so if we apply this
to our first example instead of a using directive the program would be written:

#include <iostream>

using std::cout;
using std::endl;
using std::cin;

int main()
{
cout << "Hello, world" << endl;

cin.get();
return 0;
}

(c) Explicit identifier:

std::cin.get();

Here an explicit identifier is used as a prefix for each use. Our first program would then be written:

#include <iostream>

int main()
{
std::cout << "Hello, world" << std::endl;

std::cin.get();
return 0;
}

For the sake of clarity you will often find that tutorials, which tend to show small pieces of code to
demonstrate the subject under discussion, may use a using directive even though in general this is
discouraged for the reason given above.

8. C++ Headers

We've used two headers from the C++ standard library in our discussion so far. As you progress
further with your programming and write more sophisticated code you will need to include other
headers as appropriate. This means you will need to know what is included in each header so that you
can include it in your program. If you fail to include the correct headers your program won't compile.

The C++ library includes headers from the C standard library. These have names such as:

<stdlib.h>, <string.h>, <time.h>

You can use these headers in your C++ programs but be aware that the contents are not in
namespace std, they're in the global namespace. Use of these older C headers is deprecated in C++;
you can use them but they may disappear from the standard at some time in the future.

C++ provides its own versions of these headers whose contents are in namespace std. The equivalent
headers for the above are:

<cstdlib>, <cstring>, <ctime>

9
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

As you can see, these drop the '.h' suffix and have a 'c' prefix. You should use these newer versions in
your programs rather than the older C headers unless you're maintaining old code which used them.

C++ also introduces a number of headers that didn't exist in C, such as:

<iostream>, <vector>, <algorithm>

As with the other C++ headers, they don't use a '.h' extension, but they don't have a prefix.

You will come across older versions of the C++ headers, pre-dating the standard. These will have
names such as:

<iostream.h>, <fstream.h>

instead of:

<iostream>, <fstream>

Note that these older versions are not addressed by the C++ standard at all. They're not deprecated,
they're not C headers and they're not part of the C++ standard. They're simply old headers that pre-
date the standard and a great deal of code has been written using them over the years. Generally you
should prefer the use of the C++ headers from the standard library rather than these older versions
unless you're maintaining old code, but compilers are likely to continue to provide both versions for
some time to come for backwards compatibility.

Finally, a common source of confusion for novice C++ programmers is which header to include for
strings. There are three string headers to consider, the first two:

<string.h>, <cstring>

are for C-style strings (null-terminated character arrays). These contain the string functions such as
strcpy(), strcat() and strlen(). The former is the deprecated C library header, the latter is the more
recent C++ header.

The third string header is:

<string>

and this is used for std::string class in C++.

9. Conclusion

This concludes the tutorial. You should now understand how to write a simple C++ program that
conforms with the C++ standard, which means that you should be able to compile it on any modern
C++ compiler. In the course of the tutorial you have been introduced to some of the features of a C++
program, function main() including command line arguments, C++ headers, and namespace std.

This tutorial is a basic introduction to the above topics and out of necessity it omits some of the finer
details. It should help you to understand some of the things you'll need to be aware of as you progress
with more sophisticated programs.

10
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

C++ Basics
Types, identifiers and keywords

1. Introduction

This tutorial provides a brief introduction to C++ types, identifiers, and keywords.

2. What is a type?

When we wish to store data in a C++ program, such as a whole number or a character, we have to tell
the compiler which type of data we want to store. The type will have characteristics such as the range
of values that can be stored and the operations that can be performed on variables of that type.

3. Fundamental types

C++ provides the following fundamental built-in types: Boolean, character, integer and floating-point. It
also enables us to create our own user-defined types using enumerations and classes.

For each of the fundamental types the range of values and the operations that can be performed on
variables of that type are determined by the compiler. Each compiler should provide the same
operations for a particular type but the range of values may vary between different compilers.

4. Boolean

The Boolean type can have the value true or false. For example:

bool isEven = false;


bool keyFound = true;

If a Boolean value is converted to an integer value true becomes 1 and false becomes 0.

If an integer value is converted to a Boolean value 0 becomes false and non-zero becomes true.

5. Character

The character type is used to store letters, digits and symbols (typically ASCII characters but not
always). For example:

char menuSelection = 'q';


char userInput = '3';
char percentSymbol = '%';

Note how a character is enclosed within single quotes. We can also assign numeric values to
character variables:

char chNumber = 26;

We can declare signed and unsigned characters, where signed characters can have positive and
negative values or zero, and unsigned characters can only contain positive values or zero.

signed char myChar = 100;


signed char newChar = -43;
unsigned char yourChar = 200;

Note that if we use a plain char, neither signed nor unsigned:

11
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

char dataValue = 27;

it may differ between compilers as to whether it behaves as a signed or unsigned character. On some
compilers it may accept positive and negative values or zero, on others it may only accept positive
values or zero. Refer to your compiler documentation to see which applies.

The size of char is always one byte, which is guaranteed to be at least 8 bits. C++ also provides the
type wchar_t, a wide character type typically used for large character sets.

An array of characters can be used to contain a C-style string in C++. For example:

char aString[] = "This is a C-style string";

Note that C++ also provides a string class that has advantages over the use of character arrays.

6. Integer

The integer type is used for storing whole numbers. We can use signed, unsigned or plain integer
values as follows:

signed int index = 4198;


signed int temperature = -32;
unsigned int count = 0;
int height = 100;
int balance = -67;

Like characters, signed integers can hold positive or negative values or zero, and unsigned integers
can hold only positive values or zero. However, plain integer can always hold positive or negative
values or zero, they're always signed.

You can declare signed and unsigned integer values in a shortened form, without the int keyword:

signed index = 4198;


unsigned count = 0;

Integer values come in three sizes, plain int, short int and long int.

int normal = 1000;


short int smallValue = 100;
long int bigValue = 10000;

The range of values for these types will be defined by your compiler. Typically a plain int can hold a
greater range than a short int, a long int can hold a greater range than a plain int, although this may
not always be true. What we can be sure of is that plain int will be at least as big as short int and may
be greater, and long int will be at least as big as plain int and may be greater. A short integer is
guaranteed to be at least 16 bits and a long integer at least 32 bits.

You can declare short and long integer values in a shortened form, without the int keyword:

short smallValue = 100;


long bigValue = 10000;

You can have long and short signed and unsigned integers, for example:

unsigned long bigPositiveValue = 12345;


signed short = -7;

12
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

7. Floating-Point

Floating point types can contain decimal numbers, for example 1.23, -.087. There are three sizes, float
(single-precision), double (double-precision) and long double (extended-precision). Some examples:

float celsius = 37.623;


double fahrenheit = 98.415;
long double accountBalance = 1897.23;

The range of values that can be stored in each of these is defined by your compiler. Typically double
will hold a greater range than float and long double will hold a greater range than double but this may
not always be true. However, we can be sure that double will be at least as great as float and may be
greater, and long double will be at least as great as double and may be greater.

8. Enumeration

An enumeration is a user defined type that enables the user to define the range of values for the type.
Named constants are used to represent the values of an enumeration, for example:

enum weekday {monday,tuesday,wednesday,thursday,friday,saturday,sunday};


weekday currentDay = wednesday;
if(currentDay==tuesday){
// do something
}

The default values assigned to the enumeration constants are zero-based, so in our example above
monday == 0, tuesday == 1, and so on.

The user can assign a different value to one or more of the enumeration constants, and subsequent
values that are not assigned a value will be incremented. For example:

enum fruit {apple=3, banana=7, orange, kiwi};

Here, orange will have the value 8 and kiwi 9.

9. Class

A class enables us to create sophisticated user defined types. We provide data items for the class and
the operations that can be performed on the data. For example, to create a square class that has a
data item for size, and provides draw and resize operations:

class square {
public:
square();
~square();
void draw();
bool resize(int newSize);
private:
int size;
};

[Please refer to a tutorial on classes and objects for a more detailed explanation of classes, which is
outside the scope of this tutorial].

10. C++ Identifiers and Keywords

In C++ we provide names for the entities we create, the variables, functions and types in our
programs. These names, or identifiers, are required to conform to some simple rules.

13
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

An identifier must start with a letter and is composed of a sequence of letters and digits. Somewhat
surprisingly, in this context the underscore _ is considered to be a letter (although there are conditions
associated with its use). There's no restriction on the length of an identifier.

Identifiers beginning with an underscore followed by an upper case letter are reserved for use by the
implementation, as are identifiers containing two consecutive underscores, so to avoid problems you
should refrain from using them for your own identifiers.

You can't use an identifier that is a C++ keyword in your programs. Keywords are:

and, and_eq, asm, auto, bitand, bitor, bool, break, case, catch, char, class,
compl, const, const_cast, continue, default, delete, do, double,
dynamic_cast, else, enum, explicit, export, extern, false, float, for,
friend, goto, if, inline, int, long, mutable, namespace, new, not, not_eq,
operator, or, or_eq, private, protected, public, register, reinterpret_cast,
return, short, signed, sizeof, static, static_cast, struct, switch, template,
this, throw, true, try, typedef, typeid, typename, union, unsigned, using,
virtual, void, volatile, wchar_t, while, xor, xor_eq.

You should also try to avoid using names from the C++ library, e.g. swap, max.

C++ is case sensitive, so upper case and lower case characters are distinct. This means that the
names userInput and userinput are recognised as two different identifiers.

Examples of acceptable identifiers are:

calculate_height, readWindSpeed, channel42, foo

Examples of unacceptable identifiers:

calculate height, delete, 2letters, _HELLO_

11. Hints and Tips

Use meaningful descriptive names to make your code more easily understood,
e.g. int height rather than int h, char menuSelection rather then char ch, int patient_age rather than int
number.

Avoid names that differ only in capitalisation


e.g. height, Height.

Avoid using names that are keywords but with different capitalisation
e.g. Return, Continue.

Try to maintain a consistent style. Examples are:

- Capitalising all words except the first,


e.g. readInUserData(), getMaximumSpeed().

- Using underscore to separate words,


e.g. read_in_user_data(), get_maximum_speed().

- Using a type identifier prefix,


e.g. int nGetSomeIntegerValue, char szDataString[].

12. Conclusion

This concludes the tutorial.

14
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

C++ Loops
Introducing iteration in C++

1. Introduction

This tutorial explains how to use loop structures in C++. In it I cover:

goto
for loops
while loops
do-while loops
continue
break

The tutorial is aimed at beginners. It assumes that you have a C++ compiler installed on your
computer so that you can run the code samples provided, and that you're familiar with using your
compiler. The code has been written to compile on any relatively modern C++ compiler that is close to
the C++ standard. If it fails to compile, and you're sure your compiler is set up correctly (and you
haven't made any typing errors) you should consider getting a more up-to-date compiler.

I would encourage you to type in and run the examples provided so that you see the output. It will help
you to understand how the loops work.

2. What is a loop?

When we talk about loops we're talking about a code structure that executes a piece of code either
none, one or multiple times depending on a condition.

Sometimes we know in advance how many times we wish to execute a piece of code, it's fixed. Other
times we might not know how many times to run it in advance, but we know under what condition the
loop should terminate. A condition will determine whether the code within a loop is executed none,
one or multiple times. Sometimes we know that the code will always execute at least once, possibly
multiple times (but not none). Another possibility is that we wish to execute a loop endlessly, known
as an infinite loop. Each of these will be covered.

3. Iteration using goto

The goto statement was once widely used. Unfortunately code that used goto extensively was poorly
structured and could easily become unmanageable, and is known as "spaghetti code". Today,
programming languages provide other ways to structure code so goto is rarely needed. In C++ it is
always possible to use something other than goto to achieve what you need. However, using goto for
loops is included here for completeness.

Note that the use of goto is a religious issue and has provoked a great deal of debate. In C++ there is
always a better alternative for writing loops, so you needn't use goto at all. There are other
circumstances where goto may be more appropriate than the alternatives and I leave it to you to
decide whether to use it in those cases.

To loop using goto we simply need a goto statement that identifies where the execution of the program
should jump from and a label that identifies where the execution of the program should jump to. Here's
a simple example:

#include <iostream>

using namespace std;

15
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

int main()
{
cout << "Starting the program." << endl;
start:
cout << "Hello, world!" << endl;
goto start;

cout << "Program finished." << endl;


}

The program will begin by writing out, "Starting the program." Next it will output "Hello, world!".
Because it now encounters the goto statement execution will jump to the 'start' label and continue from
there, so it will write out "Hello, world!" once again. This will repeat endlessly; each time the program
reaches the goto statement it will jump to the 'start' label, causing it to repeatedly output the text,
"Hello, world!".

Because there is no way for the program to go beyond the goto statement, the text "Program finished."
will never be reached; our program will repeat in an infinite loop - until we stop the program from
running some other way.

Let's consider something a little more useful (if only slightly). For the next example using goto we'll
write out all of the squares for numbers from 1 to 10. This time we'll need to use a condition to
determine whether to loop back or not.

#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
cout << "Starting the program." << endl;

int counter = 1;
start:
cout << setw(3) << counter << setw(4) << counter * counter << endl;
if(counter<10){
counter++;
goto start;
}

cout << "Program finished." << endl;


}

Unlike our previous example this is not an infinite loop. The goto statement will only be executed if the
value of counter is less than 10. Once counter reaches 10 the program will continue past the goto and
output "Program finished." before terminating. I've used the manipulator setw() here to format the
output to look neater on the screen.

In the last example we knew in advance how many times we wanted to loop. The next example will
show how to loop until a condition is met, without knowing in advance how many times we want to
loop.

#include <iostream>
#include <string>

using namespace std;

int main()
{
cout << "Starting the program." << endl;

string userInput;
start:
cout << "Enter a string, or 0 to quit: "<< flush;

16
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

cin >> userInput;


if(userInput == "0"){
goto finish;
}else{
cout << "You entered: " << userInput << endl;
goto start;
}

finish:
cout << "Program finished." << endl;
}

We've used two labels here, one to identify where we want the program execution to jump to in order
to repeat the loop, and one to identify where we want the program to jump to when we terminate the
loop. Even with this simple example, we can already see that the use of multiple goto statements and
labels begins to obscure the flow of the program. Fortunately, there are better ways to write loops in
C++.

4. For loops

The for loop is commonly used in C++ programs. The classic use of a for loop is when a variable,
often a counter of some sort, is set to a value prior to looping, incremented during the loop, and the
loop terminates when the counter reaches a particular value.

Let's revisit the program we wrote using goto that wrote out squares of numbers from 1 to 10, this time
using a for loop:

#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
cout << "Starting the program." << endl;

for(int counter=1; counter <=10; counter++){


cout << setw(3) << counter << setw(4) << counter*counter << endl;
}

cout << "Program finished." << endl;


}

The structure of the for loop is as follows:

for(expression1; expression2; expression3){


statement(s);
}

In our program we have:

for(int counter=1; counter <=10; counter++){


cout << setw(3) << counter << setw(4) << counter*counter << endl;
}

The first expression:

int counter=1;

is evaluated once only, on entering the loop. We typically initialise one or more values. In our program
we declare a new variable here, an integer named counter, and initialise it with a value of 1.

17
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

The second expression:

counter<=10;

is evaluated at the start of each iteration of the loop, including the first iteration. We typically use an
expression that identifies the condition for which the loop will iterate. In our program we have added
the condition counter <=10. This means that the loop will repeat each time the condition is tested if the
value of counter is less than or equal to 10. As soon as the condition becomes false, in other words
counter reaches a value greater than 10, the loop will terminate.

The third expression:

counter++;

is evaluated at the end of each iteration of the loop. We typically use an expression that modifies the
value of a variable that is used in the loop condition, in this case our counter variable. In our program
we increment counter by one each time the loop is executed.

For each iteration through the loop the statements between the enclosing braces are executed. In our
program this is the output statement for counter and counter squared:

cout << setw(3) << counter << setw(4) << counter * counter << endl;

It's common to see several, perhaps many, statements here.

Working through our for program then, we have the following:

The message "Starting the program." Is output. Next, we reach the for loop and the variable counter is
created and initialised to a value of 1. Then the second expression is evaluated, counter<=10, which
evaluates to true (the value of counter is 1 which is less than 10). The statement inside the braces is
executed, which outputs the number 1 and it's square, also 1, followed by a newline. Then we reach
the bottom of the loop and the third expression is evaluated, which increments the value of counter to
2.

Next, execution returns to the top of the loop and the second expression is evaluated once more,
counter<=10, which evaluates to true (2 is less than 10). The program executes the statement within
the loop, which outputs the number 2 and it's square, 4, followed by a newline. Again we reach the
bottom of the loop and the third expression is evaluated, which increments the value of counter to 3.

The second expression is evaluated again, counter<=10, which evaluates to true (3 is less than 10).
This sequence repeats until, having reached the bottom of the loop, expression 3 is evaluated and
increments the value of counter to 11. We return to the top of the loop and the second expression is
evaluated, counter<=10, which now evaluates to false as 11 is greater than 10.

Execution now continues with the statement following the closing brace, which outputs "Program
finished.".

From the above we can see that the program will output each number and it's square in turn, for all
values from 1 to 10 inclusive.

We'll look at for loops again later, but having covered the classic for loop, we'll move on to while loops.

5. While loops

The while loop can be used as a direct replacement for the for loop. The structure of a while loop is as
follows:

while(expression){
statement(s);

18
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

Unlike the for loop, where all of the expressions that initialise, control and terminate the loop are
declared in one place, in a while loop we have to add them at the appropriate point. Here's our
previous example reworked as a while loop:

#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
cout << "Starting the program." << endl;

int counter = 1;
while(counter <=10){
cout << setw(3) << counter << setw(4) << counter*counter << endl;
counter++;
}

cout << "Program finished." << endl;


}

The program flow is as follows:

The program starts by writing out the message "Starting the program.". Next the variable counter is
initialised with a value of 1. Then the while loop is reached and the expression is evaluated. The
expression evaluates to true (1 is less than 10) so the statements within the loop are executed. The
first statement outputs the number 1 and it's square (also 1) followed by a newline. The next
statement increments the value of counter, in this case to 2. The bottom of the loop is reached.

Execution continues at the top of the loop with the evaluation of the expression. This evaluates to true
(2 is less than 10) so the statements are executed once more. This sequence repeats until the value
of counter is incremented to 11.

The expression evaluates to false (11 is greater than 10). Execution continues with the statement
following the closing brace. The message "Program finished." is output.

A while loop is useful when we don't know in advance precisely how many iterations we require,
instead relying on a terminating condition being met. Take a look at the following example, where we
revisit the program we wrote earlier using goto:

#include <iostream>
#include <string>

using namespace std;

int main()
{
cout << "Starting the program." << endl;

string userInput = "";


while(userInput != "0"){
cout << "Enter a string, or 0 to quit: "<< flush;
cin >> userInput;
}

cout << "Program finished." << endl;


}

This is much easier to follow than the equivalent example using goto.

19
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

We start with our "Starting the program." message. Next the userInput string is initialised with an
empty string. Then the while loop expression is evaluated. In this case it evaluates to true, as
userInput does not contain the string "0" (zero). The statements inside the while loop are executed,
first prompting the user to input a string and then storing the string in userInput.

Now the while loop expression is evaluated again. If the userInput contains the string "0", the while
loop will terminate and execution will continue with the statement following the closing brace, which
outputs the "Program finished." message. If userInput contains any other string the while loop
statements will be executed once more.

The sequence will repeat until userInput contains "0". Try it for yourself and you'll see how flexible this
is. You may choose to enter "0" the first time through the loop, or you may choose to enter any
number of other strings before you terminate the program. The precise number of iterations depends
on the user input, but the terminating condition is clearly defined.

6. Do-while loops

The do-while loop structure is shown below:

do {
statement(s);
} while(expression);

Notice the semicolon at the end.

The similarity with the while loop is obvious. The important difference is that the expression is
evaluated at the bottom of the loop, which means that the statements within the loop will always be
executed at least once, unlike the for loop and while loop.

#include <iostream>
#include <string>

using namespace std;

int main()
{
cout << "Starting the program." << endl;

string userInput;
do {
cout << "Enter a string, or 0 to quit: " << flush;
cin >> userInput;
}while(userInput != "0");

cout << "Program finished." << endl;


}

7. Using break

The break statement, when it occurs within a for loop, a while loop, or do-while loop, causes the loop
to terminate immediately and program execution continues with the statement following the closing
brace.

The example below is a modified version of a while loop we saw earlier. In the previous example the
loop was terminated when the userInput string value was "0". In this version we've added a counter
and an if statement that tests the value of the counter. If the value of counter reaches 5 the break
statement is executed. This will cause the program execution to jump to the statement following the
while loop, outputting the "Program finished." message.

20
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

There are now two ways to terminate this loop; the user can choose to terminate it by entering "0" or
the loop will terminate when the value of counter reaches 5, limiting the number of strings that the user
can input.

#include <iostream>
#include <string>

using namespace std;

int main()
{
cout << "Starting the program." << endl;

string userInput = "";


counter = 0;
while(userInput != "0"){
cout << "Enter a string, or 0 to quit: "<< flush;
cin >> userInput;
if(counter==5){
break;
}
counter++;
}

cout << "Program finished." << endl;


}

8. Using continue

The continue statement, when it occurs within a for loop, a while loop, or a do-while loop, causes the
program execution to jump to the bottom of the loop. None of the statements between the continue
statement and the bottom of the loop are executed. The loop then continues as normal.

The example below shows a continue statement used in conjunction with a for loop:

#include <iostream>

using namespace std;

int main()
{
cout << "Starting the program." << endl;

for(int counter=1; counter<=10; counter++){


if(counter==5){
continue;
}
cout << counter << endl;
}

cout << "Program finished." << endl;


}

The for loop will iterate 10 times, with counter values from 1 to 10. Each iteration the value of counter
is compared with 5; if it's not equal to 5 the line that follows will be executed, which will output the
value of counter. If the value of counter is 5 the continue statement is executed, which jumps to the
end of the loop without executing the output statement, and continues with the next iteration.

The program output is therefore numbers 1 to 4 and 6 to 10.

9. Infinite loops

An infinite loop is one in which the condition will always be true. A simple example, using a while loop:

21
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

#include <iostream>
#include <string>

using namespace std;

int main()
{
cout << "Starting the program." << endl;

string userInput;
while(true){
cout << "Enter a string: " << flush;
cin >> userInput;
}

cout << "Program finished." << endl;


}

As you can see, the while loop expression will always be true (we use the Boolean value true), so the
loop will continue endlessly. Of course, we could use a break statement to terminate the loop much as
we did before, in this case when the string "quit" is entered:

#include <iostream>
#include <string>

using namespace std;

int main()
{
cout << "Starting the program." << endl;

string userInput;
while(true){
cout << "Enter a string or quit to terminate: " << flush;
cin >> userInput;
if(userInput=="quit"){
break;
}
}

cout << "Program finished." << endl;


}

A do-while loop will work the same way if we use true as the expression. A for loop can be used as an
infinite loop like this:

#include <iostream>
#include <string>

using namespace std;

int main()
{
cout << "Starting the program." << endl;

string userInput;
for(;;){
cout << "Enter a string: " << flush;
cin >> userInput;
}

cout << "Program finished." << endl;


}

22
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

Notice how there is no expression at all in the for loop statement. In fact any or all of the expressions
can be empty, but the semicolons are still required. As before we can use the break statement to
terminate the loop:

#include <iostream>
#include <string>

using namespace std;

int main()
{
cout << "Starting the program." << endl;

string userInput;
for(;;){
cout << "Enter a string or quit to terminate: " << flush;
cin >> userInput;
if(userInput=="quit"){
break;
}
}

cout << "Program finished." << endl;


}

10. Nested loops

Loops can be nested, you can have a loop within a loop. That includes while loops nested within for
loops, do-while loops nested within while loops, or several levels of nesting of one type of loop; any
combination you like in fact. Here's an example of a program with a nested loop, an implementation of
the infamous bubble sort. A bubble sort is one of the simplest (and least efficient) sorting algorithms.

#include <algorithm>
#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
// create an array of unsorted integers
int myArray[10] = {8,21,3,92,56,130,312,228,18,45};

// display the array contents


for(int index=0; index<10; index++){
cout << setw(4) << myArray[index];
}
cout << endl;

// loop through the array for as many times as there


// are elements
for(int outer=0; outer<10; outer++){
// loop through each element in the array in turn
for(int inner=1; inner<10; inner++){
// compare each element with the one below it
if(myArray[inner-1] > myArray[inner]){
// swap them if they're not in the correct order
swap(myArray[inner-1], myArray[inner]);
}
}
}

// display the sorted array contents


for(int index=0; index<10; index++){
cout << setw(4) << myArray[index];
}

23
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

Don't be put off if you don't understand the whole program; the comments should help you to
understand what it going on. Notice how, in the middle of the program, there is a for loop nested inside
another for loop. Structures such as this are not uncommon. Understandably, if you're nesting loops in
this way make sure you use indentation to make it easy for the reader to follow.

In some cases you may come across programs with several levels of nesting.

11. Miscellaneous Issues

11.1 Do you need enclosing braces?

All of the examples shown have used braces for the statements within the loop. Strictly speaking you
only need the enclosing braces if the loop contains multiple statements (2 or more). If there is only a
single statement the braces are not required; the following is perfectly valid code:

#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
cout << "Starting the program." << endl;

for(int counter=1; counter <=10; counter++)


cout << setw(3) << counter << setw(4) << counter*counter << endl;

cout << "Program finished." << endl;


}

So should you include the enclosing braces for a single line statement? It's really a question of
personal preference, though some would argue that it adds clarity to include the braces for all cases.

11.2 Where should I place the enclosing braces?

Just about the single most important thing about your own coding style is consistency. If you're always
consistent in the way you write your code it helps other people to make sense of it. If that's not enough
of a reason, it also helps you to make sense of it yourself if you come back to it six months after you
first wrote it.

Just as it's a matter of personal taste as to whether to include the enclosing braces when a loop
contains a single statement, so it is with where you place the braces.

In my examples I place the opening brace at the end of the line in which the for, while, or do occurs. I
also place the closing brace directly below the start of the for, while or do, as shown in the nested loop
example (shown here with comments removed):

for(int outer=0; outer<10; outer++){


for(int inner=1; inner<10; inner++){
if(myArray[inner-1] > myArray[inner]){
swap(myArray[inner-1], myArray[inner]);
}
}
}

Some people prefer to place the braces differently, for example the opening brace is placed on the
next line, directly below the for, do or while:

for(int outer=0; outer<10; outer++)


{

24
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

for(int inner=1; inner<10; inner++)


{
if(myArray[inner-1] > myArray[inner])
{
swap(myArray[inner-1], myArray[inner]);
}
}
}

There are other variations on the same theme, and I won't complicate matters by demonstrating more.
Let me simply say once more, it's a matter of personal preference and consistency is important.

11.3 For loop variable scope

I didn't mention it earlier, but you should be aware of the scope of variables declared in a for loop. In
an earlier example we declared the integer variable counter in the first expression of the for loop
statement thus:

for(int counter=1; counter <=10; counter++)

When we do this, the scope of the variable is restricted to the loop; it won't be accessible outside of
the loop:

for(int counter=1; counter <=10; counter++){


cout << setw(3) << counter << setw(4) << counter*counter << endl;
}
counter++; // <-- invalid, counter out of scope

You should also be aware that prior to the C++ standard this wasn't the case. You might find your
compiler doesn't correctly implement this yet, although many do. Go ahead, try it.

If you take another look at the nested loop example you'll see that in the first for loop we declare an
integer variable named index and use that as a counter within the loop. You'll notice that we used the
same name again in the last loop, and declared the variable again. We had to declare it again as it is
unknown outside of the first loop, so if we had written the last loop like this:

// display the sorted array contents


for(index=0; index<10; index++){
cout << setw(4) << myArray[index];
}

it would have resulted in a compilation error (in a compiler that conforms to the C++ standard). Of
course we could have just chosen a different name.

If you want to use the variable after the loop has terminated you need to declare it outside of the loop
so that it remains within scope:

int number;
for(number=1; number<=10; number++){
cout << setw(3) << number << setw(4) << number * number << endl;
}
number = someothernumber; // <-- valid, number is still in scope

11.4 Should I use counter++ or ++counter?

If we take another look at our classic for loop we had:

for(int counter=1; counter<=10; counter++){

Some people suggest that the following should be preferred:

for(int counter=1; counter <=10; ++counter){

25
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

In the case of built in types such as integers there is unlikely to be a noticeable difference, however,
with user defined types (e.g. classes) the former may be less efficient due to the creation of temporary
variables (a topic beyond the scope of this tutorial). For this reason you may prefer to get into the habit
of using the latter style.

11.5 What can possibly go wrong?

A relatively common error made by novices is to add a semicolon to the end of a loop statement, for
example:

for(number=1; number<=10; number++)


cout << setw(3) << number << setw(4) << number * number << endl;

The code above is correct, but now let's add that extra semicolon:

for(number=1; number<=10; number++);


cout << setw(3) << number << setw(4) << number * number << endl;

Hardly noticeable is it? In the former the loop iterates 10 times and with each iteration it outputs the
value of number and number squared. In the latter the loop iterates 10 times but does not output
anything until after the loop has terminated. It then outputs number and number squared just once,
and the value of number will be 11, the value that caused number<=10 to evaluate false).

Another relatively common error is to use an erroneous expression that prevents the code within the
loop being executed, for example:

// display the sorted array contents


for(index=0; index>10; index++){
cout << setw(4) << myArray[index];
}

That looks harmless enough, doesn't it? But if you look closely we can see that the second expression
is incorrect; instead of executing when the value of index is less than 10 it only executes when the
value is greater than 10. The value of index is initialised to 0 when the loop is entered, then the
expression index > 10 is evaluated, which evaluates to false, so the loop terminates without executing
the statements within the enclosing braces at all.

12. Which loop should I use?

The simple answer, whichever one you want to - but avoid writing loops using goto.

You can use a while loop for all cases that we've mentioned, that is, when the number of iterations is
known in advance, when the number of iterations is unknown and dependent on some condition being
met, when the loop may iterate none, one or more times, or when the loop must undergo at least one
iteration.

A for loop has all of it's expressions in one place at the start of the loop which can aid readability and
understanding, particularly with deeply nested loops. (Remember, most code is read far more often
than it's written). It also provides a compact structure and a mechanism for introducing a variable with
scope limited to the loop.

A do-while loop seems a natural choice when you know the loop must undergo at least one iteration.

You may come across debate in public forums about which is better, which is more appropriate for
particular circumstances, which is most efficient. Much of the time it won't matter which you use as
long as the program behaviour is correct.

Learn how to use each of them, and use them as you see fit.

26
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

13. Conclusion

This concludes the tutorial. You should now understand how to use loops in a C++ program to perform
iteration.

27
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

C++ Random Numbers


Introducing the functions srand() and rand()

1. Introduction

The C++ standard library provides a facility for generating random numbers using the function rand().
Of course, these numbers aren't truly random. They're pseudo random numbers. They're generated in
a sequence that gives the illusion of being random but the sequence will eventually repeat.

So is rand() useless? Not at all. All random number generator programs have limitations and some are
better than others. The version of rand() that comes with your C++ compiler will in all probability be a
pretty simple generator and wouldn't be appropriate for scientific use but it can still be used for some
purposes. It may well be random enough for use in simple programs and games. If you want
something a little better, you'll have to look beyond the C++ standard library but for now we'll concern
ourselves with the functions C++ provides.

We'll look first at the rand() function itself, then discuss RAND_MAX, followed by the srand() function,
and finally we will see how to use rand() to generate pseudo random numbers in a specified range. All
of the example code provided has been written to be portable and should compile successfully on
modern compilers that support the C++ standard.

2. How do I generate random numbers in C++?

To use rand() we need to include the appropriate header in our program, <cstdlib>. The function
rand() simply returns a pseudo random integer in the range 0 to RAND_MAX. We use it like this:

#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
int random_integer = rand();
cout << random_integer << endl;
}

To generate more random numbers we simply call rand() repeatedly:

#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
int random_integer;
for(int index=0; index<10; index++){
random_integer = rand();
cout << random_integer << endl;
}
}

3. How large a number will rand() generate?

The value of RAND_MAX isn't specified by the C++ standard, it's implementation defined, however we
can rely on the value of RAND_MAX being at least 32767.

28
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

To find out the value of RAND_MAX on your compiler run the following code:

#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
cout << "The value of RAND_MAX is " << RAND_MAX << endl;
}

4. Why do I need srand()?

The function srand() is used to initialise the pseudo random number generator. This sets the starting
point for the sequence of generated numbers. We only need to initialise the pseudo random number
generator once, before our first call to rand().

#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
int seed = 5;
srand(seed);
int random_integer;
for(int index=0; index<10; index++){
random_integer = rand();
cout << random_integer << endl;
}
}

If we initialise the pseudo random number generator with the same seed value each time we run the
program, as shown above, it will always output exactly the same numbers. This is inadequate for most
needs, after all we want to produce numbers that appear to be random. (An exception to this might be
when we wish to debug our code, using a repeatable sequence of numbers).

The solution is to use a different seed value each time we run the program. A common means of
achieving this is to seed the pseudo random number generator with the current time. Because this is
likely to be different each time we run the program the sequence of numbers generated will be
different:

#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;

int main()
{
srand(static_cast<unsigned>(time(0)));
int random_integer;
for(int index=0; index<10; index++){
random_integer = rand();
cout << random_integer << endl;
}
}

Notice that we included the header <ctime> for the time() function. The value returned by time() is cast
to unsigned integer using static_cast.

29
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

5. How do I generate numbers in a specified range

There are several ways to generate numbers in a specified range, some better than others. One
method that you'll probably come across is the following:

random_integer = (rand()%10);

This will generate numbers in the range 0 to 9. To use a non-zero baseline you can do the following:

random_integer = 20 + (rand()%10);

This will generate numbers in the range 20 to 29.

The above method of producing pseudo random numbers is poor because it only uses the low-order
bits of the number returned from rand() and these may be less random for some pseudo random
number generator implementations.

For a better method you should prefer the following:

random_integer = 20 + int(10.0 * rand()/(RAND_MAX+1.0));

Don't be put off by the apparent complexity, it's remarkably simple to use and is superior to the
previous version. If we now substitute this into our earlier program we have the following:

#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;

int main()
{
srand(static_cast<unsigned>(time(0)));
int random_integer;
for(int index=0; index<10; index++){
random_integer = 20 + int(10.0 * rand()/(RAND_MAX+1.0));
cout << random_integer << endl;
}
}

We can make this more generally useful by incorporating it into a function, as shown below:

int random_range(int lowest_number, int highest_number)


{
if(lowest_number > highest_number){
swap(lowest_number, highest_number);
}

int range = highest_number - lowest_number + 1;


return lowest_number + int(range * rand()/(RAND_MAX + 1.0));
}

We pass random_range() two numbers representing the upper and lower values of the range of
numbers we wish to generate. The function checks that we have the lowest and highest values in the
right order. Next the range of random numbers required is calculated. Finally, we apply these numbers
to our call to rand() and return the random value.

Note that swap() requires the <algorithm> header.

The following small program demonstrates the use of random_range(). We initialise the pseudo
random number generator using the current time, then set up a vector to store the results returned by

30
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

random_range(). We provide storage for values from 0 to 11, but call random_range() with a range of
1 to 10.

The function random_range() is called 1,000,000 times and each returned value is recorded in the
results vector. Finally, we output the results for all occurrences from 0 to 11. There should be no
occurrences of 0 and 11, and the number of occurrences of each value from 1 to 10 should be close to
100,000.

#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <vector>

using namespace std;

int random_range(int lowest_number, int highest_number)


{
if(lowest_number > highest_number){
swap(lowest_number, highest_number);
}
int range = highest_number - lowest_number + 1;
return lowest_number + int(range * rand()/(RAND_MAX + 1.0));
}

int main()
{
srand(static_cast<unsigned>(time(0)));
int random_integer;
vector<int> results(12);
for(int index=0; index < 1000000; index++){
random_integer = random_range(1,10);
results.at(random_integer)++;
}
for(int index2=0; index2 < results.size(); index2++){
cout << setw(2) << index2 << setw(6) << results[index2] << endl;
}
}

To use random_range() in a program simulating a dice we would call:

random_range(1,6);

6. Conclusion

This concludes the tutorial. You should now be able to use the C++ rand() function to produce pseudo
random numbers in your programs.

As I said earlier, rand() itself is only really good enough for simple random number generation and for
many applications something better than rand() will be required. For a more in depth discussion about
random numbers and pseudo random number generators I can recommend the book Numerical
Recipes in C++, The Art of Scientific Computing (second edition). The Numerical Recipes Home
Page can be found at:

http://www.nr.com/

31
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

Simple C++ Program Example


Temperature Conversion

1. Introduction

This tutorial is for beginners. It assumes you are at least familiar with a simple Hello World program,
such as that described in the First C++ Program tutorial. Unlike many tutorials, this one doesn’t focus
on a single feature of the language but instead presents a simple C++ example program and
discusses a number of C++ language features as we develop it. Through following the example,
compiling the code and modifying it the reader should be able to gain some familiarity with the
language features covered and confidence in using the features in their own programs.

The example that follows is described sufficiently to understand its operation, but note that none of the
features introduced are discussed in their entirety. The aim is to provide enough of an explanation for
the code operation to make sense, but you’ll need to refer to an in-depth tutorial or a good book to
understand the features in more detail.

If you have difficulty with a particular feature, don’t dwell on it. It’s not necessary for you to understand
absolutely everything as we go along, and sometimes you may have to come back to a feature and
read through it again, before it falls into place. Compiling and modifying the examples should help;
don’t be afraid to experiment.

We develop a temperature conversion program which converts temperature from Celsius to


Fahrenheit, starting with a very simple version then addressing various problems with the basic
program. Then we introduce a separate conversion function and finally we extend the program to
make it more usable. As we progress through the different versions of the program we use if-else
statements, while loops, standard string class, creating and calling a simple function, range checking
of user input and handling invalid user input.

2. A Basic Temperature Conversion Program

In this basic version of our program we prompt the user to enter a temperature in degrees Celsius,
then convert the temperature to Fahrenheit and display the result.

#include <iostream>

using namespace std;

int main()
{
cout << "Temperature Conversion Program." << endl;
cout << "Enter degrees Celsius from 0 to 100: " << flush;

double degreesCelsius;
cin >> degreesCelsius;

double degreesFahrenheit = degreesCelsius*(9.0/5.0)+32;

cout << degreesCelsius << " degrees Celsius = ";


cout << degreesFahrenheit << " degrees Fahrenheit" << endl;
}

Let’s take a look at the body of the program. You should already be familiar with the following
statements:

#include <iostream>
using namespace std;

and with function main():

32
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

int main()
{

if not, read the tutorial named “First C++ Program”.

cout << "Temperature Conversion Program.\n";


cout << "Enter degrees Celsius from 0 to 100: " << flush;

Here we output two lines of text. The first line is simply the title of the program. At the end of the line of
text we have the newline character, ‘\n’, so that any text which follows appears on the next line of the
display.

The second line of text prompts the user of the program to enter a value for degrees Celsius, from 0 to
100. The flush manipulator that follows causes the line of text to be written to the display, but doesn’t
output a newline character so that the number the user enters appears just to the right of the prompt.

Having output the prompt we now want to read in the value from the user:

double degreesCelsius;
cin >> degreesCelsius;

The first of these lines declares a variable named degreesCelsius, of floating point type ‘double’. We
use the double type to store a number. Unlike the integer type, which only stores whole numbers,
floating point types such as double and float can store numbers that have a fractional part after the
decimal point e.g. 1.234, 0.006, 1387.9 and -126.57.

The second line reads in the value entered by the user and stores it in the variable degreesCelsius.
Once we have the user input we want to do the temperature conversion. The formula for converting
Celsius to Fahrenheit is:

Fahrenheit = Celsius x (9 / 5) + 32

We apply the formula in the following line:

double degreesFahrenheit = degreesCelsius*(9.0/5.0)+32;

At the left hand side we declare another floating point variable of type double, to store the temperature
in degrees Fahrenheit:

double degreesFahrenheit

On the right hand side we apply the conversion formula to the Celsius value we stored above:

degreesCelsius*(9.0/5.0)+32

Notice how we use the ‘*’ symbol for multiplication, and the forward slash ‘/’ for division. In order to
store the result of the conversion in degrees Fahrenheit we use the assignment operator, ‘=’.

Note also that we used floating point literals, 5.0 and 9.0, rather than integer literals 5 and 9. If we'd
used integer literals although the formula looks correct we'd get an incorrect result. This is because
integer division truncates, so with integer division the result of 9/5 is 1, not 1.8. This is a common error
for novice C++ programmers.

Now that we have our result, we can display it. The next two lines do just this.

cout << degreesCelsius << " degrees Celsius = ";


cout << degreesFahrenheit << " degrees Fahrenheit" << endl;

33
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

The first line outputs the value for degrees Celsius that the user input followed by the text “degrees
Celsius = ”. The second line outputs the value for degrees Fahrenheit followed by the text “degrees
Fahrenheit”. The endl manipulator causes a newline character to be output, followed by a flush of the
output stream (cout) so that the text is displayed and any text following (if any) will appear on the next
line. It’s equivalent to using ‘\n’ followed by flush.

That brings us to the end of the program. If you haven’t already done so, try typing in or pasting the
program and run it. Enter different values for degrees Celsius and confirm that the program gives the
correct answer.

2.1 Adding range checking for user input

The version of the program that we’ve written so far suffers from some problems, though we didn’t
point them out before. Notice how we prompt the user for degrees Celsius from 0 to 100 but the
program will accept any value even if it is lower than zero or higher than 100. Let’s modify the program
to handle this:

#include <iostream>

using namespace std;

int main()
{
cout << "Temperature Conversion Program." << endl;
cout << "Enter degrees Celsius from 0 to 100: " << flush;

double degreesCelsius;
cin >> degreesCelsius;

if((degreesCelsius < 0) || (degreesCelsius > 100)){


cout << "The number you entered is invalid." << endl;
}else{
double degreesFahrenheit = degreesCelsius*(9.0/5.0)+32;

cout << degreesCelsius << " degrees Celsius = ";


cout << degreesFahrenheit << " degrees Fahrenheit" << endl;
}
}

Our improved version starts just the same as before until we have read in the value from the user.
Now we have introduced an if statement. The expression between the brackets will be evaluated and
if it’s true then the code that immediately follows will be executed. If the expression evaluates to false
the code that follows the else statement will be executed instead.

if((degreesCelsius < 0) || (degreesCelsius > 100)){

The line above, the if statement, will evaluate to true if either degreesCelsius is less than zero, or
degreesCelsius is greater than 100. So, if we enter a value below 0 or above 100 the line that follows
will be executed:

cout << "The number you entered is invalid." << endl;

Instead of performing the conversion and displaying the result this line writes out an error message to
the user. The lines that follow the else statement won’t be executed.

If the value entered by the user is within range, from 0 to 100, then the if statement expression will
evaluate to false, the error message will not be displayed, and the code that follows the else statement
will be executed:

}else{
double degreesFahrenheit = degreesCelsius*(9.0/5.0)+32;

cout << degreesCelsius << " degrees Celsius = ";


cout << degreesFahrenheit << " degrees Fahrenheit" << endl;

34
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

This is the code that we saw earlier.

Once again, try typing in or copying this version of the program. Enter different values, some within
range and some without, and see what happens to the program output. Try changing the values of 0
and 100 in the if statement:

if((degreesCelsius < 0) || (degreesCelsius > 100)){

and check the operation of the program.

2.2 Handling invalid user input

There’s another problem with both of the versions of our program. You may have discovered this for
yourself, but if you haven’t go back and try entering a word instead of a number when prompted for
degrees Celsius. The behaviour of your program will depend on the compiler you are using but we
would expect it not to work correctly; clearly entering a word instead of a floating point number can’t
work as we can’t convert “hello” to Fahrenheit.

Here’s the program rewritten to handle this:

#include <iostream>

using namespace std;

int main()
{
cout << "Temperature Conversion Program." << endl;
cout << "Enter degrees Celsius from 0 to 100: " << flush;

double degreesCelsius;
while(!(cin >> degreesCelsius)){
cin.clear();
cin.ignore(1000,'\n');
cout << "Enter degrees Celsius from 0 to 100: " << flush;
}

if((degreesCelsius < 0) || (degreesCelsius > 100)){


cout << "The number you entered is invalid." << endl;
}else{
double degreesFahrenheit = degreesCelsius*(9.0/5.0)+32;
cout << degreesCelsius << " degrees Celsius = ";
cout << degreesFahrenheit << " degrees Fahrenheit" << endl;
}
}

Much of the above will look familiar to you. What we’ve actually done is modify the code associated
with the user input. We’ve replaced this:

cin >> degreesCelsius;

with this:

while(!(cin >> degreesCelsius)){


cin.clear();
cin.ignore(1000,'\n');
cout << "Enter degrees Celsius from 0 to 100: " << flush;
}

We’ve introduced a while loop. The expression in the while loop will be evaluated and if it's true the
statements that follow will be executed then the expression will be evaluated again. The statements
will continue to be executed repeatedly until the expression evaluates to false, then the program will
continue after the while loop.

35
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

while(!(cin >> degreesCelsius)){

This is the while loop statement. The expression that gets evaluated is:

!(cin >> degreesCelsius)

The exclamation mark is the not operator in C++. If the value entered by the user is invalid (for
example it is a word instead of a floating point number) then this expression will be true. The input
stream (cin) will be in a failed state. In this case, we have to reset the input stream flags:

cin.clear();

Next we discard anything that is left in the input stream from the failed operation:

cin.ignore(1000,'\n');

This will actually discard up to 1000 characters from the input stream or up to the next newline
character, whichever is first. (Note that if the user has entered more than 1000 characters this will still
leave characters in the input stream; the value of 1000 used here is arbitrary and there is a better
method but this is satisfactory for our purpose).

Because the user input was invalid we prompt for a value once more:

cout << "Enter degrees Celsius from 0 to 100: " << flush;

and now the program execution loops and the while loop expression will be evaluated once more:

while(!(cin >> degreesCelsius)){

If the user enters invalid data the while loop will repeat; if the user enters a valid numeric value the
program will continue execution after the while loop as normal.

Try it for yourself. Compile this version of the program and try entering a word instead of a number.

2.3 Putting it all into a function

So far all of our program has been contained within one function, main(). In the next example we will
move our temperature conversion code into a function on its own and call it from function main().
Although the code has been restructured the program behaviour when we run it will be just the same
as it was in our last version. Here’s the new version:

#include <iostream>

using namespace std;

void temperatureConversion()
{
cout << "Enter degrees Celsius from 0 to 100: " << flush;

double degreesCelsius;
while(!(cin >> degreesCelsius)){
cin.clear();
cin.ignore(1000,'\n');
cout << "Enter degrees Celsius from 0 to 100: " << flush;
}

if((degreesCelsius < 0) || (degreesCelsius > 100)){


cout << "The number you entered is invalid." << endl;
}else{
double degreesFahrenheit = degreesCelsius*(9.0/5.0)+32;
cout << degreesCelsius << " degrees Celsius = ";
cout << degreesFahrenheit << " degrees Fahrenheit" << endl;
}

36
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

int main()
{
cout << "Temperature Conversion Program." << endl;
temperatureConversion();
}

You may have used your own functions before or, if you’re still very much a novice, you may only have
come across main() until now. We've introduced a function called temperatureConversion into out
program. The basic structure of this function is simple, compare it to function main():

void temperatureConversion()
{
// do some stuff here

The return type of the function is void. This means that we don’t return a value to the calling routine
(which happens to be function main()) when the function terminates, so we don’t need a return
statement at the end of the function.

The return type is followed by the name of the function, temperatureConversion.

The function name is followed by a pair of brackets within which we may pass values (parameters) to
a function. In this particular case we don’t pass any parameters to the function so the list of
parameters is blank, though we still need the pair of brackets.

Just like main the body of the function is inside a pair of curly braces, with the opening brace at the
start of the function and the closing brace at the end. If you forget to add one of these your program
will fail to compile and will generate an error. (Sometimes it’s not obvious what the cause of the error
is from the error message).

All of the code within the temperatureConversion function should be familiar to you, we’ve simply
moved it from main() to this function.

Program execution starts with main(), so in order to execute the temperature conversion code we
need to call our new function from within main(). We call the function like this:

temperatureConversion();

When this line is reached within main(), the program will execute the code in the
temperatureConversion function. When it reaches the end of that function execution returns to main()
and continues with the code that follows the function call (which in our case is the closing brace of
main() so our program terminates).

2.4 Repeat conversion

The advantage of placing our temperature conversion code in a separate function may not be
immediately apparent from our program. However, now we'll extend our program to enable the user to
repeat the conversion as many times as they wish, and only terminate the program when they’ve
finished.

Because we've put the temperature conversion code into a function we can simply call that function as
many times as we like. We don’t have to include the code more than once in our program.

#include <iostream>
#include <string>

using namespace std;

void temperatureConversion()
{

37
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

cout << "Enter degrees Celsius from 0 to 100: " << flush;

double degreesCelsius;
while(!(cin >> degreesCelsius)){
cin.clear();
cin.ignore(1000,'\n');
cout << "Enter degrees Celsius from 0 to 100: " << flush;
}

if((degreesCelsius < 0) || (degreesCelsius > 100)){


cout << "The number you entered is invalid." << endl;
}else{
double degreesFahrenheit = degreesCelsius*(9.0/5.0)+32;
cout << degreesCelsius << " degrees Celsius = ";
cout << degreesFahrenheit << " degrees Fahrenheit" << endl;
}
}

int main()
{
cout << "Temperature Conversion Program." << endl;

string userInput("yes");
while(userInput == "yes"){
temperatureConversion();
cout << "\nWould you like to convert another temperature? " << flush;
cin >> userInput;
}
}

Firstly, although our code is starting to look quite complex, most of it is unchanged from the last
version. In fact, the temperatureConversion function hasn’t changed at all. Function main() has been
modified and we’ve also included a new header:

#include <string>

We’ve included this header because we use the standard string class in main(). Working through the
changes in this version of the program we come to the declaration of a string:

string userInput("yes");

This creates a string named userInput and initialises it with the value “yes”. Next we come to a while
loop:

while(userInput == "yes"){
// do some stuff here
}

The while loop expression will be evaluated and if true the code between the braces will be executed.
This introduces the == operator, which is used to test equality. We've just initialised the string
userInput with the value “yes”, so the first time through this loop the expression will evaluate to true
and the code within the while loop will be executed. The second time the expression is evaluated the
value will be that entered by the user (as we shall see, below).

while(userInput == "yes"){
temperatureConversion();
cout << "\nWould you like to convert another temperature? " << flush;
cin >> userInput;
}

When the loop is entered, it calls the temperatureConversion function and executes the code in that
function. The function will do what it did in the previous example; it will prompt for a Celsius value,
check the range and handle invalid input, and output the Fahrenheit value as appropriate. Once done,
execution will return to the next statement inside the while loop in main().

38
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

The next statement outputs a newline character in order to visually separate the text from the previous
output, then prompts the user to see if they’d like to convert another value:

cout << "\nWould you like to convert another temperature? " << flush;

Following this, we read in and store the string entered by the user:

cin >> userInput;

Now program execution returns to the top of the loop and the expression is evaluated once more. If
the user has typed in “yes” then the temperature conversion function will be called again and the
sequence will repeat. It will continue to repeat until the user enters a different string instead of “yes”
when prompted. At that point the while loop will terminate and the program will continue after the while
loop, which happens to be the end of the program.

2.5 What did we cover?

You may have already covered some of these features before reading this tutorial, but to recap, we
talked about:

Output using cout; the newline character, flush and endl; declaring and using
a floating point type double; reading in a value using cin; using a formula;
integer division; if-else; range checking user input; while loops; handling
invalid user input; resetting cin in a failed state; discarding characters
from the input stream; creating and calling a simple function; standard
string class;

3. Conclusion

This concludes the tutorial. I hope you have found the example useful. Don’t forget to copy and
compile the code yourself, and try modifying it to reinforce your understanding.

39
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

Pointers - Part 1
An introduction

1. Introduction

This tutorial is for beginners. It assumes you have already covered basic C++ programming to the
point where you can compile simple programs, declare and use different types of variables, and call
simple functions. In this tutorial we will discuss pointers. No previous knowledge of pointers is
necessary.

Understanding pointers is often challenging for beginners. It requires new concepts to be learnt and
understood, and the application of pointers can be far more error-prone than using other variable
types such as ints, doubles and chars. Still, if you're prepared to spend a little time acquiring a
thorough understanding of the basics, using pointers can be learnt with relative ease.

This is the first of two tutorials covering pointers and serves as an introduction. At the end of it you
should have a basic understanding of what a pointer is, how to declare one in your program and how
to manipulate the value of the variable pointed to. You should practice using pointers as shown here in
your own programs before trying to move on to more advanced applications of pointers, which I'll
cover another tutorial.

2. Integer, integer, wherefore art thou, integer?

The variables you declare and use in your program exist in memory during program execution. Each
variable will exist at a particular memory address.

We can declare an integer variable in our program like so:

int myInteger = 37;

This will set aside enough memory to store an integer value and initialise that memory to hold the
value representing 37 in integer format. We don't yet know the actual memory address the value is
stored at but it's there somewhere and our program knows where to find it, otherwise it couldn't set or
retrieve the value of myInteger. The actual address where myInteger is stored may change each time
we run the program but our program knows how to cope with that.

C++ provides a way for us to refer to the address of a variable using the 'address of' operator, a single
ampersand (&), in conjunction with the variable name. The memory address of myInteger can be
referred to using:

&myInteger

Because we can refer to it, we can output the value of the address as follows:

#include <iostream>
using namespace std;

int main()
{
int myInteger = 37;
cout << &myInteger << flush;
}

When I ran this program on my computer it displayed the following:

0x76fde4

This represents the memory address at which the value 37 is stored, in hexadecimal.

40
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

We can use the address of operator for other types too. Try the following program:

#include <iostream>
using namespace std;

int main()
{
int myInteger = 37;
int anotherInteger = 42;
double floatingPoint = 1.234;
bool trueOrFalse = true;

cout << "myInteger: " << &myInteger << endl;


cout << "anotherInteger: " << &anotherInteger << endl;
cout << "floatingPoint: " << &floatingPoint << endl;
cout << "trueOrFalse: " << &trueOrFalse << endl;
}

When I ran this I obtained the following output:

myInteger: 0x76fde4
anotherInteger: 0x76fde0
floatingPoint: 0x76fdd8
trueOrFalse: 0x76fdd7

We can see that each variable has its own address, occupying its own space in memory.

3. Storing a memory address in a pointer

Now that we've seen how to refer to a memory address, let's see how we can store a memory
address. This is where pointers come in. Listen carefully:

A pointer is a variable that holds an address.

A pointer is a type of variable. Just as C++ has integers to store whole numbers, doubles to hold
floating point values, bools to hold values of true or false, and strings containing characters, C++ has
pointers, which can hold addresses.

Earlier we declared an integer variable, myInteger:

int myInteger = 37;

We also output the address of myInteger:

cout << &myInteger << flush;

Now we will see how to store the address of myInteger in a pointer variable.

When we declare a pointer variable we have to tell it the type of data stored at the address. Here's a
declaration for a pointer to an integer, with initialisation:

int* myPointer = &myInteger;

We start by identifying the type of data stored at the address, in this case int, followed by '*' which tells
us this is a pointer. Next is the name we gave to our pointer variable, myPointer. We then chose to
initialise the pointer variable with the value of the address where myInteger is stored.

So, when our program executes it sets aside enough memory to be able to hold a memory address. It
stores in this memory the address of myInteger, which - when I ran the program earlier - was
0x76fde4. In other words the value 0x76fde4 is stored in the variable myPointer. Don't worry if you

41
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

can't see how this could be useful yet. For now, satisfy yourself that you understand what is happening
with the line of code we just covered.

Let's see it in action, and convince ourselves that what I said above is true. Look at the following
program:

#include <iostream>
using namespace std;

int main()
{
int myInteger = 37;
int* myPointer = &myInteger;
cout << myPointer << flush;
}

This time, instead of outputting the address of the variable myInteger directly, we've stored the value
in our pointer variable, myPointer, and then output that value. When I ran this the output was:

0x76fde4

Don't worry if the value you obtain is different to the one you had earlier. It could be a different value
every time you run your program, or it could be the same value between runs. It's platform specific and
either behaviour is normal.

Now, just in case you need further convincing, try the following:

#include <iostream>
using namespace std;

int main()
{
int myInteger = 37;
int* myPointer = &myInteger;
cout << &myInteger << endl;
cout << myPointer << endl;
}

Here we output the address directly, and also using the pointer variable. The two values output should
be identical when you run the program. When I ran this I obtained:

0x76fde4
0x76fde4

In the program above we say that myPointer 'points to' myInteger. This is just a convenient way of
expressing that it hold the address of the variable myInteger.

The type of myPointer is 'pointer to int'. If we have the following two declarations we can see clearly
the difference between the declaration of an integer and the declaration of a pointer to integer:

// Declaration of an integer
int n;

// Declaration of a pointer to an integer (uninitialised)


int* p;

The following example is effectively the same as the previous example but this time for a floating point
variable, a double.

#include <iostream>
using namespace std;

int main()

42
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

{
double floatingPoint = 1.234;
double* myPointer = &floatingPoint;
cout << &floatingPoint << endl;
cout << myPointer << endl;
}

Notice that the declaration of the pointer variable reflects the fact that it now 'points to' a variable of
type double:

double* myPointer = &floatingPoint;

Previously we had:

int* myPointer = &myInteger;

The type shown in the pointer declarations above is known as the 'base type', and as we said earlier, it
tells us what type of data is pointed to, int, double or some other variable type.

4. Accessing a variable through a pointer

Now that we know how to take the address of a variable and store it in a pointer, let us look at how we
can use that pointer to access the variable that it points to. For now, don't worry about why we would
want to, it's important for you to understand how it can be done, and it's really quite simple.

Here's a code example to demonstrate:

#include <iostream>
using namespace std;

int main()
{
int myInteger = 37;
int* myPointer = &myInteger;
cout << *myPointer << flush;
}

All of the above code should look familiar from our previous examples, except the last line:

cout << *myPointer << flush;

When I run this code on my computer it outputs the number 37.

We declare a pointer to int and call it myPointer. We initialise the myPointer to hold the address of the
integer variable myInteger - we saw that earlier.

With this:

*myPointer

we can actually access the value of the integer that is pointed to, which in this case is 37. So the
whole line causes the value pointed to by myPointer to be output.

Here's another example using the pointer to double that we saw earlier:

#include <iostream>
using namespace std;

int main()
{
double floatingPoint = 1.234;
double* myPointer = &floatingPoint;

43
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

cout << *myPointer << flush;


}

Once again, most of the program should be familiar to you. And with this line:

cout << *myPointer << flush;

we output the value of the variable pointed to by myPointer, which in this case is the value 1.234.

We can also change the value of the variable pointed to through our pointer:

#include <iostream>
using namespace std;

int main()
{
int myInteger = 37;
int* myPointer = &myInteger;
cout << myInteger << endl;

*myPointer = 42;
cout << myInteger << endl;
}

We start off as before, initialising myInteger with a value of 37. Next, as before, we initialise myPointer
with the address of myInteger. The following line simply outputs the value of myInteger, which will
output the value 37.

This line:

*myPointer = 42;

assigns the value 42 to the variable pointed to by myPointer, in other words, it assigns the value 42 to
myInteger. It is effectively equivalent to:

myInteger = 42.

It's important that you understand what's going here. We don't assign a value of 42 to the pointer, in
fact the pointer variable itself is not modified in any way and continues to hold the memory address of
the integer variable myInteger. What we're doing is saying take the address that is held in myPointer
and modify the variable at that address to be 42. Instead of referring directly to myInteger we refer to it
using its address in myPointer.

The last line outputs the value of myInteger again but this time instead of 37 it outputs 42.

To reinforce the idea, here's the equivalent floating point version:

#include <iostream>
using namespace std;

int main()
{
double floatingPoint = 1.234;
double* myPointer = &floatingPoint;
cout << floatingPoint << endl;

*myPointer = 9.876;
cout << floatingPoint << endl;
}

This line:

*myPointer = 9.876;

44
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

assigns the value 9.876 to the variable pointed to, which in this case is floatingPoint. When I run this
program the output is:

1.234
9.876

5. Modifying a pointer variable

Just like other variables, we can modify the value that a pointer variable holds. A pointer holds an
address; when we modify its value we are assigning a different address to it. Let's see a simple
example:

#include <iostream>
using namespace std;

int main()
{
int myInteger = 37;
int* myPointer = &myInteger;
cout << *myPointer << endl;

int newInteger = 99;


myPointer = &newInteger;
cout << *myPointer << endl;
}

To begin with we initialise myPointer to hold the address of myInteger, and to prove it we output the
value pointed to, which will output 37.

Next we assign the address of newInteger to myPointer:

myPointer = &newInteger;

Now it points to newInteger, so when we output the value pointed to it will output 99.

6. Using pointers as function parameters

When we pass a variable to a function a copy of the variable is created and used within the function;
the original value is unaffected by any changes that are made to the copy. For example, consider the
following:

#include <iostream>
using namespace std;

void printDoubleValue(int localCopy)


{
localCopy = localCopy * 2;
cout << localCopy << endl;
}

int main()
{
int myInteger = 4;
cout << myInteger << endl;
printDoubleValue(myInteger);
cout << myInteger << endl;
}

The output of the above code will be:

45
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

8
4

We start by initialising myInteger with a value of 4 and then output this value.

Next we call printDoubleValue and pass myInteger as a parameter to the function, with a value of 4. A
local copy of myInteger, localCopy, is made and it's this local copy that is multiplied by 2. The new
value of localCopy is then output.

The variable myInteger is unaffected by the changes made to the local copy in the function, so when
we output myInteger a second time the value is still 4.

Now let's see what happens if we pass a pointer to a variable instead:

#include <iostream>
using namespace std;

void printDoubleValue(int* pointerToInteger)


{
*pointerToInteger = *pointerToInteger * 2;
cout << *pointerToInteger << endl;
}

int main()
{
int myInteger = 4;
cout << myInteger << endl;
printDoubleValue(&myInteger);
cout << myInteger << endl;
}

This time our function expects a pointer to an integer to be passed as a parameter:

void printDoubleValue(int* pointerToInteger)

When we call our function, we pass the address of myInteger:

printDoubleValue(&myInteger);

When we modify the value pointed to by pointerToInteger in our function, because pointerToInteger
holds the address of the variable myInteger any changes made to the value pointed to actually modify
the value held by myInteger:

*pointerToInteger = *pointerToInteger * 2; // doubles the value held in myInteger

When our function returns, myInteger holds the new value of 8. The output of the code is therefore:

4
8
8

Compare this with the previous version which output:

4
8
4

To recap, when we pass a variable as a parameter to a function a copy of the variable is made and
used by the function, and any changes to that variable leave the original variable (outside of the
function) unaffected. By passing a pointer to a function we can modify the original variable through the
pointer.

46
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

7. Conclusion

That completes our basic introduction to pointers. It's worthwhile spending whatever time you need to
become comfortable with the ideas that have been introduced. Once you understand and feel
confident with the basics, you'll be ready to progress with more advanced uses of pointers, something
I plan to address in my next tutorial.

47
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

Further Reading
Where to go for help

1. Buy a book; buy several books

If you’re trying to learn C++ you need to buy a book. The quality of the books on the market at the
moment varies considerably, so do look around and seek advice before you part with your money.

There is probably no single book that can be recommended for all newcomers to C++ because
previous knowledge and experience will vary. Some will have no previous experience of programming
at all, and may be relatively unfamiliar with even using a computer. Others may have had previous
experience in a different language such as Basic, Pascal or Ada. And some may have experience with
a language that has familiar syntax, such as C. The learning curve for each will be different.

Buy a book that teaches C++ and is not specific to a particular environment (e.g. Microsoft Windows,
Unix). It may well be the case that you’re only interested in writing programs for one environment at
the moment but you will find it beneficial to become proficient in the core language before you try to
write platform specific programs. It will also help you to understand what is standard, portable C++ and
what is platform specific, which is a major advantage.

Be prepared to buy more books once you start to become proficient. It’s unlikely that you’ll become
truly skilled as a C++ programmer from a single book, particularly when your first book is likely to be
aimed at beginners. You should expect to add several books to your own personal library as you
develop your C++ skills.

There are many books to choose from and everyone has their own personal favourites. I'll restrict my
list of recommendations to just two.

The C++ Programming Language, Special Edition


Bjarne Stroustrup
Addison Wesley, ISBN 0-201-70073-5

This is a popular and highly recommended book, written by the original creator of the C++ language.
For some novices with limited previous programming experience the book may be hard going as a first
book so I would recommend that you start with something else, but this is a good choice for your
second book and will undoubtedly prove to be an invaluable reference; every C++ programmer should
have access to a copy. I would recommend the hardback Special Edition over the softback Third
Edition; if you use your copy as much as I use mine it will benefit from the hardback cover.

The C++ Standard Library, A Tutorial and Reference


Nicolai M. Josuttis
Addison Wesley, ISBN 0-201-37926-0

A hugely popular book, it covers the C++ Standard Library in depth, and is written in an easy to follow
style with many code examples. A worthy addition to your collection, this book will enable you to
appreciate and take advantage of the power that the standard library provides.

2. Newsgroups

There are currently three newsgroups that you might be interested in if you’re learning C++. If you’ve
never used newsgroups before I would encourage you to try them.

Before you post to a newsgroup you should read the posts there for a while, at least for a few days, to
get a feel for what is considered to be on-topic and relevant, and what is not. Find out where you can
get the FAQ for the newsgroup and read it before your first post. Newsgroups are a useful resource

48
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

but they can be unforgiving at times; if you don’t follow netiquette you can end up on the receiving end
of some flames from the regulars. Follow netiquette and you’ll find people can be extremely helpful.

If you have a question search the posts in the newsgroup to see if it has been asked before. You’d be
surprised just how often some questions come up. You can search a historical database of
newsgroups at Google:

http://groups.google.com/

Remember that the people answering questions in newsgroups do so voluntarily. They receive no
payment for doing so and act out of kindness. Remember also that sometimes, even with the best
intentions, people answering questions in newsgroups get it wrong. On rare occasions it’s deliberate
and malicious, more often it’s unintentional. In general mistakes are spotted by other posters and a
correction is posted, but exercise caution.

Newsgroups are not chat rooms; when you post a message to a newsgroup it may appear almost at
once on your server or it could take hours. It may take many hours in some cases for it to appear on
servers around the world, though often it can be very fast. Be prepared to wait for an answer, don’t be
impatient if you don’t get a reply in the first 10 minutes, and don’t be tempted to post your question
more than once just because you don’t see it appear straight away.

The following newsgroups are worth subscribing to:

alt.comp.lang.learn.c-c++

This newsgroup is specifically aimed at people learning C or C++. You should only post here if your
question is about using the language itself as defined by the standard; questions about your particular
compiler, or operating system, or platform specific code, will be considered off-topic. Remember to
identify your question as being related to C++ as many of the regulars will answer both C and C++
questions and will obviously provide different answers for each.

The group is unmoderated; anyone can post to the newsgroup whether the question is relevant or not,
so there is some degree of ‘noise’ (off-topic posts) and the occasional nuisance poster. When you first
learn C++ this is an ideal place to ask questions, and to read the posts of others.

comp.lang.c++

This newsgroup is for questions relating to the use of the C++ language (as defined by the standard).
As with alt.comp.lang.learn.c-c++ you should avoid platform specific questions. You can post to either
of the two groups when you’re first learning and you’ll find that both have regulars who will provide
good quality answers. In general, I would advise you to use alt.comp.lang.learn.c-c++ to ask questions
while you’re first learning, but read the posts in this group too as you’ll learn a lot from them.

This group is also unmoderated so there is a degree of noise and the occasional nuisance poster.

comp.lang.c++.moderated

As the name implies this group is moderated. Posts are filtered by individuals from a group of
moderators who check that the content is on-topic and non-abusive. If a post doesn’t meet the
necessary criteria it is rejected. This keeps the noise level down at the expense of introducing a delay
between posting your question and seeing it appear. The delay is usually quite short and reasonable.
You might find the posts in this newsgroup difficult to understand as a novice, but in time it may prove
to be a useful resource for you.

49
C++ Tutorials (for beginners and cheapskates) 5th May 2004
By Bob Jacobs

3. The Internet

The internet is full of useful resources. Your favourite search engine is your friend; use it whenever
you want to find something specific. You can find reference information, tutorials, forums, free tools
and compilers, and a great deal more.

One word of caution, don’t believe everything you read on the internet.

You should be cautious about the information you come across unless you know and trust the source.
Of the huge volume of information at your finger tips much may be old and potentially out of date. You
need to consider this when you’re searching, it won’t always be obvious to you. Cross check against
other sources of information wherever possible (but consider that some might have used the same
source as yourself).

Of the rest, much may simply be inaccurate. In some cases it may just be slightly incorrect, the harm
done may be minimal, in other cases the information may be totally useless – and you can’t always tell
by looking. Once again, cross check against other sources of information wherever possible.

That said, there’s a lot of good stuff out there, so get surfing.

50

You might also like