Fundamentals of Programming
Chapter I-Problem Solving Using Computers
Chapter III
Problem Solving Using Computers
Computer problem solving is a complicated process requiring careful
planning and attention to detail. The vehicle for the computer solution
to a problem is a set of explicit and unambiguous instructions called a
program and expressed in a programming language. A program is a
sequence of instructions that determine the operations to be carried
out by the machine in order to solve a particular problem. There are
five stages of software/program development. They are Analysis,
Algorithm design & Flow chart, Coding, Implementation, and
Maintenance.
Stages of Program Development
There are five stages of program development: namely, Analysis,
Algorithm & Flow chart design, Coding, Implementation, and
Maintenance.
I. Analysis
Analysis stage requires a thorough understanding of the problem
at hand and analysis of the data and procedures needed to achieve the
desired result. In analysis stage, therefore, what we must do is workout
what must be done rather than how to do it.
What input data are needed to the problem?
What procedures needed to achieve the result?
What outputs data are expected?
II. Algorithm design and flowchart
Once the requirements of the program are defined, the next
stage is to design an algorithm to solve the problem. An algorithm is
a finite set of steps which, if followed accomplishes a
particular task. An algorithm is a map or an outline of a solution which shows the
precise order in which the program will execute individual functions to arrive at the
solution. It is language independent. An algorithm can be expressed in many
ways. Here, we only consider two such methods: Narrative
1
Fundamentals of Programming
Chapter I-Problem Solving Using Computers
(pseudocode) and Flowchart. English is often used to describe or
narrate the algorithm. There is no need to follow any rules about how to write it.
Instead we use pseudo code which is free form list of statements that shows the sequence
of instructions to follow.
Flowchart
A flowchart consists of an ordered set of standard symbols
(mostly, geometrical shapes) which represent operations, data flow or
equipment.
A flowchart is a diagram consisting of labeled symbols,
together with arrows connecting one symbol to another. It is
a means of showing the sequence of steps of an algorithm.
A program flowchart shows the operations and logical decisions of a
computer program.
The most significant advantage of flowcharts is a clear presentation of the flow of
control in the algorithm, i.e. the sequence in which operations are performed.
Flowcharts allow the reader to follow the logic of the algorithm more easily than
would a linear description in English.
Another advantage of flowchart is it doesn’t depend on any
particular programming language, so that it can used, to translate
an algorithm to more than one programming language.
A basic set of established flowchart symbols is:
Decision
Processing Input/output
START/STOP
Connector Flow lines
The symbols have the following meanings:
Processing: one or more computational tasks are to be performed sequentially.
Input/output: data are to be read into the computer memory from an input device
or data are to be passed from the memory to an output device.
Decision: –It usually contains a question within it. There are
typically two output paths: one if the answer to the question is
yes ( true) , and the other if the answer
2
Fundamentals of Programming
Chapter I-Problem Solving Using Computers
is no ( false). The path to be followed is selected during the execution by
testing whether or not the condition specified within the outline is fulfilled.
Terminals: appears either at the beginning of a flowchart (and contains the world
"start") or at its conclusion (and contains "stop"). It represents the Start
and End of a program.
Connector: makes it possible to separate a flowchart into parts.
Flow lines: is used to indicate the direction of logical flow. (A path
from one operation to another)
3
Fundamentals of Programming
Chapter I-Problem Solving Using Computers
DESIGN AND IMPLEMENTATION OF ALGORITHMS
An algorithm is a finite set of instruction that specify a sequence of
operations to be carried out in order to solve a specific problem or
class of problems. It is just a tool for solving a problem. All the tasks
that can be carried out by a computer can be stated as algorithms.
For one problem there may be a lot of algorithms that help to solve
the problem, but the algorithm that we select must be powerful,
easy to maintain, and efficient (it doesn’t take too much space and
time)
Once an algorithm is designed, it is coded in a programming
language and computer executes the program. An algorithm consists
of a set of explicit and unambiguous finite steps which, when carried
out for a given set of initial conditions, produce the corresponding
output and terminate in a fixed amount of time. By unamabiguity it is
meant that each step should be defined precisely i.e., it should have
only one meaning. This definition is further classified with some more
features.
An algorithm has five important features.
Finiteness: An algorithm terminates after a fixed number of
steps.
Definiteness: Each step of the algorithm is precisely defined,
i.e., the actions to be carried out should be specified
unambiguously.
Effectiveness: All the operations used in the algorithm are
basic (division, multiplication, comparison, etc.) and can be
performed exactly in a fixed duration of time.
Input: An algorithm has certain precise inputs, i.e. quantities,
which are specified to it initially, before the execution of the
algorithm begins.
Output: An algorithm has one or more outputs, that is, the
results of operations which have a specified relation to the
inputs.
Examples:
4
Fundamentals of Programming
Chapter I-Problem Solving Using Computers
1) Algorithm to add two 2) Algorithm to find largest
number from two numbers.
numbers.
Step 1: START
Step 1: START Step 2: Read n1 and n2.
Step 2: Read two numbers Step 3: If n1 > n2 go to
n1 and step 5
n2. Step 4: Big←n2,go to step
Step 3: Sum ← n1 + n2 6
Step 4: Print Sum Step 5: Big ← n1
Step 5: STOP Step 6: Print Big
Step 7: STOP
3) Algorithm to find largest
number from three numbers. 4) Algorithm to find sum of N
Step 1: START positive integer numbers.
Step 2: Read n1, n2 and n3. Step 1: START
Step 3: If n1 > n2 and n1 > n3, Step 2: Read N
go to step 6 Step 3: Sum ← 0,
Step 4: If n2 > n1 and n2 > n3, Step 4: Count ← 0
go to step 7 Step 5: Read Num
Step 5: Big ←n3, go to step 8 Step 6: Sum←Sum + Num
Step 6:Big ← n1 , go to step 8 Step 7: count ← count +1
Step 7:Big ← n2 Step 8: If Count < N then goto
Step 8: Print Big step5
Step 9: STOP. Step 9: Print Sum
Step 10: Stop
5) Algorithm to find factorial of a given Number. (N! = 1*2*3*…*N)
Step 1 : Read N
Step 2: Fact=1
Step 3 : Count = 1
Step 4 : Fact = Fact * Count
Step 5 : Count = Count +1
Step 7 : If Count < = N then Goto step 4
Step 8 : Print Fact
Step 9 : Stop
5
Fundamentals of Programming
Chapter I-Problem Solving Using Computers
1. Draw a flowchart to add two numbers. 2. A Flowchart to find largest
of two numbers.
6
Fundamentals of Programming
Chapter I-Problem Solving Using Computers
III. Coding
The flowchart is independent of programming language. Now at
this stage we translate each steps described in the flowchart
(algorithm description) to an equivalent instruction of target
programming language, that means, for example if we want to write in
FORTRAN program language, each step will be described by an
equivalent FORTRAN instruction (Statement).
IV. Implementation
Once the program is written, the next step is to implement it.
Program implementation involves three steps, namely, debugging (the
process of removing errors), testing (a check of correctness), and
documenting the program (to aid the maintenance of a program during
its life time). Every program contains bugs that can range from simple mistakes in the
language usage (syntax errors) up to complex flaws in the algorithm (logic errors).
V. Maintenance
There are many reasons why programs must be continually
modified and maintained, like changing conditions, new user needs,
previously undiscovered bugs (errors). Maintenance may involve all
steps from requirements analysis to testing.
Types of Programming Languages
We have seen that a computer system consists of different layers. It is
possible to communicate with the computer by writing a program at
the different layers but basically there are three types of programming
languages: - Machine, Assembly and high- level.
Machine Language: - This is the only language that the computer
understands directly. A machine language is a set of machine
instructions which consists of zero’s and one’s. A machine instruction
contains two parts an operation code - (OP code) and an address.
The OP code tells the microprocessor system what operation it should
perform such as add, transfer, compare, or move data to output
device, etc. The address identifies the location (memory, register)
holding the required operands that is, the data to be operated upon.
7
Fundamentals of Programming
Chapter I-Problem Solving Using Computers
The address part may contain one, two or more addresses that is ,
there may be one (single) address, two( double) address, and three
( or triple) address instructions.
Assembly Language: - In machine language we have seen that the
OP code and the address are represented as a binary sequence but it
is difficult for the programmer to write a big program using binary
sequence and it is difficult to debug an error from such program so
instead of representing the OP code and the adders as a binary
sequence we can represent them in mnemonics (symbols). An
Assembly language is a programming language which uses mnemonics
to write a program. It is machine dependent.
High-Level Language: -We have seen that writing a program in low-
level languages is easier and simple compare to machine languages.
But still Assembly language has its own drawback, which is machine
dependent. So we need another type of languages which are not
machine-dependent and more flexible. These languages are called
high-level languages.
Advantages of High-Level Languages:-
1. Easier to learn and understand ( Look like English)
2. Require less time to write and easier to debug errors.
3. Can be used on different machines with little modifications.
E.g:
a. C++ :- Originated from C.
b. Fortran:- FORmula TRANslation.
c. COBOL-:-Common business Oriented Language.
d. ALGOL 80:- (Algorithmic Oriented Language).
e. BASIC:- ( Beginners All-purpose Symbolic Instruction
Code) simplest language developed for solving
numerical problem
f. Pascal, Ada, Modula-2:- Used in teaching programming
language.
4. There are also other languages which are still simplest and
easier than high-level languages which we call them fourth
8
Fundamentals of Programming
Chapter I-Problem Solving Using Computers
generation languages. These languages are application
oriented languages. Ex: - Visual basic
Translation and Execution
The only language that the computer understands is the machine
language. Therefore any program that is written in either low-level or
high level language must be translated to machine code so that the
computer could process it.
A program written in High-level or Assembly is called Source
code or Source program and, the translated machine code is called
the object code or object program. Programs that translate a
program written in high level language and Assembly to machine code
program are called translators. There are three types of translators;
assembler, interpreter, and compiler.
Source code: High-level language instructions.
Compiler: System software which translates high-level
language instructions into machine language or object code.
The compiler translates source code once and produces a
complete machine language program.
Object code: Translated instructions ready for computer.
An assembler is a software tool for translating low-level
language (assembly language) into machine language.
The translator not only translates the instructions into machine code
but also it detects whether the program fulfills the syntax of the
programming language. A program passes
through different stages before it carries out its function. First the
program will be translated to object code (compilation time), then it
will be loaded to the memory and finally it will be executed (run time)
or carries out its function.
Basic Programming Tools
The three basic building blocks, that is essential to develop a solution to a problem are:
1. Sequential executions where instructions are performed one after the other.
2. Branching operations where a decision is made to perform one block of
instructions or another.
3. Looping operations where a block of instructions is repeated. There are two
types of loops. The first is the conditional loop where we do not know in advance
9
Fundamentals of Programming
Chapter I-Problem Solving Using Computers
how many times something is to be repeated. The second type is the counted loop
where we do know in advance how many times to repeat the solution.
I. Sequential Execution of Instructions
Sequential instructions are executed one after the other. The computer begins with
the first instruction and performs the indicated operation, then moves to the next
instruction and so on.
Illustration: 1 - An algorithm and a flowchart to compute the area of a rectangle whose
length is ‘l’ and breadth is ‘b’.
Algorithm Flowchart
START
Step 1: START
Step 2: Obtain (input) the length, call it l Read l,b
Step 3: Obtain (input) the breadth, call it b
Step 4: Compute l*b, call it Area Area ← l*b
Step 5: Display Area
Display
Step 6: STOP Area
Stop
Illustration: 2- To allow for repeated calculation of the area of a rectangle whose length
is ‘l’ and breadth is ‘b’, rewrite the above algorithm and flowchart. Allow different values
of ‘l’ and ‘b’ before each calculation of area.
Algorithm Flowchart
Step 1: START START
Step 2: Read length, call it l
Read l,b
Step 3: Read breadth, call it b
Step 4: compute l*b, call it Area Area ← l*b
Step 5: Display Area
Step 6: Go to step 2 Display
Area
Note: Here in effect we created a loop. The series of
instructions to calculate ‘area’ is reused over and over again, each time with a different
set of input data. But here it is an infinite loop. There is no way to stop the repeated
calculations except to pull the plug of the computer. There fore using this type of
unconditional transfer (Go to) to construct a loop is generally not a good idea. In almost
all cases where an unconditional loop seems useful, one of the other control structures
(loops or branches) can be substituted and in fact it is preferred.
II. Branching Operations
10
Fundamentals of Programming
Chapter I-Problem Solving Using Computers
With sequential instructions there is no possibility of skipping over one instruction. A
branch is a point in a program where the computer will make a decision about which set
of instructions to execute next. The question that we use to make the decision about
which branch to take must be set up so that the answers can only be yes or no.
Depending on the answer to the question, control flows in one direction or the other.
Illustration: Construct an algorithm and flowchart to read two numbers and determine
which is large.
Algorithm Flowchart
Step 1: START
Step 2: Read two numbers A and B.
Step 3: If A > B then go to step 6
Step 4: Display B is largest.
Step 5: Go to step 7
Step 6: Display A is largest
Step 7: STOP
Note that only one block of instructions is executed, not both. After one block or other
executes, the two paths merge (at the circle) and control transfers to the next instruction.
We could have several loops inside each block since we are not limited to just one
instruction.
Nesting of Branching Operations
There are many times when we need to choose between more than two alternatives. One
of the solutions to this is nesting of instructions.
Illustration
Construct an algorithm and flowchart to see if a number ‘n’ is negative, positive, or zero
Algorithm Flowchart
Step 1: START
Step 2: Read in ‘n’
Step 3: Is n<0
Step 4: If yes, go to step 11
Step 5: Is n=0
Step 6: If yes, go to step 9
Step 7: Print “Positive”
Step 8: go to step 12
Step 9: Print “Zero”
Step 10: go to step 12
Step 11: Print “Negative”
Step 12: STOP
The Select Case Structure
11
Fundamentals of Programming
Chapter I-Problem Solving Using Computers
A simpler way to handle multiple
alternative problems is the ‘Select Case
Structure’. Several alternatives are
offered, but only one can be executed-
the one selected inside the diamond.
Then the control transfers to the end of
the structure. You can have as many
alternatives as you wish. The computer
decides which set of instructions to execute by examining the case value (CV).
Illustration: An algorithm and flowchart to calculate the value of ‘a’ based on the
equations: When(x=1) a=x*y*z ; When (x=3) a=x/z ;When (x=5) a=x*y/z
12
Fundamentals of Programming
Chapter I-Problem Solving Using Computers
Algorithm Flowchart
Step 1: START
Step 2: Read in values for x, y, z.
Step 3: When(x=1) go to step 10
Step 4: When (x=3) go to step 8
Step 5: When (x=5)
Step 6: a=x*y/z
Step 7: go to step 11
Step 8: a=x/z
Step 9 : go to step 11
Step 10: a=x*y*z
Step 11: Print value of a
Step 12: STOP
III. LOOPS
Loops are the third major type of control structure that we need to examine. There are 2
different types of loops, the counted loop and the conditional loop. The counted loop
repeats a predetermined number of times while the conditional loop repeats until a
condition is satisfied.
In the counted loop a counter keeps track of the loop executions. Once the counter
reaches a predetermined number, the loop terminates. Number of loop executions is
set before the loop begins and cannot be changed while the loop is running.
The conditional loop has no predetermined stopping point. Rather, each time
through the loop the program performs a test to determine when to stop. Also the
quantity being used for the test can change while the loop executes.
The variable used to control the loop can be referred to as Loop Control Variable
(LCV).
Flowchart symbol for loop is hexagon. Inside the loop is
the start and stop values for LCV. Also a step value is Start =…
Stop=…
included from which the computer decides how many Step=…..
times to execute the loop. Inside the loop is the body
which can consist of any number of
instructions. When the loop finishes,
the control transfers to the first
statement outside the loop.
With counted loops, it’s a must to
know in advance how many times the
loop will execute. But if this
information is not available and yet the problem demands a loop means, we can
make use of conditional loop, where the machine will check every time through the
loop to see whether it should be repeated or not.
In conditional loop, the programmer must change the Loop control variable.
13
Fundamentals of Programming
Chapter I-Problem Solving Using Computers
Illustration
An algorithm and flowchart to print out the numbers 1 to 100 and their squares.
Algorithm Flowchart
Start 1: START
Start 2: Loop (LCV start=1;stop=100,step=1)
Step 3: Print LCV, LCV2 value
Step 4: End loop
Step 5: STOP
COMMENTS
We can place any comments to describe what the flowchart does using the symbol
Your
Comments here
Comments greatly improve the readability of the flowcharts and hence the programs first.
You will find them useful during debugging by reminding what you were thinking when
you first constructed the solution.
DEBUGGING TIPS
Debugging is the process of removing errors from your program. Bugs fall into two
general categories – syntax and logic errors. Syntax errors are mistakes in the grammar of
the computer language. These types of errors are easy to correct since the computer will
highlight them. Logic errors, on the other hand, are mistakes in the sequence of
instructions you have given the computer.
Test Your Self
Construct an algorithm and a flowchart for the following:
1. To find the smallest number from three numbers.
2. To read in x, y and z and then compute the value of xyz.
3. To determine if a whole number is odd or even.
4. To print a prompt message “good morning”.
5. To find the sum of first n even numbers.
6. To find the sum of digits of a given number.
7. To print out a list of first n even numbers and their squares.
8. To find the sum of n positive numbers.
9. To find the biggest among n numbers.
10. To find the factorial of a given number.
14
Fundamentals of Programming
Chapter I-Problem Solving Using Computers
11. To generate Fibonacci series (1, 1, 2, 3, 5, 8, 13…)
12. To read in a series of numbers and keep track of the running total and the number
of data items. Stop reading in the numbers when one of them has a value zero.
Then compute the average of all the numbers and report it.
15