Learning To Program With C++

Getting Started


Introduction

I am writing this introductory C++ programming tutorial for the members of the Computing Club at Fernie Secondary School in Fernie, British Columbia, Canada, although it is freely available to others for their personal use.

Students will be programming on MacOS X, using the Terminal application, a text editor of their choice (I use emacs) and the gcc compiler that ships with MacOS X. Essentially, this means that we will be programming in a Unix environment. So, as the need arises, information about using the Unix environment will be introduced. There is a summary of the Unix commands that we commonly use in Appendix A Surviving Unix. There is a summary of common emacs commands in Appendix B Surviving emacs. These Appendices open in a separate browser window so that they may be kept open whilst using the rest of this tutorial.

This tutorial is (and will continue to be) a work in progress. I am writing it on a PC (running XP and Redhat Linux) because I don't have access to a Mac at the moment. Hopefully, this will not present any problems - but if you find programs listed in this tutorial that don't compile and run as they should on your MacOS X, please send me an email with "C++ Tutorial" in the subject.


Hello World!

First, we will write, compile and run a very simple program.

MacOS X is based on the Unix operating system. When you are in the terminal window, you need to enter written Unix commands at the % prompt rather than using the mouse and clicking on icons as you would in the Mac Finder application.

Open a terminal window (Go > Applications > Utilities > Terminal) and type the following entries at the % prompt. Press Enter after each command.

Terminal Window
% pwd
/Users/myLogin
% mkdir MyPrograms
% cd MyPrograms
% mkdir HelloWorld
% cd HelloWorld
% pwd
/Users/myLogin/MyPrograms/HelloWorld
%

What's happened here? The first command, pwd, tells you your present working directory. At the beginning of a terminal application, you start out in your home directory. Then you created a directory (in Unix, folders are called directories) named MyPrograms. Then you changed directory (cd'ed) to the new directory. Then you made a second directory named HelloWorld, and cd'ed into this. Now, pwd verifies that you are in the directory HelloWorld.

There are three main stages to production of a program:

  1. Write out the program in a text editor (if you use a word processor, make sure that you save the file in a text only format); this is called the source code.
  2. Compile the source code; the compiler reads the source code, checks it against the rules of the C++ language, and then produces an executable file that the computer can read but you and I can't.
  3. The program is run, or executed.

As far as we're concerned, the interesting part will be writing the source code. Our first program doesn't do very much (it just prints the phrase "Hello World!" to the screen) but it is a good way to make sure that we have everything we need to write, compile and execute programs.

