myvariable = 26;
myvariable
=
26
;
myvariable=
26 ;
Obviously, you wouldn’t choose to spread your statements out like that, but the compiler would still understand them even if you did. It ignores all those spaces and line breaks in unusual places, and it is very tolerant of strange program layouts. It knows where each statement ends because it comes across the semicolon. If you miss out a semicolon where it is needed or put one in where it shouldn’t be, the compiler will tell you.
namespace std;
On the other hand, there are quite a few C++ compilers that don't recognize this line at all and refuse to accept it. For simplicity, I have missed out the line from all the listings in this book. Just be aware that you may need to include it.
N.B. One line you will certainly need to include in order to access cin and cout is the line #include<iostream>. This is explained later.
C++ must contain at least one function, called main. It is set out like this:
void main ()
{
The program statements go here
}
The curly brackets are important as they indicate the start and end of the function – all the program statements making up the main part of the program go between them. The word void and the parentheses () are also important. Here is an example of a very simple program, which asks you to enter two numbers and then multiplies them. You can see the function main with its constituent parts:
Listing 1.1
#include <iostream>
void main ()
{ int first, second;
cout << "Enter first value : ";
cin >> first;
cout << "Enter second value : ";
cin >> second;
cout << first * second << endl;
}
As well as the function main in the program, there is an #include statement at the start. This tells the compiler that some of the instructions used in the program are to be found defined in another file. In this case, there are a couple of instructions called cout and cin which are defined in a file called iostream.
Functions and the #include statements are explained in more detail later. Suffice it to say that your program should start with the line #include <iostream> and should contain a function called main. If you miss out the #include statement, the compiler will come across the cin and cout statements without knowing what they mean. It will display an error message and stop compiling the program.

