headerstuff

C++ For

Ordinary People

Introduction

This book is written for ordinary people who are studying C++. It is NOT written for those who are studying Computer Science at say Harvard, MIT, or Cambridge.

Instead, I imagine you as a student or hobbyist. You are reading fat C++ books, websites, and instructors notes, but you are getting confused. All you want to do is understand and run some simple programs!

The bad news is that C++ is not simple, but this book cuts down on the detail, only presenting the essential stuff bit-by-bit. It will get you headed in the right direction, then later you can use and understand advanced material from the fat books and impenetrable instructors notes.

This book covers: data types, arrays, strings, files, control structures, functions, and an introduction to object-oriented programming. (I know you won't understand most of these terms yet, but I assure you that they are all essential.)

The programs in the book have been tested on zero-cost C++ systems, and an appendix has information on these free systems.

The programs can be downloaded from:
http://www.mikeparr.info/cpp.html


Best wishes in your studies.

Mike Parr

(February 2014)

Contents

Chapter 1
Computers:
The Basics

Introduction

The purpose of this chapter is to provide an introduction to the considerable amount of jargon in computing. It is written for novices.

Though this book is mainly concerned with writing C++ programs, the actual use of computer systems requires the ability to understand technical jargon. This comes with experience, but here a brief overview is presented. You also get to run a C++ program.

1.1 Hardware

The term 'hardware' refers to the physical and electronic parts of a computer. Here are the main components.

1.1.1 The Keyboard

Ensure that you can find the 'enter' key, which you press at the end of typing a line of text. Sometimes it is referred to as the 'return' key. You also need to locate the 'shift' key, which switches between upper-case letters (capitals) and lower-case (small) letters. It also gives you the upper symbol on many keys, such as '(' instead of '9'. Finally, note that there is a single-quote and a double-quote key. These are not interchangeable in C++.

1.1.2 The Screen

This can display overlapping rectangular areas called windows. They can be dragged and resized by a mouse, or directly by touch on a tablet. When you type in text, there is a flashing symbol which shows the current typing position. This is known as the 'cursor'.

1.1.3 Storage

We store items in files. For example, a file might contain a photo, a C++ program, or a word-processed document. Files can be stored permanently (barring accidents) on hard-disc drives, consisting of a rotating magnetic surface. On small portable computers and phones, we use solid-state memory cards internally, and also external USB memory sticks. When programming, it is a good idea to keep a backup copy of your files. This can be done with a USB stick, emailing them to yourself, or on Internet cloud storage.

1.1.4 Memory and CPU

Inside the computer we have devices that deal with your programs as they run (execute). In particular:

When we use C++ commands such as:
x = n+1;

the values of x and n are held in RAM, and the CPU performs the actual addition. To give you a feel for the scale, a typical RAM will be able to hold 1,000,000,000 million numbers, and 10,000,000,000 instructions (such as addition) can be executed per second.

1.2 Software

Software is harder to describe - it is less tangible than hardware. Imagine some written instructions for finding your way to a destination. The streets and buses are the hardware, and the instructions are the software. You could even memorise the instructions and throw them away - you still have the plan in your mind!

To take the analogy further, we can also make the distinction between the instructions kept unused in your pocket, and the instructions when you are in the act of using them. In computer terms, the instructions are a program which can be stored on disc. To actually obey the program, it is loaded into RAM, and executed ( or 'run' ) by the CPU. In this section, we will look at some important software concepts.

1.2.1 Machine code (object code)

The CPU can only interpret instructions written in machine code. In principle, we could use this language to write programs, but it is very tedious and error-prone. For example, the calculation:
    salary - deductions + allowances

would be carried out in machine-code by instructions of the form:
    fetch salary value
    fetch deductions value
    subtract them
    fetch allowances value
    add it

In fact, these instructions would be stored in RAM as binary data, only consisting of 1's and 0's. To avoid these very low-level instructions, we use a C++ compiler to translate C++ statements into machine code, which can then be executed. In short, C++ programs have to be compiled (translated) before running.

1.2.2 The Operating System

This is a large program which runs in RAM, alongside every other program. The names and versions change over the years, and currently the major ones are Microsoft Windows, Linux, and the Apple Mac varieties. On tablets and cellphones the most common are Android and Apple systems.

An operating system handles such tasks as:

file handling (creating, deleting, moving, printing ...)

interpreting the user's commands.

running other programs.

1.2.3 Folders

Storage can be split up into areas called folders, or directories - each folder can hold many files. As an example, we might create two folders:

letters
programs

In the letters folder, we might have two files:
job-application.doc
complaint.doc

In the programs folder we might have two files:

game.cpp
assignment.cpp

Inside the 'game.cpp' and the 'assignment.cpp' files, we would have C++ programs.

Each file and folder is given a name by the programmer. The exact rules for forming names (in particular whether spaces can be used) depend on your operating system (see below). Here, we will avoid spaces in file and folder names. This rule works on all operating systems.

1.3 Creating and Running Programs

Whichever operating system you use, the following pattern of commands is common:

  1. Type in or amend your C++ program with an editor (which is rather like a word-processor).

  2. Compile the program.

  3. If compilation errors occur, go to step 1 and amend.

  4. Execute the program. If errors occur, go to 1, and amend.

Here, three programs are being executed: editor, compiler, and C++ program. The commands or mouse-clicks needed to execute the programs will depend on which software you choose. There are options, and this is discussed below.

Note the possibility of errors in the above steps. In fact, certainty is more appropriate. There are two general categories, called compilation (or syntax) errors, and run-time errors (bugs). A compilation error is akin to a spelling mistake - you won't make very many when you get used to the language, and they are usually easy to locate. Run-time errors are typically caused because the logic of the program is wrong i.e. it is grammatically correct but doesn't carry out the intended task. Spotting these takes time and patience.

1.4 Setting up C++ On Your Computer

Appendix 1 describes possible zero-cost software choices for Windows and Linux. Read it, download your choice, and you are ready to run a first program.

1.5 Viewing Code On Your Kindle

Before we study the following C++ code, note that programmers often use lines that can extend over 70 or 80 characters in length. I have tried to shorten the lines in this book, but this is often not possible. So, I recommend that you turn your Kindle sideways when looking at program code that extends to the edge of the screen.

1.6 A First Program

Enough of words - now for action! We will begin to program. Here is a C++ program, which you could type in by using the editor. Store it in a file called hello.cpp. Note that you can choose the name, but the main part should only contain letters and numbers, and the end part (the 'extension') should be .cpp.

// my first program               (1)
#include <iostream>               (2)
using namespace std;              (3)
                                  (4)
int main(void){                   (5)
    cout << "Hi There" << endl;   (6)
    return 0;                     (7)
}                                 (8)

Note that you would not type the line numbers at the right - they are to assist in this explanation.

When you use the appropriate commands to compile and run the program, you will find that it displays the following line of text on the screen:
Hi There

Here, some introductory points are covered, to be explained in more depth later.

Line 1 shows a comment line, preceded by //. Comments can contain any text whatsoever, without any rules. They help someone else to follow the program. An analogy is jottings made in the margins of your notes, to clarify their meaning. In most of the programs which follow, we will put the name of the file itself in the first comment, so you can easily locate and run the file from our download.

Lines 2 and 3 are necessary in most C++ programs. They are needed to incorporate facilities for moving data to/from the keyboard/screen. Most programs in this book will do this. (Note that on the web, you will see programs with the single line #include <iostream.h>. This is old-style C++).

Line 4 is a blank line. We can put them anywhere, to aid human readability.

Line 5 is necessary in most small C++ programs - the program actually starts running at this line.

Lines 5 also ends with an opening curly bracket, often called a 'brace' - it matches the closing brace on line 8. The { and } are used to group statements together. Note that in C++ we also have parentheses (round brackets) and later we will encounter [ ] - square brackets.

Line 6 shows the cout 'character output stream' item in use. Effectively, this refers to the screen in simple examples. The << symbol means 'receives'. So here the screen receives Hi There. When we send endl (end-line) the end-of line character(s) are sent. Note that endl's last letter is a lower-case L.

The semicolon ends every statement - the problem is that every line of the above is not technically a statement so you can't litter semicolons around with abandon.

Typing in 8 lines of program sounds easy, but if you are new to computers it is not! Everyone finds it hard at first but after a few sessions, the keyboard and editor will become familiar.

Here is a hint. All of the programs you write will contain the above code (with the exception of the "Hi There" line) so you could start a new program by pasting in the above code, rather than re-typing it from scratch.

Key Points

Software controls hardware - without software, a computer is useless.

A C++ compiler translates your program code into machine-code, and also checks for errors you make.

Problems

  1. Find out which operating system you have. Download and install your choice of software as discussed in Appendix 1.

  2. Key in and run the example first program.

  3. Edit the program so it displays your name.

  4. Make an error in the program, and note the error message that appears. For example, you might delete a ; or a }.

Chapter 2
Variables
And Expressions

Introduction

Conceptually, a variable is like a box with a unique name, into which we can place a value, such as a number. We may then refer to the box by its name. (Behind the scenes, the box also has a numeric address, which we don't need to be concerned with for the time being.)

Here, we will look at the rules for introducing variables into a program, but the hard part is deciding which variables are required - it depends on practice, experience, and a knowledge of similar examples.

2.1 Numeric Variables

There are two main types of numeric variable:

The bottom line is that for everyday problems, int and float will accommodate most numbers you need to work with.

Choose int for exact, whole-number quantities, e.g:

Choose float for 'decimal-point' quantities, e.g:

Though you won't need them often, C++ provides some additional numeric types, not described here. Later we will encounter types for handling non-numeric character data.

2.2 Meaningful Names, with Style

As in all programming languages, there are certain rules about how we are allowed to express variable names. In C++, the rules are:

Here are some illegal names:
    3times,  payin$,  tax-rate,  tax code

Note that upper-case (capitals) are treated as distinct from lower-case, thus: PAY, pay, Pay are 3 different variables. We say that C++ is 'case-sensitive'.

Upper-case is used rarely.

Style. Look at a possible name: payineuros. It is hard for us to read, yes?. There are two style conventions that have grown up to improve clarity. We use either underscores or 'camelCapitals'.

Firstly underscores. C++ treats the 'underscore' character _ as a letter, so we can use it like this:

exam_mark rather than exammark

pay_in_euros rather than payineuros

Alternatively, we can use camelCapitals. (Trace your finger along the top of this strange word to see the hump!). We capitalise every word except the first one, as in:

examMark rather than exammark

payInEuros rather than payineuros

Some organisations insist on one or the other style. If you have a free choice, choose one and stick to it. I will choose the underscore style here.

Whichever style, use meaningful names! Your program may be read by other programmers, who need to understand its logic as quickly as possible. Meaningful names will help - e.g:

exam_mark or examMark

rather than

em, m, emk. Sometimes, short names can be meaningful. Often, mathematics names such as x and y can be appropriate.

2.3 Declaring Variables

C++ insists that you 'introduce' the name of a variable before you use it. These declarations are often grouped together near the top of the program, but you could declare a variable partway through some code. Here is an example:

//declaring.cpp
#include <iostream>
using namespace std;

int main(void){
    int exam_mark, class_size;
    float height = 1.8;
    float width = height + 0.66;
    int VDU_size = 1024;

// then calculations, cout,etc

    return 0;
}


Note that we can declare some variables of the same type on one line, with commas between them, and we can also supply an initial value by using =. Following the = we can even have calculations based on the value of previously-declared variables. Numeric variables that we do not initialise are set to zero.

2.4 Introduction to Expressions

The topic of expressions is a large one in C++, but it is important to concentrate on the main features, rather than the mass of detail. A professional C++ programmer would need to know more than the material presented here, but, for our introductory purposes, a subset will suffice.

Expressions are introduced here via assignment statements, but in fact the expression is allowed in many other contexts - it is an important concept.

2.5 The Assignment Statement

Here are some examples of the simplest form of assignment. They are executed (obeyed, carried out) in sequence, from top to bottom.

    // declare a few variables for the examples
    int a,b,c;
    float x,y;

    // now some assignment statements
    a = 1;
    b = 6;
    c = -12345;
    x = 12.34;
    y = 34.5E2;     // means 34.5 * 10 to power 2
    etc

'=' should be read as 'becomes', NOT 'equals'.

In C++, the right-hand-side of the = is evaluated first, resulting in a single number. This is then assigned to (stored in) the variable on the left-hand-side. For instance, we are allowed to put -
    c = a+b+1;    // c becomes  8
    c = c+1;      // c becomes  9

This latter form is particularly common in programming:

c was 8. It is now updated to 9.

the general form of an assignment statement is:
    variable = expression;

Note the semicolon - we are using statements, and a semicolon terminates every complete statement.

No apologies for repeating: '=' should be read as 'becomes', NOT 'equals'.

In your very early days of learning C++, you might accidentally put:
    8 = c;

The compiler is likely to respond with an error message of the form ' 8 is not an lvalue'. The 'l' in lvalue stands for left, and the compiler is stating that a number is not a suitable place to store a new value, i.e it can't appear on the left of an =.

2.6 Arithmetic Operators

The above examples assumed you would guess what '+' meant, and it does indeed represent addition. It is an example of an arithmetic operator, and the complete set is:

Consider the expression:
    6 + 4 * 2

Does it result in 20 or 14 ?

In fact, C++ follows the algebra convention in performing multiply before add, so the result is 14. The priority of calculation is

If all the operators have the same priority, left to right order is used.

Most programming tasks don't involve a rote conversion of algebraic formulae into C++ assignments, but let's have a look at tricky areas:

        Algebra                C++

(a) y=mx+c                 y=m*x+c;
(b) x=(a-b)(a+b)           x=(a-b)*(a+b);
(c) y=3[(a-b)(a+b)]-x      y=3*((a-b)*(a+b))-x;
(d) y=1-2/3b               y=1-2/(3*b);
(e) a=-b                   a= -b;

(Rotate your Kindle to view the above.)

In (a) and (b) the * is not assumed, as it is in maths.

In (c), we are forced to use () - rather than square brackets - in every case.

In (d), if we had written 2 / 3*b without brackets , this would have divided by 3 then multiplied by b.

In (e), we have used - for negation.

To complete our look at the arithmetic operators, let us look at integer division, and the '%' remainder (or modulo ) operator. Integers may not be able to cope with very large values, but at least they are guaranteed to be accurate. If we evaluated the integer expression:
    3 / 2

and we obtained the 'float' answer 1.666667, our accuracy is suspect!

The C++ solution is to produce an integer result when dividing integers, as in:
    a = 3 / 2;        // a becomes  1
    a = 3 / 3;        // a becomes  1

Thus, any digits after the decimal point are removed.(known as truncation)

We can find what the integer remainder is by:
    a = 3 % 2;        // a becomes  1
    a = 3 % 3;        // a becomes  0

Think this is no use ? Try converting a whole number of cents into the number of dollars and the number of cents left over:

    //all variables are int
    dollars = cents / 100;
    cents_left = cents % 100;

Note that
    a = 3 % 2.0;

would be incorrect as, in C++, 2.0 is a float, not an integer.

2.6.1 Style: operators and spaces

This is a minor point. There are two styles. Firstly with no spaces, secondly with extra spaces round operators. The C++ compiler accepts either, it is a human readability issue. Here are some examples:
a = b + c * d;
a=b+c*d;

Extra spaces never hurt, unless you are programming on a very small screen.

2.6.2 Style: long lines

If a line is long, such that it disappears off the right edge, it is a good idea to 'break' it at a suitable point. You can do this at any point, but not in the middle of a name, number, or string in quotes. Here is the same line, split up for a smaller screen. Note the extra spaces of indenting in the second one, to improve clarity:
salary = gross_pay + travel + food;
salary = gross_pay +
             travel + food;

The above long line is not really long of course. Because you are viewing the book on a Kindle, I kept it relatively short. I when you program on a computer, a long line might be 80 , 90, 100 characters long. And just a reminder: turn your Kindle sideways when you see code reaching the right edge of your screen.

2.7 Type Conversion in Assignment

If i is int, and f, x are float, what might we expect from:

1.            f = 123;
2.            i = 12.67;
3.            i = x;

In fact, different languages treat such expressions in different ways. Some would suspect a possible error, and warn you. C++ accepts all the above assignments!

  1. is not serious. f becomes 123.0, i.e. a float.

  2. is potentially serious. i becomes 12. We have lost some decimal digits.
  3. is like (b), but not as easy to spot, because we have a variable instead of a number.
In short, the right-hand-side is converted to the type of the left-hand-side, even if this results in information being lost.

2.8 Constants: const

The main thing about variables is that they hold values which can change. The 'constant' feature in C++ allows us to give meaningful names to values that never (or rarely) change. For example, what does the number 2.54 mean to you? It probably has several connotations, but the idea I have in my mind is that it represents the number of centimetres in an inch. In C++ I can put

    const float inches_to_cm = 2.54;
    float cm, ins = 1.7;
    cm = ins * inches_to_cm;

Compare this with the readability of
    cm = ins * 2.45;     //error: 2.54

The above is not very readable - we have a 'magic number', which in fact I got wrong, and the C++ compiler will not warn me. It is not like miss-spelling a variable name. When the program gets larger, the const feature pays off, as it is hard for humans to spot such errors.

The const keyword also prevents us from changing the item. An attempt to change it (for example by assigning a new value) will produce a compilation error.

The number 2.54 is fixed forever, but there are other items which might need to be changed over the years - such as an email address. If this is set up as a constant, a single edit can change the address, instead of having to look through the whole code. This makes programs easier to maintain.

One common style (though not universal) is to use capitals for constants, such as METRESPERMILE.

2.9 Increment - Decrement ++ and --

. Instead of n = n+1 or b = b-1 we may put
       n++       or        b--

The incrementing (increasing by 1) and decrementing (reducing by 1) tasks are very common in programming. The main use of ++ and -- is as a complete statement, or in the for loop, covered later. There are several ways to use them ,but the most common is, for example:
    int age = 22;
    age++;           //age now 23

Key Points

Problems

(We have not yet covered how to display the results of calculations, which means that we cannot find out if our program works. We cover this in the next chapter. So, for now, do the following questions on paper, or in your head. )

Do not spend long here - move to the next chapter soon. Spoiler alert! The answers are shown after the last question.

  1. Which of the following are acceptable C++ variable names?

    dollars
    $
    my salary
    student-age
    teacher_pay
    USA_income
    silly
    companyProfits

  2. What are the final values of a, b, c after the following assignment statements?
        int a,b,c;
         a = 1;
         b = 2;
         c = 3.8;    //nb int, float issue
         a = b+c;
         a = a+1;
         b = a;
         b = a+b*10;
         c = b % 10;

  3. Here is part of a program used to calculate the volume of a box, given 3 (invented) values for its 3 dimensions. Complete it by adding the missing bits where you see ...
    float width = 1.67;
    ...
    ...
    float volume;
    volume = width * ...  ;

Answers Q1.
dollars             yes
$                   no
my salary           no - space
student-age         no  - hyphen/minus
teacher_pay         yes
USA_income          yes
silly               yes - probably meaningless
companyProfits      yes

(Turn Kindle sideways.)

Q2.

a 6, b 66, c 6

Q3.

float width = 1.67;
float height = 2.1;
float length = 1.4;
float volume;
volume = width *height * length ;

Appendix 1 - C++ Setup

Windows and Linux

On Windows, You can use a small install compiler from Borland, which works with some editors. Similarly, there is a Windows version of the Linux g++ compiler in the minGW suite, freely available.

If you want a very powerful system with visual debugging, try Microsoft's free Visual Studio Express for Windows Desktop - you will be creating console apps - but you can create GUI apps.

On GNU/Linux, there is the g++ compiler, which is there as standard.

Borland C++

On Windows, there is the free Windows Borland bcc compiler. It can be got via

http://edn.embarcadero.com/article/21205

Here is a good video about its installation:

http://www.youtube.com/watch?v=FHSA0avzLPs

Follow the installation instructions. Basically, you install the download, modify an environment variable - see below) , create 2 files, restart.

On Windows XP, add a path reference to the Environment variables by:

  1. Using the mouse, right-click on the "My Computer" icon (on your desktop) and choose "Properties".

  2. Click on the "Advanced" tab.

  3. Click on the "Environment Variables..." button.

  4. Highlight the "Path" System variable (bottom).

  5. Click on the "Edit..." button.

  6. Add this to the end of the line, being careful to add the semicolons before and after

    ;C:\BORLAND\BCC55\BIN;


  7. Click OK (in the "Edit System Variables")

  8. Click OK (in the "Environment Variables" window) and click OK (in the "System Properties" window)
Finally, restart Windows

On Windows 7

  1. Start - Control Panel - System
  2. To Advanced system settings - Environment Variables (just like xp above so far)
  3. highlight Path, click Edit...
  4. In the Variable value area, click on the current value, and scroll right as far as possible, then, being careful to add the semicolons before and after, add at the end ;C:\BORLAND\BCC55\BIN;
  5. Click ok, then click OK in all the open windows to exit.
  6. Restart Windows.

For the 2 config files, use the notepad editor, rather than typing 'edit' as Borland suggest. The files should be stored in C:\BORLAND\BCC55\BIN

The config files are:

Part 1: Creating BCC32.CFG.

1.Type (or click on notepad), 'notepad bcc32.cfg' to edit in Windows Notepad. 2. Add these lines:
-I"c:\Borland\Bcc55\include"
-L"c:\Borland\Bcc55\lib"
3. Save the changes
4. Exit notepad
Part 2: Creating ILINK32.CFG
5. type, 'notepad ilink32.cfg' to edit in Windows Notepad
6. Add these lines:
-L"c:\Borland\Bcc55\lib"
7. Save the changes
8. Exit
10. Restart Windows.

PSPAD and Borland

PSPAD is a good free editor for Windows. The setup for pspad involves using its menu options as follows:

Compiler: C:\Borland\BCC55\Bin\bcc32.exe

Parameters: %Name%%Ext%
Log File: %Name%.LOG
Run After Compilation:  cmd.exe /K %Name%.exe cnvspk.txt
Log Parser: * * %F %L:

To compile a loaded program, use ctrl F9

Note: the K option keeps the window open, and cmd.exe was added.

Appendix 2 - Reserved Words

Turn your Kindle sideways please.
alignas             enum                return
alignof             explicit            short
and                 export              signed
and_eq              extern              sizeof
asm                 false               static
auto(1)             float               static_assert
bitand              for                 static_cast
bitor               friend              struct
bool                goto                switch
break               if                  template
case                inline              this
catch               int                 thread_local
char                long                throw
char16_t            mutable             true
char32_t            namespace           try
class               new                 typedef
compl               noexcept            typeid
const               not                 typename
constexpr           not_eq              union
const_cast          nullptr             unsigned
continue            operator            using
decltype            or                  virtual
default             or_eq               void
delete              private             volatile
do                  protected           wchar_t
double              public              while
dynamic_cast        register            xor
else                reinterpret_cast    xor_eq


tailstuff