Chapter 1
Chapter 1
Programming a Computer
A computer is a device which processes information according to instructions it has been given. A
program is a set of instructions given to a computer. The activity of writing instructions for a computer is
called programming. Computer programs are written using programming languages such as C, C++, Java,
Pascal, and Visual Basic. Thus, writing a computer program basically involves telling a computer what to
do, using various types of statements provided in a programming language. In this chapter, we first
describe how a computer is organized and then explain how a program can be written to instruct the
computer to perform a certain task.
All computers have the same basic internal organization, built around an input—processing—output
model. Computer hardware refers to the physical computer equipment, such as the keyboard, the
mouse, the monitor, the hard disk, and the printer. Computer software refers to the programs that
cause the computer to perform different tasks.
Figure 1.1 shows the internal organization of a computer. Each component is briefly described below.
Internal External
Memory Memory
Control Unit
Input Output
Device Arithmetic and Device
Logic Unit (ALU)
1
CPU
The CPU is the Central Processing Unit or processor. It consists of the Control Unit and the ALU.
The CPU is contained in a single integrated-circuit chip, which contains millions of components
in an area smaller than a postage stamp.
Control Unit
The Control Unit controls all the activities within the CPU. It accepts input values (from an input
device) and stores them in memory. It also interprets the instructions in a computer program. If
we wanted to perform a calculation, the control unit retrieves the values needed for the
calculation from memory and sends them to the ALU. The ALU performs the calculation and
returns the result to the Control Unit which then stores it in memory.
ALU
The ALU is the Arithmetic and Logic Unit. It performs all the arithmetic and logic functions in a
computer such as addition, subtraction, comparison, etc.
Input Device
Input devices are used to get information from the user into the computer’s memory. There are
many kinds of input devices. Some of the most common include keyboard, mouse, scanner, and
microphone.
Output Device
Output devices are used to communicate the results of processing back to the user. Some of the
more widely used output devices include monitor, printer (e.g., laser printer and ink-jet printer)
and speakers.
Internal Memory
This includes Random Access Memory (RAM) and Read Only Memory (ROM). Internal memory is
used to store data. RAM is volatile, so as soon as the electrical power is cut off, all the data is
lost.
2
External Memory / Secondary Storage Devices
Secondary storage devices are used to provide an abundant storage space for programs and
data. Examples are hard disk drives (C drive in PCs) and flash drives. Data are generally stored in
these devices as files, which are not volatile. The term “save” is used to denote the act of
copying data in memory to a non-volatile file in secondary storage. Although files are not
volatile, they can be changed from time to time or be removed forever (this is referred to as
deleting a file).
Computers are built to execute instructions. The range of instructions that can be executed by a
computer is referred to as that computer's instruction set. Different computers have different
instruction sets.
A binary digit or bit is the smallest unit of storage in a computer system. A bit can either be '1' or '0'
corresponding to the electrical states of on or off, respectively. An instruction consists of a string of bits
called a word that directs the computer to perform a certain operation. For example, the following
instruction may direct the computer to add two numbers, where the leftmost part represents "Add" (the
operator), and the two rightmost parts are the numbers to be added (the operands):
It is very difficult to write programs using strings of 1's and 0's. It is also highly prone to error. An
improvement over this is to use symbols for the operators and operands, e.g., ADD = 1001, A = 101011,
B = 111010. When this is done, the above instruction can be written as:
ADD A B
However, programming is still tedious and prone to error. Programs written using strings of 1's and 0's
or equivalent symbols are said to be written in low-level programming languages. They cannot be easily
transferred from one type of computer to another since different computers have different instruction
3
sets. For example, the code "1001" given to the ADD operator above might represent the MULTIPLY
instruction in another kind of computer.
A high-level programming language is oriented towards solving problems, rather than towards the
instruction set of a specific type of computer. There are many high-level programming languages which
are commonly used today such as C, C++, Java, Python, and Visual Basic. Each language consists of a
grammar (set of rules) and pre-defined words for writing instructions (i.e., programming) in the
language. A program written in a high-level language is called a source program and the programming
statements in the program are referred to as source code.
#include <iostream>
int main () {
cout << "Hello World of Computer Programming!";
return 0;
}
The source code of the program must first be typed into an editor using characters from the keyboard.
The program should then be saved to a file in external storage so that it will not be lost when power is
turned off. The above program should be saved to a file called HelloWorld.cpp. The “.cpp” extension is
normally used for files containing C++ source code.
Earlier, it was mentioned that computers only understand machine level instructions expressed as a
string of bits. The HelloWorld.cpp program written in the C++ programming language consists of a set
of characters typed at the keyboard. So, how is it possible to get from the C++ source program to an
equivalent set of machine-level instructions, known as the object code? This task is achieved by a
4
compiler which translates the source code into object code. The compiler is itself a computer program
that accepts as input a source program and after translation, produces the object code as output.
In this book, we will assume that you are using an Integrated Development Environment (IDE) to write,
compile, and execute the C++ programs in this book as well as your own programs. A popular IDE that
you could use is the Dev-C++ IDE. It contains an editor for typing the source code of a program,
compiling the source code into object code, and running the object code. There are other IDEs available
that can be used to develop C++ programs such as Code::Blocks and Microsoft Visual Studio®.
If compilation of HelloWorld.cpp is successful, the compiler produces the equivalent object program,
HelloWorld.exe (also called the executable program). The compiler will not produce the object code if
there are errors in writing the source code. These errors are called syntax errors. They are caused when
you write statements that do not conform to the rules of the C++ language. If your program contains
syntax errors, the compiler will give a list of the lines with errors and a description of each error. These
errors must be corrected before the object code is produced. When correcting syntax errors, it should
be noted that an error in one statement can often lead to several syntax errors later in the source code.
On many occasions, these subsequent errors can all be fixed by correcting the first error.
Figure 1.2 shows the process of translating the source code to object code. After the object code is
produced, it must be executed to achieve the desired functionality of the program.
5
When the HelloWorld program is executed, the following output is displayed on another window:
“cout” stands for “Console Output”. The cout statement in the HelloWorld program instructs the
computer to display the string, “Hello World of Computer Programming!” on the “console” or window.
The program can be modified by inserting another cout statement to display the second string, “Here I
come!”, after the first one, as follows:
#include <iostream>
int main () {
cout << "Hello World of Computer Programming!";
cout << "Here I come!";
return 0;
}
Save this program to the file HelloWorld2.cpp. Now, let’s compile and run the program. We get the
following output:
This is not what we wanted. We wanted the second string to be displayed on a new line by itself. This
can be accomplished by telling the cout statement to go to a new line, before displaying the second
string. To go to a new line, the endl keyword (“end line”) can be used:
6
The program then becomes:
#include <iostream>
int main () {
cout << "Hello World of Computer Programming!";
cout << endl;
cout << "Here I come!";
return 0;
}
Let’s compile and execute the HelloWorld2 program again. We now get the desired output:
The instructions in a computer program are executed in sequence based on the order in which they
appear in the program. After one instruction in a program is executed, the computer goes on to execute
the next instruction in the sequence.
Let’s look again at the HelloWorld2 program from the previous section. When compiled and executed,
the program produces the following output:
Observe that the cout statements are executed in the order they are written in the source program,
starting from the top.
7
Suppose that the cout statements are written in reverse order like this:
#include <iostream>
int main () {
cout << "Here I come!";
cout << endl;
cout << "Hello World of Computer Programming!";
return 0;
}
When compiled and executed, the program generates the following output:
Here I come!
Hello World of Computer Programming!
This is because the cout statements are executed in the order (or sequence) in which they are written.
In general, the statements in a computer program are executed sequentially, starting from the top. An
important aspect of computer programming is determining the right sequence of instructions to use in
order to produce the desired results.
The programs that will be discussed in this book have a basic structure as follows:
#include <iostream>
int main () {
Program Statements
return 0;
}
The highlighted statements are common to all the programs in the book. These statements can be
placed in the file, Template.cpp, and used as a starting point for any program you have to write. So,
whenever you have to write a program, make a copy of Template.cpp and write the program
8
statements that will solve the problem. Of course, these statements will be different for each program.
The highlighted text in Template.cpp will be explained later in the book.
The HelloWorld2 program contains 11 lines of source code, three of which are completely empty. What
is the purpose of these blank lines? Also, you will notice that all the statements within main are indented
by the same number of spaces. Why is this necessary? Consider what would happen if the program was
written as follows:
#include <iostream>
using namespace std;
int main () {
cout << "Hello World of Computer Programming!";
cout << endl;
cout << "Here I come!";
return 0;
}
When this program is compiled and executed, it produces the same output as the HelloWorld2
program from the previous section. However, the previous version of the HelloWorld2 program is much
easier for human beings to read.
The term white space refers to the blank lines in a program as well as the spaces that are used to indent
statements. White space is used to improve the readability of source code. It is ignored by the compiler
so it has no effect on the object code produced.
Programs often contains thousands (and sometimes, millions) of lines of source code. After a program
goes into operation in an organization, changes to its functionality may be requested and errors may
surface from time to time. The person/s who wrote the program may no longer have responsibility for
that program or may no longer work at the organization. It is therefore important for the source code to
be readable so that changes can be made in an efficient manner.
9
1.9 Exercises
#include <iostream>
int main () {
cout << "Hello!";
return 0;
}
Do you think this program will compile? If not, why not? If you think the program will not compile,
how can it be fixed?
2. Write a program to display your name on one line, your telephone contact on a second line, and
your email address on a third line.
3. Write a program to display the translation of the following words from English to Spanish on the
monitor:
English Spanish
dog perro
cat gato
horse caballo
cow vaca
computer computador
Centigrade Fahrenheit
========== ==========
-40 -40
0 32
10 50
20 68
30 86
40 104
10
5. Write a program to display the following pattern of stars (asterisks) on the monitor:
**********
*********
********
*******
******
*****
****
***
**
*
6. Write a program to display the following pattern of stars (asterisks) on the monitor:
***********
*********
*******
*****
***
*
11