1 Chapter 1
1 Chapter 1
In order to solve a given problem, computers must be given the correct instruction
about how they can solve it. The term computer program refers to the instructions
that tell the computer what to do. Computer requires programs to function, and a
computer program does nothing unless its instructions are executed by a CPU.
Computer programming (often shortened to programming or coding) is the process
of writing, testing, debugging/troubleshooting, and maintaining the computer
programs. Writing computer programs means writing instructions that will make the
computer follow and run a program based on those instructions. A computer
program usually consists of two elements:
Data
Instruction
Computer program (also known as code) is often written by professionals known as
Computer Programmers (simply programmers). Code is written in one of
programming languages. A programming language is an artificial language that can
be used to control the behavior of a machine, particularly a computer. Programming
languages, like natural language, are defined by syntactic and semantic rules which
describe their structure and meaning respectively. The syntax of a language
describes the possible combinations of symbols that form a syntactically correct
program. The meaning given to a combination of symbols is handled by semantics.
Many programming languages have some form of written specification of their
syntax and semantics; some are defined only by an official implementation. In
general, programming languages allow humans to communicate instructions to
machines.
1
This is the very first stage in any program development. Knowingly, or
unknowingly every programmer goes through this step.
In this stage, the main thing to do is to understand the given problem. Problem
identification simply means understanding what to be done. Ask yourself this
question:
What must I do?
What is it that is needed or expected?
Specifically, the things that should be known at the end of this stage are:
i. Identifying input data to the problem
ii. Identifying output data from the problem
iii. Identifying procedures needed to achieve the result.
Note that, in this stage the thing that must be worked out is what must be done
not how to do it.
2. Algorithm Design
When you pass to this stage, you have all the information about what to be
done. But you still don’t think about how to do the specified thing. This is the
purpose of this step.
Programs are the children of algorithms. If the algorithm is not correct or not
efficient, then the program will also be inefficient and incorrect since programs
are the direct translation of algorithms in programming languages.
Therefore, to make your program of good quality, you must design the algorithm
carefully. And it is advisable to test the algorithm (instead of the program) to
check for reliability, maintainability and efficiency.
Since an algorithm is set of steps to perform the thing that is defined in the
previous stage, it should be represented in one way or another to be available
and be a program in the next step. Algorithms could be represented in different
ways. You might use the narrative way (writing the steps in English), pseudo-
code (‘false code’) or flowcharts.
3. Coding or Implementation
Right now, the algorithm is available. You know how to achieve the goal specified
in the problem identification stage. But the steps represented in the previous
phase are not still in the form understandable for the computer. Therefore, it is
necessary to rewrite the steps of your algorithm by using instructions in the
selected programming language. This process is called coding.
4. Testing and Debugging
You must be very lucky if your program works perfect at its first completion. But
it is not also fair to complain about the unlucky situation of a program’s fail at its
first completion because it is a usual thing to happen.
Therefore, it is more than necessary to test a program for all possible inputs
including invalid and extreme cases. If a program cannot perform as expected,
then the program is said to be having errors. Errors in programs are usually
called bugs. Whenever, there is a bug, you need to remove it until your program
is error free. Removing bugs is called debugging.
There are three types of errors that probably be encountered in a program:
a) Syntax errors:
Syntax is the general format of writing a command (statement) in
programming languages. Syntax errors are errors created due to the
violation of the syntax of a command or a statement.
Example: In C++, at the end of each statement (command), there should
be a semicolon. This is one of the grammatical rules in C++. If
you miss a semicolon at the end of a statement in C++
program, then it will be a syntax error.
If there are any syntax errors in C++, then they will be detected and
notified in the compilation time. Therefore, a program having a syntax
error could not be run without removing the errors.
2
b) Run-time errors:
These types of errors are errors that will appear when the program is
allowed to run.
Example: division by zero. If there is any place (instruction) which
attempts to divide any number by zero, then this error will not
be syntax error instead run time error. When the computer
reaches and executes this instruction, it will find out that this is
invalid and the execution will be interrupted by announcing the
error.
c) Logical Errors:
These are the most dangerous errors. These errors are errors which cause
the program to produce a wrong output. Logical errors cannot be detected
in the compilation time as well as in the run time. It is the programmer’s
job to test the program for such types of errors by providing all the
possible inputs and check whether the outputs are the expected ones.
Debugging (particularly for logical errors) can be done in different ways:
Manually: Before entering the program instruction into the computer, the
programmer can trace the program by checking each and every
instruction and by recording the values (outputs) of each instruction.
Tools included in the compiler: most compilers have got debugging tools
which show you how each instruction after being executed affects the
values of your variables and outputs.
5. Maintenance
Writing program for a given problem is an endless task. At the end of the day, you
might find undiscovered errors in the above phases or otherwise users may come up
with a new need. Therefore modification is expected even after finishing and
implementing the program. Modifying programs to make them error free (more!), to
satisfy user’s need, or to expand the capability of the program is called
maintenance.
To make programs easier to modify, documentation play a major role. Starting from
the first step, documentation should be done.
A typical document may contain the following about a developed program:
A statement of the problem
A description of the system, which involves the description of program
functions and the system specifications
A description of the program which involves program flowcharts, program
listings, test data and results.
Instructions for installing and running the program.
1.2.1. Algorithms
Before a program is written, the programmer must clearly understand what data are
to be used, the desired results, and the procedure to be used to produce the results.
The procedure, or solution, selected is referred to as an algorithm. An algorithm is
defined as a step-by-step sequence of instructions that must terminate and describe
how the data is to be processed to produce the desired outputs. Simply, algorithm is
a sequence of instructions. Algorithms are a fundamental part of computing. There
are two commonly used tools to help to document program logic (the algorithm).
These are Pseudocode and flowcharts.
1.2.2. Pseudo-code
A pseudo-code is a kind of structured English for describing an algorithm. The steps
of the algorithm will be represented using English phrases without the use of any
specific programming language.
When designing an algorithm for a given problem, the designer is advised to use a
pseudo-code so that he/she could be able to focus on the algorithm or the method of
solving the problem instead of worrying to write instructions in the correct syntax of
a particular programming language. Moreover, once an algorithm is represented,
3
coding will be translating the steps written in the pseudo-code in one of the
programming language. We can say if a well-written algorithm is prepared the
challenge of programming is defeated.
There is no standard for pseudo-code writing. You may see different ways of
pseudo-code representations in different books. Even you can develop your own way
of writing pseudo-code for an algorithm.
But, there are some useful points that you have to know to start writing pseudo-
code. There are three basic constructs for flow of control from which any algorithm
is implemented. Therefore a pseudo-code may be made up of these three logic
structures. They are:
1. Sequence
Sequence structures show the processing of steps one after the other
sequentially. Whenever there are any series of steps, they will be represented in
pseudo-code by writing one after the other in their right order just like the
following illustration:
Step 1
Step 2
Step 3
.
.
.
step n
2. Selection
Selection happens whenever there are things to be done based on the being true
of a certain condition. There will be usually two or more choices. This one is
illustrated as:
If condition1 then
Sequence 1
Else if condition2 then
Sequence 2
. The indicated part (by the
. brace) is optional meaning it
.
may appear or not.
Else
Sequence n
End if
3. Iteration (Loop)
This condition refers to a situation in which there are one or more instructions
which should be performed several times depending on some condition. This is
what we call loop.
Loop is implemented in pseudo-code like the following (i.e. of course one way)
While condition
Sequence
End while
Additionally, the following keywords are common:
a) To accept input value
Read, Get
b) To show an output value
Write, Display or print
c) To perform calculation
Compute, Calculate
d) To initialize variables
4
Set
e) To add one to the value of a variable
Increment
Moreover, the keywords ‘Begin’ and ‘End’ can be used to show the beginning and
the end of the algorithm.
Note that indentation will also play a major role in making the represented algorithm
readable and easily modifiable. When you start a different sequence, indent the
steps to differentiate the set of the steps in this sequence from the previous one.
Examples:
Design an algorithm for solving the following problems. Represent the algorithm in
pseudocode.
1. Add two given numbers.
Pseudocode can be completely formed from only English phrases or alternatively
English phrases and code like statements can be mixed in a pseudocode. For this
problem both types are shown below. But for the other examples, the second
form is used to implement the pseudocode.
Begin
Read the two numbers Completely described
Compute the sum by adding the numbers in English phrases
Display the sum
End
Begin
Read a,b The second style consisting of keywords,
suma+b
Display sum
operators and sometimes English phrases
End
Try to see how the steps are clear. For this problem, the only thing that is left is to
rewrite the steps in the selected programming language. In C++, the following
program could be produced from the above pseudocde:
#include <iostream.h>
main()
{
int a,b,sum;
cout<<”Please enter the two numbers”; //To ask the user for the two numbers
cin>>a,b; //To read the numbers
sum=a+b; //To add the numbers
cout<<sum; //To display the sum
}
Don’t worry if you don’t really understand the above program since it is not the right
time to complain. This program is just here to show you how a program in one
programming language could be produced from a pseudo-code.
2. Produce the result of the following computation for four given numbers
a,b,c and d. Result=(a-b-c)+d
Begin
Read a,b,c,d
Result (a-b-c)+d
Display result
End
3. Change a value in Km to a value in m.
Begin
Read ValueInkm
ValueInm ValueInkm*1000
Display ValueInm
End
5
4. Find the average of three numbers.
Think about the given problem. How would you find an average of three numbers
if you are asked? Are you going to ask your friend to do it for you? The method is
very simple: Add the three numbers and them divide the sum by 3. Therefore,
the following will be the pseudocode representation of this algorithm:
Begin
Read a,b,c
Average (a+b+c)/3
Display Average
End
5. Find the largest of three given numbers. Take the assumption that the
numbers entered will never be equal.
A number of algorithms can be designed for this problem. Please try to design
your own algorithm before going through the next one.
Begin
Read a,b,c
max a
if max<b then
max b
end if
if max<c then
max c
end if
Display max
End
6. Find the average mark of a student for given four subject marks.
This is not really a different question than Q.No.4. Therefore it will be done like
the following:
Begin
Read mark1,mark2,mark3,mark4
sum mark1+mark2+mark3+mark4
Average sum/4
Display Average
End
7. Obtain average marks for five students for given four subject marks.
This problem and the above one are basically the same. The only difference
between the two is that in the first case, we had only one student where as in
this problem we have five students for whom the same task to be done. What
are we going to do to treat this problem?
One way (may be foolish way) is to repeat the instructions for all of the five
students resulting to have 20 steps (later to be instructions) in the algorithm.
What if we have 100 students? Is this method really feasible?
Therefore we use a loop for such cases. A loop refers to set of instructions, which
will be repeated for a number of times based on some condition. Since we have
five students here, the loop should run for four times. How can we implement
this?
Let’s first start by writing the steps using English phrases:
Begin
While there is still a student
Read the four marks of the student
Compute the sum by adding the mark values
Compute the average by dividing the sum by 4
Display the Average
End of the while clause
End
‘While loop’ is going to be used in implementing the above algorithm. How do I
tell the ‘while loop’ that there are five students and it should run exhaustively for
five times? Even how will I stop the ‘while loop’?
6
‘While loop’ needs an initialization in which the condition is going to be based on.
A certain variable will be initialized to count the number of times the loop is run.
Usually the counter must be initialized to 1 to start counting the loop from 1.
The pseudocode representation of the above algorithm is presented below:
Begin
counter1
while counter<=5
Read mark1,mark2,mark3,mark4
sum mark1+mark2+mark3+mark4
Average sum/4
Display Average
countercounter+1
end while
End
The above algorithm will be executed like the following:
The first step is to assign the value 1 to a variable called ‘counter’. This is the
initialization process. The value of ‘counter’ is going to be used for counting the
loop. The loop is started now. All loops have a certain condition to be tested. In
our case, the condition is set to check whether the current value of the variable
‘counter’ is less than or equal to 5. If this condition is evaluated to true, then the
instructions found within the loop will be executed for one more time. If the
evaluation of the condition is false, then the loop will be stopped and the very
next instruction after ‘end while’ will be executed. Once a loop is stopped, it will
never be returned back.
Success to start
Begin the loop once
Checking counter1 again because
the the condition
while counter<=5
possibility stated is true
Read mark1,mark2,mark3,mark4
to add one
more loop sum mark1+mark2+mark3+mark4
Average sum/4
Display Average
countercounter+1 Otherwise, when
end while the condition is
End false, all the
instructions will
be jumped.
First round:
Counter=1
Since 1<5, the loop will be entered and as a result the average for the first
student will be computed by reading his/her marks. Then after displaying the
computed average, the statement countercounter+1 will be produced.
According to this instruction, the sum of the current value of the variable
counter and 1 will replace the previous value of counter. So after the execution
of this instruction, the value of counter is 2.
Second round:
Counter=2
One more execution of the loop will be carried out and the value of counter
will be incremented.
The same will happen to the third, fourth and fifth round. At the end of the fifth
round, the value of counter becomes 6. Right now, it is not possible for the ‘while
loop’ to continue since the logical comparison counter<=5 (which is 6<=5) yields
false.
8. Design and represent an algorithm to obtain the sum of the first 50
counting numbers.
Looping structure is needed and the algorithm is presented below.
7
Begin
number1
while number<=50
sum sum+number
numbernumber+1
end while
Display sum
End
Hand trace (process the instructions yourself) the above algorithm. It seems to be perfect. But it is not. The
problem is that sum is not initialized. When we reserve space for ‘sum’ in memory, we don’t know the value
stored there. Therefore we have to initialize ‘sum’ to be zero. The edited algorithm will be:
Begin
sum 0
number1
while number<=50
sum sum+number
numbernumber+1
end while
Display sum
End
9. Find the largest of three given numbers. Assume there is a probability
that three equal numbers be entered.
Begin
Read a,b,c
If a=b and b=c then
Display message as to tell the user the numbers are all equal
End if
max a
if max<b then
max b
end if
if max<c then
max c
end if
Display max
End
8
ab
btemp
display a,b
End
12. Count the occurrence of negative numbers form 10 given numbers.
Begin
cnt 0 //cnt is to say counter. Even you can use a different name for the variable.
index1
while index<=10
read number
if number<0 then
cnt cnt+1
end if
indexindex+1
end while
Display cnt
End
13. Compute the following:
20+21+22+……..+29
Begin
sum 0
i0
while i<=9
sumsum+2i
ii+1
end while
Display sum
End
1.2.3. Flowchart
The other way to represent an algorithm is the flowchart method. A flowchart is a
graphical way of representing algorithms. The flowchart will be used to present the
operations and their flow using the standard symbols.
9
The list of the standard symbols and their meaning is shown below:
Terminal
Decision Connectors
Input / Output
Start
The body of
the algorithm
Stop
Read a
Display sum
iii) Processing: operations to be done will be expressed using this symbol. These
operations are of two types: arithmetic operations (addition, subtraction,
multiplication and division) and data movement instructions (copying some data
from a variable to another one).
sum a+b
x y
x 4
iv) Decision: we know that there are two types of operations that can be done by
the computer. The first types are arithmetic operations where as the other type
is logical operation. Logical operation consists of the evaluation of logical
expressions. Logical expressions are expressions which are built from logical
operators (like <,>,=,<=,>=) and evaluated only to the values true or false.
Therefore, sometimes decisions can be made based on the value of a logical
operation. A good example for this is the statement ‘if a>b then maxa’. When you
10
have such conditions to be tested, then you could use the decision symbol to
represent the situation.
To implement the above if clause using the decision symbol, you could do the
following:
No Is Yes
max b a>b
max a
The decision standard symbol will have one entry point and at least two exits.
v) Flow line: shows the direction of logical flow. This arrow connects standard
symbols used to represent sequence of steps.
vi) Connectors: There are two types: on-page connector and off-page (Interpage)
connector respectively as shown above in the figure.
Start
A labeled on-page
1 connector connecting
one point from the
flow chart to another
1 one
Stop
There are some guidelines that you have to follow when drawing flowcharts:
a) A flowchart should start and end with the terminal symbol having ‘start’ or
‘begin’ and ‘stop’ or ‘end’ respectively.
b) Crossing flow lines should be avoided. And to avoid this, you need to use
connectors.
Before seeing the examples that we have, let’s list some of the advantages of
flowcharts:
a) They can be used by both programmers and non-programmers alike to
illustrate the entire process graphically in a smart manner.
b) While drawing a flowchart one is not concerned with the details of the
elements in programming language. Hence, it facilitates program writing.
c) Since it shows the flow of operations in pictorial form, it allows to easily
detect logical errors in the algorithm.
d) Since it is independent of programming languages, it can be translated into
more than one language.
We will draw flow charts for some of the same examples given before (in the
pseudocode section).
Examples
1. Add two given numbers.
11
It is really very easy to draw a flowchart starting from the already constructed
pseudocode.
Start Begin
Begin
Read a,b
suma+b Read a,b Read a,b
display sum
End
sum a+b = sum a+b
Stop End
2. Find the largest from two given numbers. Take the assumption that the
numbers entered will never be equal.
Begin
Read a,b Start
if a>b then
max a
else Read a,b
max b
end if
Display max Is Yes
End a>b
max a
No
max b
display max
Stop
3. Find the largest of three given numbers. Take the assumption that the
numbers entered will never be equal.
Begin Start
Read a,b,c
max a
Read a,b,c
if max<b then
max b
end if max a
if max<c then
max c
end if Yes
Display max
max b max<b
End
No
Yes
max<c max c
No
display max
12
Stop
4. Obtain average marks for five students for given four subject’s marks.
Begin
Start
counter1
while counter<=5
Read mark1,mark2,mark3,mark4 counter 1
sum mark1+mark2+mark3+mark4
Average sum/4 1
Display Average No counter<=5
countercounter+1
end while
End Stop Yes
Read mark1,
mark2, mark3,
mark4
Avg(mark1+mark2+mark3+mark4)/4
Display avg
countercounter+1 1
sumsum+number
Stop numbernumber+1 1
13
6. Find the maximum (largest) from a given list of numbers.
Begin
Read n
Read number Start
max number
counter1
while counter<=n Read
read number number
if max < number then
max number rem number mod
2
end if
countercounter+1
end while Display message No rem=0
display max ‘ n is even’
End
Yes
Display message
‘ n is odd’
Stop
Read n
Read number
max number
cnt1
1
No cnt<=n
Read number
Stop
No max<number
Yes
maxnumber
cntcnt+1 1
14
8. Suppose that Birr 1000 is deposited in a savings account in 1993 and the
bank pays 10 percent interest, compounded annually. Draw a flowchart
of an algorithm which prints the year and the amount in the account,
until amount first exceeds Birr 10,000 and which also finds the number
of years it takes for amount to reach Birr 10,000 or more. {From ‘Introduction
to computer Science’ by Dr. Dida Midekso}
Develop your own algorithm after understanding the problem. Write the pseudocode form of your
algorithm and draw the flowchart.
The following is an algorithm presented here:
Start
amnt 1000
year1993
cnt1
amntamnt+0.10*amnt
No
Display year,amnt,cnt
cntcnt+1 1
Stop
Begin
Read name,year,hour
If year=1 then
Totalpayment=hour*2
else of year=2 then
Totalpayment=hour*3
else if year=3 then
Totalpayment=hour*4
else if year=4 then
Totalpayment=hour*5
else
Display message as “Invalid year value”
Endif
Display totalpayment
end
15
Start
Read name
Read year
Read hour
yes Year=1
Totalpaymenthour*2 No
1
yes
Display Totalpayment Year=2
2 No Totalpaymenthour*3 1
Stop
yes
Year=3
No Totalpaymenthour*4 1
yes
Year=4
No Totalpaymenthour*5 1
Display message
2 INVALID DATA
16