Open a text editor and type in the source code below, omitting the red line numbers. Take care to type exactly what is shown below. Then save the file as hello.cpp in your HelloWorld directory. (If you're using the emacs text editor that is the favourite of many programmers, open a second terminal window and enter cd MyPrograms/HelloWorld to go directly to the directory for your program. Enter the program code and save your file with Control+X, Control+S. For more information on how to use emacs, check out Appendix B. Surviving emacs)

Program 1-01.cpp
1 #include <iostream>
2 using namespace std;
3
4 int main(){
5 cout << "Hello World!" << endl;
6 return 0;
7 }

Code Explanation
1
#include is an instruction to the preprocessor (something that runs at the start of the compilation process) to read the file that follows, i.e. include the file iostream.
iostream
is needed for the cout statement
2
using namespace std; tells the compiler which cout to use - we'll go into more detail later
4
Every C++ has a main() function. It's where the program starts.
5
cout stands for console out. It prints the string "Hello World!" enclosed in parentheses to the computer console (monitor). endl is code for a new line
6
return the value 0 if program is successful.

Now it's time for the second part of the process: compilation of the source code into an executable file. There is now a file called hello.cpp in your HelloWorld directory.

Terminal Window
% pwd
/Users/myLogin/MyProgram/HelloWorld
% ls
hello.cpp
% g++ -o hello hello.cpp
% ls
hello hello.cpp
%

The command to use the compiler is g++. The -o option tells the compiler that want to specify the name of the executable file; in this case we're specifying that the executable is to be called hello. The last argument to the compiler, hello.cpp, tells the compiler which file is to be compiled.

If the source file, hello.cpp, has no errors in it, the compiler compiles the file into the executable hello. (If there are errors, the compiler will say what type of error has occurred, and on what line in the file hello.cpp. Correct the mistake - probably a typing mistake - and run the compiler again.)

Now we can execute the program. This is done by typing ./hello at the terminal prompt. (The ./ part tells the operating system to look in the current directory for the executable file hello.) All that this program does is print the "Hello World!" message to the screen.

Terminal Window
% ./hello
Hello World!
%

That's it! You have now written, compiled and executed your first program. It's not the most exciting program, but you'll quickly be writing more demanding and interesting programs.


Some Questions and Answers

What is a program?

A program is a sequence of statements following the rules (or syntax) of C++ , C, Java, Pascal, Perl, or some other language. It is written by a programmer (you!). The programmer writes this source code with a text editor, which is just a simple word-processor with no fancy formatting capability.

The word program also may refer to the executable file that is used to run the program (like hello above). The executable is in machine code that the computer understands.


How is the source code converted into machine code?

That depends upon which type of programming language is being used.

A compiled language uses a compiler (go figure!). The compiler is a sophisticated program that converts the source code into an executable file. (It's a lot more complicated than that but that's all we need to know for now ;-) The compilation process for a large program can take some time, but the executable machine code runs quickly. This executable will run on all computers that have the same operating system as the computer where the program was compiled, so there is no need for these other machines to have a compiler of their own. But if I write and compile a program on an Apple running MacOS X, it will not run on Windows XP. To run it on XP, it will be necessary to compile it again, from the source code, with a compiler on the Windows machine. Fortunately, the same source code will/should work for both the Mac and the Windows compiler. C and C++ are compiled languages.

An interpreted language uses an interpreter (go figure, again!). The interpreter does the time-consuming conversion from source code to machine code each time the program executes, one line at a time. This can make the execution (or run time) of the program up to 100 times slower so interpreted languages are not so useful when speed of execution is important. Each machine running the code needs an interpreter. Perl and Prolog are interpreted languages.

Of course, it's not really that simple. Interpreters can be written for C++ and a compiler can be written for Perl. But C++ grew out of the language C, and C was designed to be compiled.

And then there is Java. Java is 80% compiled and 20% interpreted. Java wants to be platform-independent (that is, it wants to be able to run on Unix, Mac, Windows, etc.). Java also would like to be reasonably quick. The part of the language that does not depend on the operating system is compiled to improve speed. The remaining 20% is interpreted to allow programs to run on any machine with a Java interpreter without recompiling the program. Recent refinements to the Java language have improved its speed so that it is not much slower than some widely used compiled languages (so says James Gosling, who was the main original developer of the Java language).


 Why C++?

As mentioned above, C++ grew out of C, an extremely powerful and fast language. C++ is C with extra functionality added (that's where the pluses come from). C and C++ have the advantage that they are able to directly access bits and bytes and memory addresses in the computer hardware. (You'll learn about bits, bytes and memory addresses later.)

C++ supports object-oriented programming. This is a different way of approaching programming problems which is beneficial in large programming projects.

C++ is one of the most widely used programming languages, and is also one of the most common for first-year university courses. High school students with some knowledge of C++ will have a considerable advantage in their later studies.


Data Types

Programs manipulate data. In C++, every data item has a data type, like int (integer) or char (character). The C++ compiler needs to know what type each item is so that it knows how much space to reserve for the item in the computer's memory. (Not all data types are the same size.) The compiler also checks that you are using the correct data type for what you are trying to do; then the compiler can find errors in your program during compile time - and tell you what line the error is on so that the error is relatively simple to fix. Other languages (like Perl) that have a more relaxed approach to data types may not notice these errors. The errors won't be noticed until the program is run and it gives incorrect results. It's harder to find these errors, because you don't know what line they are on.

In C++, there are data types defined by the language. It is also possible for the programmer to define his/her own data type; we will be doing a lot of this later when we create structs and classes, but for now we are interested in the basic (called primitive) data types.

Numerical data types fall into two categories: integers and floating point numbers.

Integers are whole numbers like 42, +42, -42 but not 42.0. It might seem a little strange that 42 is an integer but 42.0 is not, when they are really the same value. But, they're not the same value as far as the compiler is concerned; they are treated differently and may require different amounts of memory to store them.

There are different types of integer: short, int, long, and char. It might seem a little strange (again!) that characters are an integer type, but each character is associated with an integer. Remember: everything in a computer is stored as a number of some sort.

Floating point numbers are numbers like 42.0, 3.14159 and 2.718. It is important to know that a float is usually an approximation of a number. This is because decimal numbers cannot always be represented accurately with binary numbers. (The same is true for decimal numbers; one third is represented 0.33333... and no matter how many 3's we add, the decimal is never exactly equal to one third.) A double is a float that is given more room in memory, and can hold larger numbers.

The bool type contains only two values, true and false. When C++ is evaluating boolean values, non-zero are evaluated as true, zero as false.

The void type is used as a return type for functions. Functions will be discussed later.

The size of these types are not defined by the rules ofs C++. They depend upon the computer and/or compiler that you are using. You can check the size on your computer with the following code:

1
#include <iostream>
2
using namespace std;
3
4
int main(){
5
cout << "short is " << sizeof(short) << endl;
6
cout << "int is " << sizeof(int) << endl;
7
cout << "long is " << sizeof(long) << endl;
8
cout << "float is " << sizeof(float) << endl;
9
cout << "double is " << sizeof(double) << endl;
10
cout << "long double is " << sizeof(long double) << endl;
11
cout << "char is " << sizeof(char) << endl;
12
cout << "bool is " << sizeof(bool) << endl;
13
return 0;
14
}
Program 1-02.cpp

Code Explanation
1
iostream is the input output stream definition.
It's needed for cout
2
using namespace std; tells the compiler which cout to use
4
main() is the entry point for the program
5
cout prints the string "short is " to the screen, followed by the value returned by the sizeof() function. endl sends a new line to the screen.
13
return the value 0 if program is successful.

The program can be compiled with the command g++ -o sizes 1-02.cpp and run entering ./sizes. This is the same approach that we took with the HelloWorld program we wrote earlier. But, if you omit the -o option for the compiler and just enter g++ 1-02.cpp, an executable named a.out is created. This is a little less typing, but the new a.out will overwrite any existing a.out executable file in the directory. This is only a problem if you want to keep the existing a.out.

Results of this program may be something like the following:

Terminal Window
% ./a.out
short has size 2
int has size 4
long has size 4
char has size 1
float has size 4
double has size 8
long double has size 12
bool has size 1
%

What does 'char has size 1' mean? In a computer, data is stored in bits. Each bit can hold either a 0 or a 1.

Two bits of memory can store 2x2 (=22) different values. These four values are 00, 01, 10, and 11. They are the binary representation for our usual 0, 1, 2, and 3 in decimal notation.

Three bits can store 2x2x2 (=23) different values. These eight values are 000, 001, 010, 011, 100, 101, 110, and 111, which are 0, 1, 2, 3, 4, 5, 6, and 7 in decimal.

Eight bits can store 28 = 256 different values, where 00000000 in binary is 0 in decimal and 11111111 in binary is 255 in decimal.

A byte is eight bits. 'char has size 1' means that a char has size one byte = eight bits. A char can hold values in the range 0 to 255. A short has size 2 bytes in computer memory. Therefore, a short can hold a range of 216 = 65536 different values.

It's a bit more complicated still! A short does not assume the full range of values from 0 to 65535. Instead, the possible numbers are split equally into positive and negative numbers. So, a short can have a value in the range -32768 to +32767. And, as if it wasn't already complicated enough, there is another type of short that we haven't talked about yet. This is the unsigned short which doesn't have any negatives. The unsigned short can assume values in the range 0 to 65535.

Confused? Don't worry - for the most part we don't need to concern ourselves too much with stuff like 216. If you think that you will use a number that won't fit in the range for a short, use an int or even a long.

Strange things happen, though, if a number goes outside its allowable range. Look at the following code:

1 #include <iostream>
2 using namespace std;
3
4 int main(){
5
6 unsigned short i = 65535;
7 unsigned short iPlusOne = i+1;
8 cout << i << " + 1 = " << iPlusOne << endl;
9
10 short j = 32767;
11 short jPlusOne = j+1;
12 cout << j << " + 1 = " << jPlusOne;
13
14 return 0;
15 }
Program 1-03.cpp

Code Explanation
4
main() is the start point for the program
6
reserve space for a unsigned short called i and give it the largest value that a short can store; this will be explained in the next section on variables
7
reserve space for a unsigned short called iPlusOne, give it the value that is in i and add one to that value
8
print out the value of i, the string " + 1 = " and the value stored in i+1
10-12
repeat with the signed int data type

The output from this program may seem a little surprising.

Terminal Window
% ./a.out
65535 + 1 = 0
32767 + 1 = -32768
%

You learned in elementary school that 65535 + 1 is definitely not 0! What's happening?

65535 is the largest number we can store in an unsigned int. When we add 1 to it, it 'overflows' and wraps around to 0 again. Let's think in decimal for a moment. Suppose that we only have three spaces to hold a digit - the largest our number can be is 999.

Now, suppose that we add 1 to this number. Elementary students will tell us right away that 999+1=1000. Correct, but there is a problem! We still only have three spaces to hold the number. The 1 in 1000 is the fourth number and gets thrown away. We're just left with 000.

The same thing has happened in our program. 65535 in decimal is 1111111111111111 (16 ones) in binary. When we add 1, the binary sum is 10000000000000000 (1 one and 16 zeros). But we still only have 16 bits of storage, and the leading one gets thrown away. That leaves just 16 zeros, which is still zero!

The same thing happens with the int but we need to know about negative binary numbers and two's complement binary arithmetic to explain it fully. And your probably sick of all this binary stuff, so we'll leave that for another day.

A char is (usually!) one byte (8 bits) long and takes values from -128 to 127. unsigned char has values in the range 0-255. A char is not usually used to store an integer; we have other types of int for that. A char is generally used to store a character. There is a relationship defined between characters and integers in the range 0-127. Some of these characters are not printable as character - things like backspace or a tab or even a bell sound. The non printable characters are in the range 0-31. Printable characters (0-9, a-z, A-Z, puntuation marks, !, $, etc.) are in the range 32-128. For more information on particular characters associated with each char integer, do a web search for ASCII (American Standard Code for Information Interchange). Or you can write a program to print them out. (We do just that when we get to writing loops!)


Variables

The programmer can store values in user-defined variables. A variable is a place in computer memory to store data. This data can be retrieved or changed later.

We've already seen variables in program listing 1-03.cpp. The statement unsigned short i = 65535; is declaring an unsigned int variable called i and assigning (giving) it a value of 65535.

Each variable has to have a type; otherwise the compiler doesn't know how much space to reserve for it in computer memory. Also, the compiler won't be able to do some of its error-checking during the compilation if it doesn't know what type the variable is.

Each variable needs to have an identifier, like i. An identifier is just a name for the variable. There are rules determining what a variable name may be. The first character must be a letter or an underscore. The following characters may be underscores, letters or digits. Furthermore, the identifier cannot be one of the words that C++ has reserved for its own use, such as int, return, ... (A list of these reserve words is available here.)

The following are valid variable declarations:

int age;
char ch;
short theResult;
long _42;
double big_number;
bool theTruth;

The following are not valid:

int my_age_is?;
short the Result;
long 42;
double float;

my_age_is? has an illegal character (the ?), the Result has a space in it, 42 starts with a number and float is a reserved word.

Descriptive variable names make a program much easier to understand. area = width * height; is much clearer than a = b * c;

Notice that we haven't give any of these variables a value yet. All that C++ requires to declare a variable is the type, the identifier and the semi-colon that C++ statements end with. However, it is good practice to give the variable an initial value when it is declared. Otherwise, we may start to use the variable without giving it a value and we don't know what is in it to start; it may just be some value left in the area of memory from a previous program. These declarations are better:

int favouriteInteger = 42;
char ch = 'A';
short theResult = 0;
long _42 = 1024;
double big_number = 9999999999999.00555;
bool theTruth = false;

When we initialise (give a variable its initial, or first, value) a variable as we declare it, we need to use an assignment operator '=' (I bet you thought that was an equals sign!) and a value of the right type. There is another way to do this, but it doesn't really have an advantage over what we can already do in a single line:

int favouriteInteger;
favouriteInteger = 42;

What's happening here? It's quite simple really. The statement int favouriteInteger; is telling the compiler to reserve some space in memory, and to refer to that space by the name favouriteInteger. The type int tells the compiler how much space to reserve. For instance, the compiler will reserve less space for a short than for a long. (Depending upon your system, short might require 2 bytes for storage and long might require 4 bytes. Remember the program we wrote using sizeof to see what the values are on the computer you are using.) Then we put a value, 42, in the space that has just been reserved by the compiler using the assignment operator '=' The statement

int favouriteInteger = 42;

does the same in one step.

The assignment operator can be a little confusing at first. It works by taking the value to the right of the assignment operator and placing it in the variable specified by the name on the left of the assignment operator. ch='A'; puts the char value 'A' into the variable named ch. The assignment operator has a strict direction associated with it. The compiler will not allow a statement like 'A'=ch;

Notice that when assigning a char, it is surrounded by single quotes.

More than one variable can be declared in a single statement. For example:

int first = 1, second, third = 9;

All the three variables (first, second, and third) are of type int, first and third are initialised (to 1 and 9 respectively) but second is not.

Variables may be declared anywhere in a C++ program, but must be declared before they are used.

Computer memory is made up of a sequence of locations, each with its own address. Each variable is given its own place in memory by the compiler. When the compiler wants to locate that variable again, it uses the address.

What happens when we make the following declarations?

char ch = 'A';
short number = 1047;

Think of apartment mailboxes as computer memory. Each apartment has its own mailbox (memory location). After the declaration char ch = 'A'; it's as though Ms. ch has moved into apartment 1004. The value 'A' is placed at location 1004. Now for the declaration int number = 1047; . Mr number requires more room (a short requires twice as much storage) so he moves into apartments 1006 and 1007. The value 1047 is split into two parts: one part fits in mailbox 1006 and the other part fits in mailbox 1007.

Suppose now that the valuable in a variable is changed:

ch = 'B';

The address of the variable ch remains fixed at location 1004 but it now holds the value 'B'

Another way to view memory is:

Thus, we have learned that a variable:

It is not allowed to declare variables with the same name that are accessible to each other; the compiler can't figure out which variable to use. So, when are variables not accessible to each other?

A statement block is a block of code enclosed in curly braces { ... }. A variable declared within a statement block is called a local variable. A local variable cannot be read or modified or modified from outside the block. The part of the program that can access this local variable is called the scope of the variable. Local variables cease to exist when the block of code in which they were declared has finished executing.

Program 1-04.cpp
1 #include <iostream>
2 using namespace std;
3
4 int main(){
5
6 int age = 18;
7 cout << "Before block, age is " << age << endl;
8
9 //create statement block
10 {
11 int age = 36;
12 cout << "In block, age is " << age << endl;
13 } //end statement block
14
15 cout << "After block, age is " << age << endl;
16
17 return 0;
18 }

Code Explanation
6
first declaration of the variable age
7
print out age; it is 18
8
start a statement block
11
redeclare the variable age. Now, inside this statement block, any references to the variable age refer to the local variable
12
print out age; it is 36
13 leave statement block
15 print out age; it is now 18 again. The local variable age within the statement block no longer exists.

Terminal Window
% ./a.out
Before statement block, age is 18
In statement block, age is 36
After block, age is 18
%

We can begin to write some fun programs now that we know about variables. (I know it's a drag, waiting to do some neat programming, but we had to learn some stuff first!)


Some Examples

Imagine for a moment that it's the end of January. It's -29oC outside, and blowing hard. You've just shovelled the snow off your driveway - and your fingers and toes are frozen. You start to think about ... Hawaii. Beaches. Sunshine. Surfing. While you are waiting for the water to boil for a hot chocolate, you stagger on numb feet to the computer and type 'Hawaii weather' into Google. It's not that easy with frozen fingers! The first link takes you to University of Hawaii Meteorology. It's 81oF. How hot is that?

In Canada, we use the Celsius scale to measure temperature. In the United States they use the Fahrenheit scale. To convert from Fahrenheit to Celsius, we subtract 32 from the Fahrenheit temperature and then divide by 1.8 to get the equivalent temperature in Celsius. We'll write an interactive program to do the conversion. (An interactive program communicates with the user; here the program asks the user to input a temperature in Fahrenheit.)

1 #include <iostream>
2 using namespace std;
3
4 int main(){
5
6 float fahr = 0.0;
7 float cels = 0.0;
8
9 cout << "Enter a temperature in Fahrenheit: ";
10 cin >> fahr;
11
12 cels = (fahr - 32)/1.8;
13
14 cout << "The equivalent temperature in Celsius is ";
15 cout << cels << endl;
16
17 return 0;
18 }
Program 1-05.cpp

Code Explanation
6, 7
Declare variables fahr, cels to hold values for temperatures
Initialise these variables to 0.0;
9
Prompt the user to enter a temperature to convert from
Fahrenheit to Celsius
10
Use cin to bring the user-defined temperature into the program.
Store the user-defined temperature in the variable fahr
(see below for more details)
12
Convert the temperature to Celsius
(see below for more details)
14,15
Write the temperature in Celsius to the screen

Line 12 needs explanation. Terms inside the parentheses (brackets) are evaluated first, so the value (fahr - 32) is calculated before the division operator, /, is applied dividing (fahr-32) by 1.8. When the right hand side of the assignment operator has been evaluated, the result of this evaluation are assigned to (or stored in) the variable cels. (Remove the parentheses, and compile and run the program again. Are the program results the same? If the result is different, why is it different?)

It's time to have a closer look at the cout and cin commands. cout (short for console out) is used together with the output operator << to write strings, constants or variables to the monitor. (A string is text enclosed by quotation marks. "Hello World!" is a string. endl writes a new line character to the screen.

1 #include <iostream>
2 using namespace std;
3
4 int main(){
5
6 cout << "This is a string." << endl;
7 cout << "6+1" << endl;
8 cout << 6+1 << endl;
9 cout << 'a' << endl;
10 cout << 'a' + 1 << endl;
11
12 return 0;
13 }
Program 1-06.cpp

Output from this program is:
Terminal Window
% ./a.out
This is a string
6+1
7
a
98
%

Code Explanation
6,
Print the string This is a string to the screen
7
Print the string 6+1 to the screen
8
Here 6+1 is not a string; there are no quotation marks
so the compiler treats these as numbers. The 6+1 is
evaluated to 7, and the number 7 is output to the screen.
9
The character a is written to the screen.
10
To add 1 to the character a, the compiler converts the
character to its integer representation (which is 97 for
the character a) so that it can be added to the number 1.
The solution of 97+1 is written to the screen.

The cin (console in) statement works with the input operator >>. cin takes input from the screen when the Enter key is pressed. cin requires a variable to store the input from the screen, such as cin >> fahr;

Imagine that you have just bought a new car. You're proudly showing off the car to Uncle Joe. He asks "How many miles does it get to the gallon?" You answer "8.3 litres per 100 kms." He looks puzzled and says, "What does that mean?" We'll write a program that converts litres/100 kms to miles/gallon - so you can give your uncle an answer!

1 #include <iostream>
2 using namespace std;
3
4 int main(){
5
6 float gas = 0.0;
8
9 cout << "How many litres per hundred kilometres? ";
10 cin >> gas;
11
12 //calculate how many litres for one kilometre
13 gas = gas/100.0;
14
15 /*calculate how many kilometres for one litre
16 note that if we use 1/50th of a litre, then
17 we get 50 kilometres for one litre */
18 gas = 1.0/gas;
19
20 //calculate how many miles for one litre
21 //1 mile = 1.6 kilometres
22 gas = gas/1.6;
23
24 /*calculate how many miles for one gallon
25 one Canadian (imperial) gallon = 4.54 litres */
26 gas = gas*4.54;
27
28 cout << gas << " miles per gallon" << endl;
29
30 return 0;
31 }
Program 1-07.cpp

Now you can tell Uncle Joe that your car gets 34 miles per gallon!

This program introduces a couple of new things. The lines in red are comments. When the compiler reads //, it ignores everything until the end of the line. Comments are used to explain what the source code is doing, and are really important to help understand the program. Comments don't just help someone reading the code; they help the programmer too. It's common to come back to a program you've written a few weeks (or even a few hours) previously and not remember how you designed part of it and comments help you understand quickly.

C++ has another method for commenting. When the compiler reads /*, it ignores everything until it reads a */, which terminates the comment. This style of commenting is not restricted to a single line.

What about gas = gas/100.0; ? It looks pretty strange if you're thinking about math. But, remember that '=' doesn't mean equals. '=' is the assignment operator. So what does gas = gas/100.0; actually do?

As before, the term to the right of the assignment operator is evaluated first. In this case, the value in gas is divided by 100. Then, this new value is assigned to the variable on the left of the assignment operator. So, if gas holds a value 78.9 to start with, this value will be divided by 100 to give 0.789. Then this value will be reassigned to gas.

In line 26, we see the multiplication operator. This line works similarly to the line 13 just described. Line 26 multiplies value in gas by 4.54.

All the calculations on gas can be combined into one line, as shown below:

1 #include <iostream>
2 using namespace std;
3
4 int main(){
5
6 float gas = 0.0;
7
8 cout << "How many litres per hundred kilometres? ";
9 cin >> gas;
10
11 gas = (100.0*4.54)/(1.6*gas);
12
13 cout << gas << " miles per gallon" << endl;
14
15 return 0;
16 }
Program 1-07a.cpp

Which of the above example is preferred? Most programmers (myself included) would choose the latter. However, an important part of programming style is to make the programming clear and easy to understand; if you find it clearer to break up a complicated statement into several simpler steps, do it!

Exercises: Now, it's your time to do something! Write programs that: