(CHAP Computers: The Basics CHAP)
Introduction
The purpose of this chapter is to provide an introduction to the considerable amount of jargon in computing. Though this book is mainly concerned with writing C++ programs, the actual use of computer systems requires the ability to understand technical literature. This comes with experience, but here a brief overview is presented. You also get to run a C++ program.
(SEC Hardware
The term 'hardware' refers to the physical and electronic parts of a computer. Here are the main components.
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 interchangable in C++.
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'.
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.
Memory and CPU. Inside the computer we have devices that deal with your programs as they run (execute). In particular:
RAM - random access memory
CPU - central processor unit.
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.
(SEC 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.
mmmMachine code (object code).nnn 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
In fact, these instructions would be stored in RAM as binary numbers, 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.
fetch deductions value
subtract them
fetch allowances value
add it
mmmThe Operating System.nnn 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 system. On tablets and cellphones we have 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.
xxFolders. 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
In the letters folder, we might have two files:
programs
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.
(SEC 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.
(SEC Setting up C++ On Your Computer
The programs in this book have been tested on Microsoft Windows 7, and the Ubuntu version of Linux (strictly, GNU/Linux.)
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.
todo replace tabs by 4 - or not need? what does export do?
(SEC 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)
Note that you would not type the line numbers at the right - they are to assist in this explanation.
#include <iostream> (2)
using namespace std; (3)
int main(void) (4)
{ (5)
cout << "Hi There" << endl; (6)
return 0; (7)
} (8)
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.
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 mmm#include <iostream.h>nnn. This is old-style C++).
After 3, we have a blank line. We can put them anywhere, to aid human readability.
Line 4 is necessary in most small C++ programs - the program actually starts running at this line.
Lines 5 and 8 are curly brackets, often called 'braces' - { }. They 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 mmmHi Therennn. When we send endl (end-line) the end-of line character is 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 check for errors you make.
Problems
Find out which operating system you have. Download and install your choice of software as discussed in Appendix 1.
Key in and run the example first program. Run it.
Edit the program so it displays your name.
Make an error in the program, and note the error message that appears. For example, you might delete a ; or a }.
(CHAP Variables And Expressions CHAP)
Introduction
Conceptually, a variable is like a box with a unique name, into which we can place a value. 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.
(SEC Numeric Variables
There are two main types of numeric variable: suu whole numbers, i.e. integers (known as xxlong in C++). The long type has an approximate range of +/- 2000 million. ii decimal numbers ( 'real' or 'floating-point' in other languages). There is a decimal point. Use xxdouble in C++. The double type has around 15 decimal places of precision, and a range of 1.7 x 10 to the power of +/- 308. If you are not hot at maths, 10 to the power of +308 is 1 followed by 308 zeros. A very large number! 10 to the power of -308 is 1 divided by this very large number. euu
The bottom line is that for everyday problems, long and double will accomodate most numbers you need to work with.
Choose long for exact, whole-number quantities, e.g: suu the number of students in a class. ii the number of locations in a computer's RAM memory. ii the number of pixels on a screen. euu
Choose double for 'decimal-point' quantities, e.g: suu your height in metres. ii average of several integer numbers. ii mass of an atom. euu (On a historical note, you will see C++ programs that use xxint and xxfloat rather than xxlong and xxdouble. They still work, but provide a smaller range and precision.)
Though you won't need them often, C++ provides some additional numeric types, not described here. Later we will encounter types for handling character data.
(SEC 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:
suu
they can contain only letters or digits, or the underscore '_'.
ii they must start with a letter. Beginning with an underscore is allowed, but not recommended here.
ii they can be as long as we like.
euu
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.
xxStyle. Look at a possible name: xxpayineuros. 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:
xxexam_mark rather than xxexammark xxpay_in_euros rather than xxpayineuros
Alternatively, we can use camelCapitals. (Trace your finger along the top of this strange word to see the hump!). We capitalise evey word except the first one, as in:
xxexamMark rather than xxexammark xxpayInEuros rather than xxpayineuros
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:
xxexam_mark or xxexamMark
rather than
xxem, xxm, xxemk. Sometimes, short names can be meaningful. Often, mathematics names such as x and y can be appropriate.
(SEC Declaring Variables
C++ insists that you 'introduce' the name of a variable before you use it. These declarations are grouped together near the top of the program. Here is an example:
#include <iostream>
using namespace std;
int main(void)
{
long exam_mark, class_size;
double height;
long VDU_size;
// then calculations, cout,etc
return 0;
}
(SEC 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.
(SEC The Assignment Statement
Here are some examples of the simplest form of assignment:
// declare a few variables for the examples
'=' should be read as 'becomes', NOT 'equals'.
long a,b,c;
double 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
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;
todo check 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 =.
todo declare and init
(SEC 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: suu + addition ii - subtraction ii * multiplication ii / division ii % remainder of integer division euu
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
suu innermost brackets ( ) first - see below.
ii * / % next
ii + - last. euu
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: todo image?
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-2a 3b y=1-(2*a)/(3*b); (e) a=-b a= -b;
In (a) and (b) the * is not assumed, as it is in maths.
In (c), we are forced to use () in every case.
In (d), if we had written 2*a / 3*b , 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 'double' 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
Thus, any digits after the decimal point are removed.(known as truncation)
a = 3 / 3; // a becomes 1
We can find what the integer remainder is by:
a = 3 % 2; // a becomes 1
Think this is no use ? Try converting a whole number of cents into the number of dollars and the number of cents left over:
a = 3 % 3; // a becomes 0
dollars = cents / 100;
Note that
cents_left = cents % 100;
a = 3 % 2.0;
todo check
would be incorrect as, in C++, 2.0 is a double, not an integer.
mmmStyle: operators and spaces.nnn 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;
Extra spaces never hurt, unless you are programming on a very small screen.
a=b+c*d;
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 + hotels - high_tax;
salary = gross_pay + travel +
food + hotels - high_tax;
(SEC Type Conversion in Assignment
If i is long, and f, x are double, what might we expect from:
(a) f = 123; (b) i = 12.67; (c) 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!
(a) is not serious. f becomes 123.0, i.e. a double.
(b) is potentially serious. i becomes 12. We have lost some decimal digits. (c) 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.
The Big Picture
We have covered sufficient detail for performing simple numeric assignment statements, but C++ has over 20 operators, with complicated rules for their use. Fortunately, many of these are used infrequently. The other classes of operator are: suu logical - used to express 'and', 'or', 'not'. ii relational - used to compare values, e.g. 'less than'. ii bitwise - used to access the binary representation of data in RAM. ii assignment '=' - yes, this is itself an operator and can be used in the middle of expressions. In fact, an assignment statement is itself an expression, and can be used in a variety of contexts. ii increment/decrement. Instead of n = n+1 or b = b-1 we may put
n++ or b--.
These operators are covered elsewhere. euu
Key Points suu Use meaningful names. ii Decide whether your variables are whole numbers or not. If so, declare them as long. Decimal-point numbers are declared as double. ii Concentrate on a few simple operators, rather than trying to learn them all. ii Expressions are used in many contexts, not only in assignment statements.
euu todo reserved words
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. The answers are on the next page. todo where?
1. Which of the following are acceptable C++ variable names?
todo list...
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?
long a,b,c;
a = 1;
b = 2;
c = 3.8; //nb long, double 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 ...
double width = 1.67;
...
...
double volume;
volume = width * ... ;
38