Lesson 1 Introduction To Programming
Lesson 1 Introduction To Programming
Introduction to Programming
Learning Outcome
At the end of this lesson, students will be able to:
1. Explain what is a program
2. List and explain the various components of a computer system
3. List the steps involved in designing and writing programs
4. Use pseudocode and flowchart in their program design
5. Conduct desk-checking of a program
6. Explain the steps in coding, compiling, and running a C++ program
7. Differentiate the different types of computer program errors
Glossary
Execution
Integrated Development Environment
If you go to an ATM machine to withdraw money from your bank account, you will come face to
face with a screen which gives you instructions for you to follow. Examples of the instruction
could be as follows:
Can you think of another example of a computer and a program which runs on the computer?
As we will see in the next section, a “computer” as we usually refer to, is actually a system
which is made up of a few components.
2.1 Hardware
A computer system basically has 5 components: input device, output device, the
processor (or better known as CPU), main memory (better known as RAM), and
secondary memory.
An output device allows the computer to communicate information to the human, such
as displaying information on a display monitor, printing out information on a printer,
producing information as a sound from a speaker, ect.
The computer’s processor and the main memory form the heart of the computer and
are usually thought of a one integrated unit.
The secondary memory is used to store a permanent copy of the information. A hard
disk is the most common type of secondary memory you will see. Other secondary
memory are tapes, disks (CD or DVD), thumb drives, etc.
2.2 Software
A software is the program that allows you to “talk” to the computer. First of all, the
computer must have a program which is called the operating system. The operating
system is a special program which was written by experts and its main purpose is to
allow the machine to interact with you. The operating system controls the computer’s
resources. If you want to run a program, you will tell the operating system the name of
the file that contains it, and the operating system will run the program. This program
which you want to run is called an application program. Application programs can be
programs which you buy, or it can be programs which you write yourself.
If you want to write a program, you must first design it. But before you can do any designing,
you must first know what it is that you want and what you want to achieve. All these are part of
a process called the software development life cycle (SDLC).
What is SDLC? When you decide to write a program, it is to solve a problem faced by a
user or to perform a certain task as required by a user. Writing a program in real life will
in many cases involve large, complex and usable software. Writing and designing the
program itself is not enough. A program, or in the case of a large and complex program
we usually call software, the story does not end with the design and the coding. The
software has a life cycle. There are six steps in the software development life cycle and
they are as follows:
In this course, we will concentrate on the first three steps; analysis of the problem,
designing the program, and writing the program code.
As mentioned in the earlier section, before you can write a good program, you must first
analyse the problem that you want to solve, and then to design the algorithm of the
program before you can write the program codes.
You have to understand the problem before you can attempt to solve it. To understand
the problem, you need to analyze it. The purpose of analyzing the problem is for you to
determine what is it that the program must to do. This is the first important step and
you must be able to determine what is task the program need to perform, and you must
specify this completely and precisely. One way that can help you get started is by
determining the output that the program must produce. In order to get an output, the
program requires input. You must determine what that input is , and how does the
program process the input to produce the output. It is important for you to remember
that a program consist of the following:
Problem:
Ali is a businessman who runs a foreign exchange bureau, exclusively for
exchange currencies from US dollars to Malaysian Ringgit. The conversion
rate between these two currencies varies daily. Ali wants a program that
would help him calculate the conversion and display it on the computer’s
monitor for his customer to see.
Let’s analyze this problem. You can start with determining the output of the program.
What is it? The output of the program is to display the amount in Malaysian Ringgit on
the computer screen. What is the input? The input of the program is the amount of US
dollar, keyed in by the user from the keyboard. And you also must have the conversion
rate. Conversion rates for foreign exchange fluctuates daily. Therefore, this information
must be given to the computer. So, this is another input which is required by this
program.
After you have determined the input and the output of the program, the next step is to
figure out the process that will take the input and produce the output that you want.
Besides the analysis of the problem, this is another challenging phase in writing a
program. This is called the problem-solving phase and the end of this phase you should
have something that is called an algorithm. An algorithm is a sequence of instructions
that leads to a solution.
Deriving an algorithm is an iterative process. After you have prepared the first version of
your algorithm, you have to check the algorithm by performing a process called desk-
checking or hand-tracing. This process requires you to execute each step of the
algorithm in your mind, or with the help of pen and paper. The purpose of this process is
to verify that the algorithm is not missing any steps and will produce the correct output.
If the algorithm does not perform as it should, then it has to be redesigned. This
iterative process will go on until the desk-checking confirms that the algorithm is
correct. After you are satisfied with the algorithm which you have derived, you may
now code your program in a chosen programming language. After you have written the
codes to your program on a computer, you may run the program, and hope that you
program will run and perform the tasks as you expected.
However, most of the time, you will find that your first few tries at running the program
will not be successful even though you have checked and rechecked the algorithm. We
will discuss why in later sections. When this happens, you will need to figure out the
reason why your program does not perform as it should, you will have to make some
changes to your codes (and maybe even your algorithm), and you will have to do this
over and over again until you get the result that you want.
The following diagram summarizes the steps that are involved in writing a program.
START
Problem definition
Testing
WORKING
PROGRAM
4.1 Algorithm
Relook at Problem 1.
Let us look at the earlier example. You want to write a program that will help user
convert US dollar into Malaysian Ringgit. You already determined the output of the
program. The output will be to display the amount in Malaysian Ringgit on the computer
screen. The input of the program is the amount of US dollar, keyed in by the user from
the keyboard. There is also a second input, which is the conversion rate. Now you have
to figure out the process that will transform the value of the US dollars into an
equivalent value in Malaysian Ringgit. In this example, the process is not very complex.
To convert the value, the computer has to multiply the value of the US dollars by the
conversion rate. We can put this information in an Input-Process-Output (IPO) table as
shown below:
4.2 Pseudocode
Start
Get value of US dollars (USD)
Get conversion rate
RM = USD x conversion rate
Display value in RM
End Program
There is another alternative to design algorithm for a program, and that is by drawing a
diagram called a flowchart.
4.3 Flowchart
Unlike pseudocode, flowcharts uses a set of standardized symbols. There are specific
symbols for input and output; symbol for processes, symbols for start and stop of
program, symbol for decision and symbol to represent the flow of the steps. There are
other symbols for other puposes, but the ones that are most common ate summarized
in the following diagram.
Start
Get
USD
Get
Conv
Rate
RM = USD X Rate
Displa
y RM
Stop
4.4 Desk-checking
When you design your algorithm, before you code them into a specific program
language, you should ensure that the algorithm is complete and that you have not
missed any steps, and that the steps are correct. To do this, you have to perform desk-
checking. Some people call this activity hand-tracing. How do you perform a desk-
check?
Before you start, you must first choose a set of input values, then you must compute or
calculate the steps manually to get the expected outputs for the set of inputs. For
example, in the currency converter problem you may choose the following set of input:
Set 2 : USD = 33
Conversion rate = 3.50
For each of the input set, you will then manually calculate the expected outcome.
Therefore, the outcome for the input sets are as follows :
Then using the input sets, by going through each step of the algorithm. You can choose
to use either the pesudocode version of the flowchart version. Let us check the
pseudocode version.
Start
Get value of US dollars (USD)
Get conversion rate
RM = USD x conversion rate
Display value in RM
End Program
To assist in the desk-checking, first create a table that contains a column for each
input, output, any temporary calculation (if necessary). For the program given
above, you will need a table as shown in Table 3.
The first instruction in the algorithm is for the user to enter the value of USD to be
converted, and the rate of conversion. Place these values in the corresponding
columns as shown in the following table.
The next instruction is to calculate the RM value based on the formula given, which
is to calculate the value of USD by the value of conversion rate. Using the table, you
will get the values that are to be calculated. So, if for example, the USD column in
the table is empty, then you know that your algorithm has missed a step. Now, since
you have the values in the respective columns, use those values to calculate the RM
value. 100 x 3.48 = 348.00, and place that value in the RM column as shown in Table
4 below.
The last instruction is to display the RM value on the computer screen. In this case,
the value 348.00 will be displayed, because that is the value that appears in the
table’s RM column. If this value is consistent with the manual calculation you
performed earlier, prior to desk-checking the algorithm, then the algorithm appears
to be correct. You should however, perform more desk checking using different sets
of input values. You must now try to conduct desk checking using the second set of
values given earlier.
With the increase of petrol prices, your friend Ahmad wants a program that will
calculate how much km per liter of petrol was consumed. For example, when starting a
journey, Ahmad will fill up his car’s tank to full and reset his car’s trip meter to zero.
After travelling 378 miles, Ahmad stopped at a petrol station to refuel. The car required
25 liters to fill up the tank. The program should calculate the number of km the car can
be driven per liter.
5.1 Algorithm
5.2 Pseudocode
Start
Get value of km driven
Get liter of petrol used
Km per liter = km driven / liter of petrol used
Display value of km per liter
End Program
5.3 Desk-checking
First choose a set of input values. Then you must compute or calculate the steps
manually to get the expected outputs for the set of inputs. For example, in the problem
given above, you may choose the following set of input:
Set 1 : km driven = 324
Liter of petrol used = 35
For each of the input set, you will then manually calculate the expected outcome.
Therefore, the outcome for the input sets is as follows:
Start
Get value of km driven
Get liter of petrol used
Km per liter = km driven / liter of petrol used
Display value of km per liter
End Program
First, create a table that contains a column for each input, output. For the program
given above, you will need a table as shown in Table 6. The first instruction in the
algorithm is for the user to enter the value of km driven, and the liter of petrol used.
Place these values in the corresponding columns as shown in the following table.
Table 6. Desk Check Table – values for km driven petrol used entered
The next instruction is to calculate the km per liter value based on the formula given,
which is to divide the value of km driven by the value of petrol used. Using the table,
you will get the values that are to be calculated. So, if for example, the km driven
column or the petrol used column in the table is empty, then you know that your
algorithm has missed a step. Now, since you have the values in the respective
columns, use those values to calculate the km per liter value. 324 divided by 35 =
9.25, and place that value in the km per liter column as shown in Table 7 below.
Table 7. Km per liter value calculated and entered in the check table.
The last instruction is to display the km per liter value on the computer screen. In
this case, the value 9.25 will be displayed, because that is the value that appears in
the table’s RM column. If this value is consistent with the manual calculation you
performed earlier, prior to desk-checking the algorithm, then the algorithm appears
to be correct. You should however, perform more desk checking using different sets
of input values.
For practice, you must now try to conduct desk checking using the second set of
values given earlier.
Programs are written using programming languages. There are many programming
languages ranging from the earlier languages such as FOTRAN, COBOL and Pascal, to
more recent languages such as C++, Java, Visual Basic, ASP, PHP and so on. These
languages are called high-level languages and they resemble English language. They are
designed that way so that it would be easy for humans to read and write in these
languages.
Besides high-level languages, there are also low-level languages and machine language.
You can try and find out more about these languages yourself. In this course, we will
concentrate on the C++ language.
Once you have decided which language you are going to use to write and later run your
program, you must learn the “rules” or the “grammar” of using the language. First of all,
you must know that each language must be written or coded in a specific way, or a
specific layout. There are some specific “statements” which you must have in your
program and it must be typed exactly as the language requires it. Let’s look at an
example of a C++ program. This program is a simple program and I will not design the
algorithm for it. This program will display the word “HELLO” on the screen. The program
looks like this :
#include <iostream>
using namespace std;
int main()
{
cout << “HELLO\n”;
system("pause"); //this statement is needed when using DEV C++
return 0;
}
This program codes can be typed or edited in any text editor such as a Notepad.
However, you can also use any C++ software development kit which you purchase or
download. The kit which contains both the editor and compiler in one integrated
environment is called an IDE or Integrated Development Environment. Examples of
these kits are Microsoft Visual Studio, Dev C ++, among others. There is one thing that
you should be aware of, which is, each IDE may have it’s own “rules”, and therefore, the
examples given here may have to be adapted to run on the IDE you are using.
Now, let’s try to understand the Hello program given above. To make it easier to refer to
the program statements, I will place the line number for each of the line in the program
codes. The program code can be saved as a file and we usually refer to these codes as
source codes.
Lines 1 and 2 are comment lines. This is indicated by the usage of the /* and */
symbols. The /* symbol indicates the beginning of a comment and the */ symbol
indicates the end of the comment line. Lines 3 and 6 were intentionally left blank to add
readability to the program codes. They do not have any effect on the execution of the
program.
Line 4, has the #include directive. Lines which start with “#” are called pre-processor
directives. The #include directive has a specific job and it must be present in your C++
program. It tells the compiler to include the contents of a particular file in the current
program. At this point of time, you only need to use the directive
#include <iostream>
What this directive does, is to ask the compiler to include the contents of the iostream
file. The iostream file must be included in any program that uses input/output
statements such as cin statement to input data from keyboard, and cout statement to
output data to the screen. C++ is a case sentitive. Which means, if you type #Include
(with a capital letter “I”), it will create an error in your program. This is called a syntax
error, which means the program (or more accurately, the compiler) does not recognize
the word “Include”.
Note: You may find that in some C++ environment, the file is specified as iostream.h
instead of iostream.. If the environment requires this, you can replace lines 4 and line 5
with the following statement
#include<iostream.h>
In many cases, you are not to include line 5. You can look at sample programs provide
by the IDE to see which style it requires.
int main()
The word main() is the name of a function. A function is a block of codes placed
between the curly brackets { and }. You know that a word is a function if it has ()
following it, such as main(). We will discuss more about functions later. In many cases,
the function main() is the beginning of the C++ program, therefore this function is
required in C++ programs. The word int preceding the word main indicates that the
function main returns an integer number. It is also possible to have a void main()
statement to indicate that the main function does not return any value. Actually the int
main() statement is called a function header. It is the beginning of a function. A program
can have only one main() function. However, there may be other additional functions in
a C++ program, as we will find out later.
The main() function is followed by the body of the function. The beginning of the body
of the function is indicated by the curly bracket {, and the end of the body of the
function is indicated by the curly bracket }. Lines 8 and 12 show these symbols
respectively. It is in the body of the main() function where the logic or the algorithm of
the program are located. In the program shown above, all the program will do is to print
the word “HELLO” on the display monitor. This is done by using the cout statement as
shown in line 9.
Line 11 contains the statement to complement the int main() statement at the
beginning of the program. This return statement simply return the value “0” to the
operating system at the end of the program. Value 0 indicates that the program has
terminated successfully. We will elaborate this return statement when we discuss
functions in later chapters.
The figure below summarizes the important points mentioned in the above paragraph :
Figure 1.
6.2 Coding a C++ program
Once we have determined the codes for the program, how do we type them into the
program and run them? For this course, we are going to use the Dev C++ IDE which
can be downloaded from the internet.
After you have downloaded the software, you can open the editor which is shown in
the following figure. You can also use other C++ IDE as mentioned earlier.
You can open a new source file where you will type the source codes given in the
HELLO program above. Figure 3 illustrates.
If your codes did not follow the correct syntax rules, the compiler will identify the
errors. However, it does not guarantee that the program will run correctly. During
execution, the program may terminate due to errors in the algorithm, and this type
of errors is referred as logical error. Another problem you may encounter is that
even though the program does not terminate, it could still provide incorrect output,
and this is also caused by error in the algorithm. In cases like these, you will have to
re examine your codes, your algorithm, and maybe even your problem analysis.
For the above program, the compilation of the codes should be successful and will
show the following response.
Once the compilation is successful, you can execute the program, and the result will
be as in the figure below.
You can now try to type in the codes for the problem which we have analyzed
earlier.
Without trying to understand the whole program at this point of time, the following
is the codes that would be written for the currency conversion problem stated
earlier.
#include <iostream>
using namespace std;
int main()
{
float usdAmount, cRate, rmAmount;
return 0;
}
After keying in the source codes into the IDE editor, you should save it in a file. Then
compile the source codes. If you get any error during compilation, check that you have
typed in each line of code correctly. If your compilation is successful, you can execute
the program. In this program, when the program is executed, it requires the value od
USD and conversion rate as inputs. You can use the values that we have determined
earlier for the desk-checking process, and once the values are entered, the program will
display the value in RM. The following figure illustrates the output of the program using
the two sets of input values given.
7.0 Problem Solving Practice
Let’s try to solve this simple problem. Let’s say you want the computer to add two numbers
which you enter through an input device, and you want the computer to display the answer
on the monitor. How would you write the instructions?
When figuring out an algorithm, you must remember that the computer does not have a
brain, and therefore must receive explicit instructions. So, in order to perform the task
stated in the above example, you will need to give instruction as follows.
First, you will ask the computer to get both numbers from the input device, add them up
and then display the answer on the answer on the monitor.
But is it practical to write the instructions in long paragraph as written above? If you have a
complex problem to solve, you may have a very long paragraph of instructions. This makes
it very difficult to read. It would be better to write the instructions as a list. So the above
paragraph can be written in a form of a list as follows :
8.0 Exercises