C++ is rather fussy about the names of variables. They must consist only of letters of the alphabet, digits and/or underscore characters (the _ symbol found on the top row of the keyboard just to the right of the 0 key). They cannot contain brackets, spaces or other punctuation, and must not start with a digit. The following are all legal variable names:
And the following ones aren’t. Can you work out why not?
One other thing to note is that variable names in C++ are case sensitive i.e. the compiler treats upper case letters (A, B, C etc.) differently from lower case ones (a, b, c etc.) so the names var1 and Var1 would be considered as referring to different variables, and the name VAR1 would refer to yet a third.
The simple variables that you will meet in this project can hold whole numbers (called integer), decimal numbers (called floating point numbers) or letters of the alphabet (called characters). When the variables are declared, you will have to tie it to one of these types, using the words int, float and char, followed by the name of the variable and a semicolon:
int age;
float h;
char initial;
This declares three variables, age which can only represent whole numbers, h which can represent decimal numbers, and initial which will hold a character (a letter of the alphabet, space or punctuation symbol). Note the semicolon on the end of each line. You can declare several variables all in one line with just one type covering all of them:
int a, b, first, last;
These four variables are all set up as integers. Variables are set to values using an equal sign:
my_age = 34;
first3 = 8.0;
initial = ‘A’;
exact_length = 0.006;
You can tell by looking at these that the variable my_age has been declared as an integer, variables first3 and exact_length have been declared as a floating point and initial has been declared as a character.
You can change the value of a variable at any time in just the same way:
my_age = 16;
my_age = -17;
my_age = 10006;
my_age = 0;
As you can see, numbers can be negative or zero. Setting a variable to a value for the first time is called initialising it. Here a variable is declared and then initialised:
float area;
area = 4.61;
You can combine these statements into one, declaring and initialising the variable at a stroke:
float area = 4.61;
int x = 480, y = -17, z = 100;
This is generally a good idea. When a variable is declared without being initialised, it contains a random number, whatever happens to be in that part of the computer’s memory at the time. You might forget to initialise the variable before you use it, in which case your program would produce an unexpected result.
float first = 1206.48, second = 347.01;
float answer;
answer = first + second – 10;
Multiplication and division take precedence over addition and subtraction:
In this case, the value of answer is 28 rather than 108, as the multiplication is done first (2 x 9 = 18) and then the addition (10 + 18 = 28). You can force the program to carry out an addition or subtraction before a multiplication or division by putting it in parentheses (brackets like these) just as in mathematics:
In this case, the program does 40 minus 4 (= 36) first, and then divides by 9 giving 4.
Here the program adds the number two and the variable temp before multiplying them by the variable var1. It then adds three to the variable temp2, divides the result by the variable x and subtracts what it gets from the previous total.
To display anything, use a standard function called cout and pass the thing that you want displayed to cout using the insertion operator (a double arrow like this: << formed simply by pressing the < key twice). Here is a statement which displays a message on the screen:
Think of this as the message being passed left (in the direction of the arrows) to cout. The message itself is called a string constant (as opposed to a variable) and is contained in double quotation marks (not single ones like character constants). You can also pass variables or mathematical expressions to cout:
int length = 10, width = 12;
cout << "The length is ";
cout << length;
cout << "The width is ";
cout << width;
cout << "The area is ";
cout << length * width;
cout << "The perimeter is ";
cout << 2 * (length + width);
Note that the variables and mathematical expressions don’t have any sort of quotation marks round them. If they did, they would be displayed as they appear here rather than as numbers. For instance, if you replaced the last line in that example with the following instruction:
You would get the following on the screen:
rather than the number 44 which is the correct perimeter. You can "chain" items together using several << symbols so that they are all displayed:
cout << "The area is " << length * width <<
"sq. cm" << endl;
cout << "The perimeter is " << 2 * (length + width)
<< "cm" << endl;
You will notice that I split each cout statement over two lines simply because they were too long to fit on one line. This doesn’t cause a problem as the compiler does not expect the end of the statement until it reaches the semicolon. That last example contained the special symbol endl which means "move to a new line". You put this symbol wherever you want the next thing displayed to appear on the next line. You can also chain endl symbols together if you want several blank lines:
cout << "3 blank lines " << endl
<< endl << endl << endl << "More text!";
An alternative to putting in endl symbols is to include the characters \n inside a string constant. The same example could be written as follows:
cout << "3 blank lines\n\n\n\nMore text!";
The symbol \n is not displayed as such on the screen, but it causes the program to move to the next line down. \n is called an escape sequence. There are others which you will meet as you go along. Here is another example, this time using variables:
cout << n1 << endl << endl << endl << (n1 + 4) * 3 << endl;
cout << n1 << "\n" << "\n\n" << (n1 + 4) * 3 << "\n";
cin >> my_try;
When the program reaches this instruction, it stops and waits for you to type in a number and press the Enter key. The number is put into the variable my_try. If my_try had been declared as a character, you would have to type a character rather than a number (and you would get an unexpected result if you type something else). Unlike cout, cin can’t be used with mathematical expressions, only entering values into simple variables.
Please note. You cannot use either cout or cin unless you put the following line at the beginning of your program:
#include <iostream>
This tells the compiler that some of the functions it will come across in the program (cout and cin in this case) are not defined inside this program, but that their definitions are present in another file, called iostream. This sort of file is called a header file and it is used like a library, containing useful routines that you are likely to need in several programs.
You may find that your compiler requires you to change this line to the following:
#include <iostream.h>
The file on the disc is called iostream.h, and some compilers prefer the full name.
switch (my_variable)
{
case 360 : cout << "First option" << endl;
age = 6 + current_age;
break;
case –24 : cout << "Second option" << endl;
cout << my_variable <<
" is negative" << endl;
age = 20 – 3 * current_age;
break;
case 1 : next_try = 7;
break;
}
The variable whose value is examined is placed in brackets after the word switch. The rest of the statement is made up of a series of clauses, each starting with the word case, the value to test for and a colon (:). These clauses are all enclosed within a pair of curly brackets.
In this case, the switch statement examines the variable my_variable (the variable in brackets). It tests to see if it has the values 360, -24 or –1 and it has a list of instructions for each of these options. If my_variable has the value 360, for example, then it displays the message First option and performs arithmetic to calculate the variable age.
Each of these lists of instructions ends with the instruction break. This means "skip the rest of the switch statement and move to the next instruction after the switch finishes." If you miss out the word break from the end of any clause, then the instruction list for that clause would run on into the next one (always assuming that clause was triggered by the variable being the right value).
If all this seems a little complicated, try typing in and running the following program. It invites you to type a number from 1 to 3 and displays a short message for each option:
Listing 1.2
#include <iostream.h>
void main ()
{ int v1 = 0, temp = 100;
cout << "Type 1, 2, or 3 and press Enter ";
cin >> v1;
cout << "temp has the value " << temp << endl;
switch (v1)
{
case 1 : cout << "You typed 1" << endl;
temp = 61;
break;
case 2 : cout << "You typed 2" << endl;
temp = 62;
break;
case 3 : cout << "You typed 3" << endl;
temp = 63;
break;
}
cout << "temp is now " << temp << endl;
}
The variable temp starts off with the value 100, but this is changed by the different clauses. Its value is displayed both before and after the switch statement so you can see any changes that have been made to it.
If you type the value 1 when prompted, the message You typed 1 appears and temp is set to 61. The break instruction forces the program to jump to the end of the switch statement. A similar thing happens when v1 has the value 2 or 3.
The last break statement (for the clause where v1 is 3) is unnecessary, since it is at the end of the switch statement anyway. Omitting this line will not affect the program in any way. Removing the other break statements, on the other hand, will change the way the program runs. Try taking them out and see what effect it has on the output.
If you entered some number other than 1, 2 or 3 for v1, then none of the clauses would be triggered. The value of temp would remain unchanged and the number 100 be displayed both before and after the switch. You can ‘mop up’ values that don’t fit any of the clauses by adding a default clause:
switch (v1)
{
case 1 : cout << "You typed 1" << endl;
temp = 61;
break;
case 2 : cout << "You typed 2" << endl;
temp = 62;
break;
case 3 : cout << "You typed 3" << endl;
temp = 63;
break;
default: cout << "That is a silly number!";
temp = 1000;
}
The default clause, if included, must always be the last clause of the switch statement since it triggers automatically if the program reaches that point. As such, it doesn’t need a break instruction. In this case, the default is triggered by entering any number other than 1, 2 or 3.
The values tested for in the switch statement needn’t be in any order, nor do they have to cover a solid range of values with no gaps (just look at the way the numbers were spread out in the first example). In fact, they needn’t be numbers at all:
switch (middle_initial)
{
case ‘M’ :
case ‘m’ : cout << "I bet your middle name is Mike!"
<< endl;
break;
case ‘L’ :
case ‘l’ : cout << "The same as mine!" << endl;
break;
default : cout << "Some other middle name!" << endl;
}
In this case, the variable middle_initial is a character variable and it is compared with character constants. This example also shows how to make two or more constant values activate the same list of instructions. In this case, both the values M and m will produce the same result.
Listing 1.3
#include <iostream>
void main ()
{ int v1 = 0, temp = 100;
cout << "Type 1, 2, or 3 and press Enter ";
cin >> v1;
cout << "temp has the value " << temp << endl;
cout << "You typed " << v1 << endl;
temp = 60 + v1;
cout << "temp is now " << temp << endl;
}
switch (x)
{
case a: cout << "x matches a" << endl;
break;
case b : cout << "x matches b" << endl;
break;
}
In order to test this, you will need to incorporate it into a program, declare the variables needed and set them to appropriate values.
Listing 1.4
#include <iostream.h>
void main ()
{ int x = 0, y = 0;
cout << "Please enter a value for x ";
cin >> x;
cout << "Please enter a value for y ";
cin >> y;
cout << "The value of (x + y)(x + 2y) is "
<< (x + y) * (x + 2 * y) << endl;
}
What value should be displayed when 6 is entered for x and 7 is entered for y? What difference would it make if the brackets in the last cout statement were removed? Predict what the values should be, then type in the program and run it to see if you are correct. Now predict what would happen if you ran the program and entered other values. Then run the program and see if you are correct. The numbers you enter can be negative or decimal. Of course, if you want to enter decimal numbers, there’s another change you will have to make to the program. What is that?
int a = 6, b = 4, c = –30;
cout << a + (b – c) * 5 / 2;
What figure would be displayed on the screen as a result of running this code? How would you adapt this code so that the user could decide what the values would be for a, b and c?
float a = 30.5, b = a + 10.1, c = b * 2 + 3;
Listing 1.5
#include <iostream>
float val1, val2;
void main()
{ cout << "Please enter first number ";
cin >> val1;
cout << "Please enter second number ";
cin >> val2;
val1 = val2;
val2 = val1;
cout << "First number is now " << val1 << endl;
cout << "Second number is now " << val2 << endl;
}
One meter is 100 centimeters, so to convert from meters to centimeters, you should multiply the figure by 100 (6m = 600cm, 2.71m = 271cm etc.) It should be fairly straight-forward to get the user to enter a number, multiply it by 100 and then display the result.
include <iostream>
int meters, centimeters;
main ()
{ cout "Please enter the length in meters : ";
cin << meters;
centimeters = 100 x meters;
c out << "The length in centimeters is <<
centimeters << endl;
int meters, centimeters;
This works perfectly providing you’re only interested in converting an integer number of meters. If you enter a decimal value for the number of meters, the program won’t crash, but it will produce a daft answer. Why is the answer wrong and what single word must be changed to correct it?
The value entered should no longer be put in a variable called meters or centimeters as we don’t know in advance which of these it will be. Instead, store the value entered in a variable value and the converted value in another variable called answer.
The actual conversion will follow the following pattern:
This pattern translates directly into a switch statement. You should adapt the program that you created in Task 2 accordingly. The character variable containing the type of the initial unit (C or M) will need to be declared, of course. Don’t forget the break statement at the end of each clause of the switch statement. A common cause of programs producing bizarre results is a missing break statement.
In fact, the easiest thing to do is to duck the question. If a quantity is provided in centimeters, convert it to both inches and meters and display both answers. Here is part of a switch statement that will do the job:
switch (initial_unit)
{
case ‘M’: meters = value;
centimeters = value * 100;
inches = value * 39.21;
break;
I haven’t given a complete switch statement – that’s your job. The variable initial_unit is the character variable which indicates what unit the typed-in quantity was (‘C’, ‘M’ or ‘I’). You may wonder where that figure of 39.21 came from. That’s the number of inches in a meter, so 1 meter becomes 39.21 inches, 9.3 meters becomes 9.3 x 39.21 = 364.65 inches etc.
The first variable assignment also deserves a mention. The initial quantity has been entered into a variable called value. Since this clause of the switch statement is activated when the user has entered a length in meters, then the value of value can be copied straight into the variable meters (no conversion is necessary). By the time the switch statement finishes, whatever the initial unit was, the variable meters will hold the length in meters, centimeters will hold the length in centimeters, and inches will hold the length in inches. It is a simple matter to display these results with the appropriate messages.
Coming up with the other parts of the switch statement will require a bit of jiggery pokery. The crucial thing to remember is that 1 meter is 100 centimeters and that 1 inch is 2.55 centimeters. This means that converting from centimeters to inches is fairly straight-forward (divide by 2.55), as is converting from inches to centimeters (multiply by 2.55).
But what about converting between meters and inches? One possibility is to go via centimeters, so converting from meters to inches would mean multiplying by 100 and then dividing by 2.55 (equivalent to multiplying by 39.21, which explains the conversion factor in the code segment above):
inches = value * 100 / 2.55;
inches = value * 39.21;
These statements effectively carry out the same calculation. In principle, any unit can be converted to any other unit provided it can be taken through an intermediate one where both the necessary conversion factors are known.

Your one complex switch statement can now be replaced by a much simple one:
switch (initial_unit)
{
case ‘M’ : centimeters = value * 100;
break;
case ‘I’ : centimeters = value * 2.55;
break;
case ‘C’ : centimeters = value;
break;
}
meters = centimeters / 100;
inches = centimeters / 2.55;
The ‘C’ clause in the switch statement does not involve any conversion as it is only activated when the original value was given in centimeters to start with. Now adding any unit to the program is a lot easier. You simply have to put in one clause in the switch statement that converts the value from that unit to centimeters and put one line after the switch statement that converts from centimeters to that unit.
int x;
cin >> x;
cout << x;
This declares an integer, x, gets you type in a value and then displays it. If you enter 6.1, it will be stored (and displayed) as 6. If you enter 72.9999, it would be stored as 72 (not rounded up to 73).
By now, you will also know that statements such as this:
float x = 3.1, y = 2 * x – 10.8;
Are perfectly legal. The variable y can be declared in terms of variable x because the compiler already knows what the value of x is. In this case, the value of y becomes 2 x 3.1 – 10.8 = –4.6. If the variables were declared the other way round,
float y = 2 * x – 10.8, x = 3.1;
it would cause an error. The compiler comes across the reference to x without having met the definition of x. Whoops!
In fact, the C++ compiler seems tolerant to a fault about declarations. Neither of these two declarations would cause an error:
int first = 0.06219;
float second = 40;
The second line shouldn’t cause any eyebrows to rise. After all, float is just as capable of holding whole numbers as int. The variable first on the other hand, will be stored as a whole number, and rounded down to 0.
You should also have found that C++ does not permit you to use variable names for the triggering values in clauses of switch statements. It will only allow you to use constant values (such as 43 or ‘D’ or arithmetic expressions that lead to constant values (such as 2 * 3, which the compiler knows is 6).
The program that you have constructed only converts lengths. However, the same principle can be applied to any quantity, such as weight (grams, kilograms, pounds and ounces) or time (seconds, minutes and hours). Each one will require its own switch statement, and all of these will have to be enclosed within a large switch statement that selects between the different quantities themselves. The whole thing will look rather clumsy – switch statements within other switch statements – and, in fact, the whole thing would be a lot easier to implement using a programming concept called functions, but that’s a subject for the next project ...

This tends to happen when you have missed out semicolons between program statements. We tend to put these at the end of lines, but as long as there is a semicolon between the statements, the compiler is happy. Here are three versions of the same code samples, all of them legal:
| cout << x; cout << y; |
cout << x ; cout << y; |
cout << x ;cout << y; |
This on the other hand causes an error:
cout << x
cout << y;
However, it isn’t until the compiler reaches the ‘c’ of the second statement that it realizes that there’s no semicolon present, so that’s the point where it signals the error.
If ever the compiler flags an error on a certain line of your program, and you can’t find any errors at that point, check the next few and the previous few lines. The compiler may have ground to a halt at some point other than where the error is.

cout << "Please enter the divisor ";
cin >> divisor;
answer = 10 / divisor;
This works perfectly when the number entered is anything other than zero. If you enter zero, the program collapses (try doing 10 divided by 0 on a calculator and you’ll see what I mean). There’s no way that the compiler could have foreseen what you were going to enter, so it couldn’t have spotted the error.

It could be due to the way the computer stores the numbers in memory. Computers have difficulty storing decimal values such as 1/3 or 1/10 in memory. They use a number system called binary and in binary, both the decimals shown are recurring numbers that would go on for ever if they could, but are chopped off after a certain number of digits in memory. The missing parts are what cause the inaccuracies. There’s not a great deal you can do about them, I’m afraid!