AIR FORCE INSTITUTE OF TECHNOLOGY (AFIT), KADUNA
FACULTY OF COMPUTING
DEPARTMENT OF COMPUTER SCIENCE
CSC 102: INTRODUCTION TO PROBLEM SOLVING
COURSE CONTENTS
1. Introduction
2. General Problem Solving Strategies
3. Concepts of Algorithm
4. Major Components of Algorithm
5. Properties of Algorithm
6. Role of Algorithm in Problem Solving
7. Ways of expressing Algorithm
8. Algorithm Development Methodologies
9. Top-Down Design
10. Object Oriented Design
11. Implementations strategies
12. Specify the problem requirements (Requirement Specification).
13. Analyze the problem (Analysis)
14. Design the algorithm to solve the problem (Design).
15. Implement the algorithm (Implementation).
16. Test and verify the completed program (Testing).
17. Maintain and update the program (Maintenance).
18. Applications of Software Development Methods in Problem Solving.
Introduction to problem solving
What is general problem solving?
Problem solving is a compound word that is composed of two words, “Problem” and “Solving”.
For us to give a definition we need to take the words into context. Depending on the context,
problem has been defined in a number of ways. The dictionary definition holds that problem is a
question raised for inquiry, consideration or solution, in mathematics; problem has been defined
as a situation that is to be resolved using well- defined mathematical principles. Solving on the
other hand can be defined as a means of finding solution to a problem.
Based on the above definitions we can formally define problem solving as the act of finding a
solution to perplexing, distressing, vexing or unsettled question. Though the definition of
problems cited in the first paragraph suits this definition, some of them are not suitable in the
context of computing. This is because computers are limited in its problem solving Capabilities.
Computers cannot be used in solving problems involving physical activities or emotions.
Solving problems with the Computers
Regardless of the area of study, computer science is all about solving problems with computers.
The problems that we want to solve can come from any real-world problem or perhaps even from
the abstract world. We need to have a standard systematic approach to solving problems. Since
we will be using computers to solve problems, it is important to first understand the computer’s
information processing model. The model shown in the diagram in Figure 1.1 assumes a single
CPU (Central Processing Unit). Many computers today have multiple CPUs, so you can imagine
the above model duplicated multiple times within the computer.
A typical single CPU computer processes information as shown in Figure 1.1. Problems are
solved using a computer by obtaining some kind of user input (e.g., keyboard/mouse information
or game control movements), then processing the input and producing some kind of output (e.g.,
images, text, sound). Sometimes the incoming and outgoing data may be in the form of hard
drives or network devices.
In regards to problem solving, we will apply the above model in that we will assume that we are
given some kind of input information that we need to work with in order to produce some
desired output solution. However, the above model is quite simplified. For larger and more
complex problems, we need to iterate (i.e., repeat) the input/process/output stages multiple times
in sequence, producing intermediate results along the way that solve part of our problem, but not
necessarily the whole problem. For simple computations, the model below is sufficient.
Figure 1.1: Computer information processing model
Problems range from simple to complex. The complexity of a problem lies in the complexity in
finding a suitable solution. For example, the problem of having to come to class early is simpler
than that of gaining an admission. Thus, your solution to gaining an admission will require more
prudent strategies and implementations than that of coming early to class. In addition,
authenticating a bank transaction online will be more complex than authenticating a game login.
To ensure accurate, fast, safe and efficient solutions are gotten to problems, procedures must be
adhered to when finding solutions to problems. We will be discussing such procedures below:
PROCEDURES/STEPS FOR PROBLEM SOLVING
1. Understand/Define the problem
2. Analyze the problem
3. Develop an Algorithm
4. Implement the algorithm (Coding)
5. Testing and Debugging
6. Documentation.
1. Understand/Define the problem: A detailed understanding of the problem that states the
objectives of the given problem must be known to proffer a solution that solves the
problem.
2. Analyze the problem: Analysis of the problem entails a thorough breakdown of possible
solutions with the evaluation of these methods. Here, you may need to break down your
defined problems into modules and solve them as entities. Strategies and methods are
considered and evaluated. By the end of this phase, you should have a broad overview of
the sequence of operations to be implemented to solve your problem.
3. Develop an algorithm: Define a step by step set of instruction from the sequence of
operations gotten from your analysis. Just as you have a series of instructions to follow
through for a food recipe, your solution should be in form of an algorithm. An algorithm
is the step-by-step instruction used to solve a problem. Your algorithm can be revised
until it captures all the features of your analysis.
4. Implement the algorithm (Coding): Your algorithm which may be in natural language,
flowchart, or pseudocode will have to be converted into a high-level programming
language understood by the computer. Each step in your algorithm is converted to its
equivalent instruction(s) in the high-level language chosen for implementation.
5. Testing and Debugging: Testing of implemented programs should be done on various
parameters, some of which are:
I. Does the program meet the user’s requirements?
II. Does it respond within the expected time?
III. Is the correct output generated for all possible inputs?
IV. Does it give room for improvements/upgrades?
V. How does it respond to errors?
Testing and De-bugging checks through the problem definition and analysis ensuring that every
needed requirement is met. This phase either takes you back to your problem definition phase
and down the chain, or takes you to program deployment. Some categories of testing are listed
below.
a. Component testing: Individual component is tested.
b. Unit testing: Individual unit of software, i.e. group of computer program, modules, usage
procedures and operating procedures are tested to determine whether they are suitable for
use or not. This is normally done by the programmer who writes the code.
c. Integration testing: It is done before, during and after integration of new module into the
main software package. One piece of software can contain several modules which are
created by different programmers. It is crucial to test each module effect on the entire
program modules.
d. System testing: This is done by the professional testing agent on the completed product
before it is introduced to the market (users).
e. Acceptance testing: Testing of the product done by the actual end users.
Acceptance testing
System testing
Integrated testing
Unit testing
Software testing hierarchy
6. Documentation: This is a phase usually neglected though very critical. Here, every
process involved in problem solving are meticulously documented. This helps in note
sharing, project handovers, maintenance, evaluation, upgrade as well as debugging. You
must be diligent to document through the process as information and decisions can be lost
with every passing phase.
WEEK 2
ALGORITHMS
In our daily activities, we perform tasks by carrying out some sequence of activities. For
example, getting to school every morning, wearing a tie, making breakfast are examples of tasks
that require a sequence of operations/activities. The following are examples of tasks that require
steps of procedures:
1. Prepare hot tea:
a) Boil water in Kettle,
b) Pour hot water in Tea cup,
c) Put tea bag in teacup,
d) Add sweeteners and/or beverage to tea.
The tea is now ready for drinking.
2. Finding the Greatest Common Divisor of two numbers 45 and 56
Step1
List the numbers that can divide 35 and 28
35: 1, 5, 7, and 35
28: 1,2,4,7,14, and 28
Step2
Find the largest common divisor of the two numbers
Result: The greatest common divisor of 45 and 56 is 7.
The step-by-step sequence of tasks to solve the above problems can be referred to as algorithms.
An algorithm is a sequential set of instructions followed to proffer solutions to a problem.
Necessity of an Algorithm: Designing algorithms could be complex and tasking, why then are
algorithms a necessity? Algorithms increase the reliability, accuracy and efficiency of obtaining
solutions. Without an algorithm, problem solving processes will be disorderly, confusing, and
frustrating, with no provision to efficiently manage systems, debugging and upgrade will be
close to impossible, and such a system will barely be reliable. An algorithm that is dependable,
correct, efficient and has a good execution speed will always produce efficient solutions and will
provide for effective maintenance.
A problem can have more than one algorithm, what then are the metrics for choosing the
algorithm to implement?
- Reliability
- Accuracy
- Ease of modification and upgrades
- Speed
- Cost
Note: There’ll sometimes be trade-offs between these factors to choose the algorithm that best
suit the solution to your problem as it relates to the resources available.
Characteristics of an algorithm:
1. Finiteness: An algorithm must terminate after a finite number of steps. Termination may
either mean an output was gotten or a message given.
2. Definiteness: Each step must be precisely stated and unambiguous.
3. Generality: It should be wholesome such that it can do similar tasks for any input of
data.
4. Effectiveness: Every step must be doable. Each step can be converted into a program
statement, and can be executed in a finite number of times.
5. Input/Output: The input precision (the kind, volume and format of data) should be
specified. The kind, volume and format of the output data should also be precise.
Algorithms should efficiently use resources (i.e. Fast speed and minimal RAM or disk space).
Factors to Identify during algorithm design
The following should be taken into cognizance while writing an algorithm
- Input: The input to be taken from the user.
- Process: The computation or process to be performed to get a result.
- Output: the result/output to be gotten.
Note: The correctness of the output that a computer gives depends on the correctness of input
provided and the accuracy of the designed process.
WEEK 3
ALGORITHM DEVELOPMENT METHODOLOGIES
Design of a solution can only begin once the input, output and processing rules have been
clarified. This information is often represented in a chart format, like the Input-Processing-
Output (IPO) chart shown below. The IPO chart below is for calculating the average of two
numbers.
Input Processing Output
Number 1
Add Number 1 and Number 2 and divide by 2 Average of the two numbers
Number 2
Design involves developing an algorithm, which can often be a difficult process. As an aid to
design structured techniques may be used:
• Top down design - An approach where the overall high level view is determined. The
large problem is then divided into individual smaller problems which are solved
separately in their own module.
• Stepwise Refinement - The process of dividing or breaking down a complex problem
into smaller and smaller problems until the solution to each individual problem is
immediately obvious.
• Structured Design - Use only sequence, selection and repetition structures
• Modular Design - The breaking down of an algorithm into modules or subprograms
where each module has one and only one function
TOP-DOWN DESIGN: Successful creation of an algorithm relies on solving a problem by
dividing the large problem into smaller problems. Initially the high level details are solved then
each of the lower level problems (modules) can be solved individually. The sum of the smaller
solutions will solve the overall problem. This divide and conquer approach is called Top Down
Design.
Advantages of top-down design:
• Each module can be solved individually, thus reducing complexity.
• The algorithm is initially functional (though limited in scope) and as more modules are
added, the overall solution becomes more and more functional.
• Different modules can be written by different people, thus saving time.
• Each module can be tested separately, making testing easier.
STEPWISE REFINEMENT: This method of solving problems works "hand in hand" with
Top-Down Design. This method involves continual development and refinement of a broad
solution into more detailed mini solutions which are combined to solve the broad problem. This
continual process of refinement is called Stepwise Refinement.
STRUCTURED DESIGN: The use of the correct control structures is an important part of
programming. The main reason for their implementation regards "correctness" of an algorithm.
The "correctness" refers to whether or not an algorithm does what it is supposed to do. The
correct structures include Sequence, Selection and Repetition.
Example of Top-Down and Stepwise Refinement Designs.
The process of Top-Down design may be enhanced through the use of structure charts. Using the
problem of finding the average of two numbers, the following structure chart may be used to
represent a breakdown of the problem.
The structure shown above would lead to an algorithm for the main program as shown below
Begin Mainprogram
Intitialise Variables
Get two numbers
Calculate Average
Print Results
End Mainprogram
Each of these smaller problems could now be solved with the following algorithms :
Initialise
Get two numbers Calculate Average Print Results
Variables
Begin Begin Begin Begin
Sum = 0 count = 0 Average = Print "The average is ";
Sum/count Average
Average = 0 while count < 2
End End
Number = 0 Get a number
End Add number to
sum
Add 1 to count
End while
End
We now have a functional algorithm through top-down design and stepwise refinement. At a
later stage this algorithm could be coded into a programming language and made to run on a
computer.
REPRESENTATIONS OF ALGORITHM
There are three common formats of expressing algorithms. The three methods are: Natural
language, flowchart and pseudocode. In choosing any of the methods one must keep in mind the
following:
- The logic of the solution is explicit.
- The flow of control is explicit.
- The processing or computation of inputs should be accurate and unambiguous leading to
an output.
- The process should produce an output.
Flow of Control
The flow of control depicts the flow of events as represented in the flow chart. The events can
flow in a sequence, or on branch based on a decision or even repeat some part for a finite number
of times.
1. Sequence
If we look at the examples above, the statements are executed one after another, i.e., in a
sequence. Such algorithms where all the steps are executed one after the other are said to execute
in sequence. However, statements in an algorithm may not always execute in a sequence. We
may sometimes require the algorithm to either do some routine tasks in a repeated manner or
behave differently depending on the outcomes of previous steps.
2. Selection
Let’s consider a situation whereby your home is far away from your school. With reference to
that, let us answer the following questions
i. Is there a predefined route for walking from home to school?
ii. Can we have different routes while coming back?
There may be multiple routes between home and school. We might take the shortest route in the
morning. But while coming back home in the traffic. Therefore, we could take another route with
less traffic. Hence, the above problem involves some decision making based on certain
conditions.
3. Conditionals are used to check possibilities. During algorithm development, we need
statements which evaluate expressions and execute instructions depending on whether the
expression evaluated to True or False. These true or false values are called binary values.
Conditions
True False
Do this Do that or do nothing
4. Repetition
When giving directions to go someplace, we say something like, “walk 50 steps then turn right”.
Or “Walk till the next crossing then take a right turn”. Consider some other examples like:
• Clap your hands five times
• Walk 10 steps ahead
• Jump on the spot till you get tired
These are the kind of statements we use, when we want something to be done repeatedly, for a
given number of times.
Algorithms can be expressed in the following formats:
• Natural Language: Algorithms can be represented in our everyday language. Steps are
written in simple conventional language.
• Pseudocode: Pseudo means “not real”, so, pseudocode means “not real/unreal codes”.
Pseudocode is essentially English with some defined rules of structure and some
keywords that make it appear a bit like program code. Pseudocodes are non-executable
codes of detailed instructions written in non-formal language that can be translated into
real codes by a programmer. Pseudocodes can be understood by non-programmers and
programmers alike. It has the advantage of not being so labourious to produce as
flowcharts. Pseudocode has the disadvantage of not being as clear and easy to read as a
flowchart - especially for beginner programmers. They are non-ambiguous, simple and
usually written with Keywords. These keywords are usually written in capital letters,
some of which are:
INPUT
COMPUTE
PRINT
INCREMENT
DECREMENT
IF/ELSE
WHILE
TRUE/FALSE
Procedures in Writing a Pseudo-code
1. Arrange the sequence of tasks and write the pseudocode accordingly.
2. Start with the statement of a pseudo code which establishes the main goal or the aim.
3. Elaborate everything which is going to happen in the actual code. Don’t make the pseudo code
abstract.
4. Use standard programming structures such as ‘if-then’, ‘for’, ‘while’, ‘cases’ the way we use it
in programming.
5. Check whether all the sections of a pseudo code are complete, finite and clear to understand
and comprehend.
6. Don’t write the pseudo code in a complete programmatic manner. It is necessary to be simple
to understand even for a layman or client, hence don’t incorporate too many technical terms.
Pseudocode Elements
Some Guidelines and keywords used for pseudocode:
• for start and finish BEGIN MAINPROGRAM, END MAINPROGRAM - this is often
abbreviated to BEGIN and END - especially in smaller programs
• for subprogram BEGIN SUBPROGRAM, END SUBPROGRAM
• for selection IF, THEN, ELSE, ENDIF
• for multi-way selection CASEWHERE, OTHERWISE, ENDCASE
• for pre-test repetition WHILE, ENDWHILE
• for post-test repetition REPEAT, UNTIL
• INPUT: This is data retrieved from the user through typing or through an input device.
• READ / GET: This is input used when reading data from a data file.
• PRINT, DISPLAY, SHOW: This will show your output to a screen or the relevant output
device.
• COMPUTE, CALCULATE, DETERMINE: This is used to calculate the result of an
expression.
• SET, INIT: To initialize values
• INCREMENT, BUMP: To increase the value of a variable
• DECREMENT: To reduce the value of a variable
• Keywords are written in capitals.
• Structural elements come in pairs, e.g. for every BEGIN there is an END, for
every IF there is an ENDIF, etc.
• Indenting is used to show structure in the algorithm.
• The names of subprograms are underlined. This means that when refining the solution to
a problem, a word in an algorithm can be underlined and a subprogram developed. This
feature is to assist the use of the ‘top-down’ development concept.
STATEMENTS IN PSUEDOCODE
A statement is defined as an instruction that directs the computer to perform a specific action. In
writing pseudocode, we will refer to singular instructions as statements.
When writing pseudocode, we assume that the order of execution of the statements is from top to
bottom. This changes when using control structures, functions and exception handling.
For example;
Write an algorithm to display the sum of two numbers entered by user, using both pseudocode
and flowchart.
Pseudocode for the sum of two numbers will be:
INPUT num1
INPUT num2
COMPUTE Result = num1 + num2
PRINT Result
The flowchart for this algorithm will be:
Start
Read num1, num2
Result = num1 + num2
Print Result
Stop
Example 2: Write an algorithm to calculate area and perimeter of a rectangle, using both
pseudocode and flowchart.
Pseudocode for calculating Area and Perimeter of a rectangle.
INPUT length
INPUT breadth
COMPUTE Area = length * breadth
PRINT Area
COMPUTE Perim = 2 * (length + breadth)
PRINT Perim
The flowchart for this algorithm is given as;
Start
Input length, breadth
Area = length * breadth
Print Area
Perim = 2* (length + breadth)
Print Perim
Rules of writing pseudocode
When writing pseudocode, everyone often has their own style of presenting things out since it’s
read by humans and not by a computer; its rules are less rigorous than that of a programming
language. However, there are some simple rules that help make pseudocode more universally
understood.
1. Always capitalize the initial word. Have only one statement per line.
2. Indent to show hierarchy, improve readability, and show nested constructs.
3. Always end multiline sections using any of the END keywords (ENDIF, ENDWHILE,
etc.).
4. Keep your statements programming language independent.
5. Use the naming domain of the problem, not that of the implementation. E.g., “Append
the last name to the first name” instead of “name = first+ last.”
6. Keep it simple, concise, and readable.
Following these rules help you generate readable pseudocode and be able to recognize a not
well-written one.
Conditionals in pseudocode.
Conditionals are written in the algorithm as follows:
If <condition> then
steps to be taken when the condition is true/fulfilled,
There are situations where we also need to take action when the condition is not fulfilled
To represent that, we can write:
If <condition> is true then
steps to be taken when the condition is true/fulfilled
otherwise
steps to be taken when the condition is false/not fulfilled
Here are some common conditions used in Pseudocode:
IF — ELSE IF — ELSE
This is a conditional that is used to provide statements to be executed if a certain condition is
met. This also applies to multiple conditions and different variables.
Here is an if statement with one condition
IF you are happy
THEN smile
ENDIF
Here is an if statement with an else section. Else allows for some statements to be executed if the
“if” condition is not met.
IF you are happy THEN
Smile
ELSE
frown
ENDIF
We can add additional conditions to execute different statements if met.
IF you are happy THEN
smile
ELSE IF you are sad
frown
ELSE
keep face plain
ENDIF
For Example, Let us write an algorithm to check whether a number is odd or even.
• Input: Any number
• Process: Check whether the number is even or not
• Output: Message “Even” or “Odd”
Pseudocode of the algorithm can be written as follows:
PRINT "Enter the Number"
INPUT number
IF number MOD 2 == 0 THEN
PRINT "Number is Even"
ELSE
PRINT "Number is Odd"
Example 2
Let us write a pseudocode and draw a flowchart where multiple conditions are checked to
categorize a person as either child (<13), teenager (>=13 but <20) or adult (>=20),based on age
specified:
• Input: Age
• Process: Check Age as per the given criteria
• Output: Print either “Child”, “Teenager”, “Adult”
Pseudocode is as follows:
INPUT Age
IF Age < 13 then
PRINT "Child"
ELSE IF Age < 20 then
PRINT "Teenager"
ELSE
PRINT "Adult"
The flowchart representation of the algorithm in shown as;
Start
Enter Age
Age <13
Age < 20
“Teenager”
“Adult”
“Child”
Stop
Repetition in Pseudocode
For example;
Write pseudocode and draw a flowchart to accept 5 numbers and find their average.
Pseudocode will be as follows:
Step 1: SET count = 0, sum = 0
Step 2: WHILE count < 5, repeat steps 3 to 5
Step 3: INPUT a number to num
Step 4: sum = sum + num
Step 5: count = count + 1
Step 6: COMPUTE average = sum/5
Step 7: PRINT average
The flowchart is as follows;
Start
count = 0, sum = 0
count <5 average = sum / 5 Print average
Stop
Input num
sum = sum + num
count = count + 1
In the example above, a counter called “count” keeps track of number of times the loop has been
repeated. After every iteration of the loop, the value of count is incremented by 1 until it
performs the set number of repetitions, given in the iteration condition.
There are situations when we are not aware beforehand about the number of times a set of
statements need to be repeated. Such requirements of unknown number of repetitions are handled
using WHILE construct
For example; Write pseudocode and draw flowchart to accept numbers till the user enters 0 and
then find their average.
Pseudocode is as follows:
Step 1: SET count = 0, sum = 0
Step 2: INPUT num
Step 3: WHILE num is not equal to 0, repeat Steps 4 to 6
Step 4: sum = sum + num
Step 5: count = count + 1
Step 6: INPUT num
Step 7: COMPUTE average = sum/count
Step 8: PRINT average
The flowchart to accept numbers till the user enters 0 representation is shown as thus;
Start
count = 0, sum = 0
Input num
num = = 0?
average = sum / count Print average
Stop
sum = sum + num
count = count + 1
Input num
In this example, we do not know how many numbers a user is going to enter before entering 0.
This is handled by checking the condition repeatedly till the condition becomes false.
Example:
Prepare an algorithm that prints name and weekly wages for each employee out of 10 using
pseudo code.
Solution
BEGIN
STORE 0 TO Sum
STORE 1 TO Count
DO WHILE Count not greater than 10
ADD Count to Sum
INCREMENT Count by 1
END WHILE
END
Why use pseudocode?
1. Better readability. Often, programmers work alongside people from other domains, such
as mathematicians, business partners, managers, and so on. Using pseudocode to explain
the mechanics of the code will make the communication between the different
backgrounds easier and more efficient.
2. Ease up code construction. When the programmer goes through the process of
developing and generating pseudocode, the process of converting that into real code
written in any programming language will become much easier and faster as well.
3. A good middle point between flowchart and code. Moving directly from the idea to
the flowchart to the code is not always a smooth ride. That’s where pseudocode presents
a way to make the transition between the different stages somewhat smoother.
4. Act as a start point for documentation. Documentation is an essential aspect of
building a good project. Often, starting documentation is the most difficult part.
However, pseudocode can represent a good starting point for what the documentation
should include.
5. Easier bug detection and fixing. Since pseudocode is written in a human-readable
format, it is easier to edit and discover bugs before actually writing a single line of code.
Editing pseudocode can be done more efficiently than testing, debugging, and fixing
actual code.
Advantages of Pseudocode
Preparing pseudocode while solving any problem through computer has following advantages:
1. It allows the designer to focus on main logic without being distracted by programming
languages syntax.
2. Since it is language independent, it can be translated to any computer language code.
3. It allows designer to express logic in plain natural language.
4. It is easier to write actual code using pseudocode.
5. Unlike algorithms, pseudocodes are concise so pseudocodes are more readable and easier
to modify.
Disdvantages of Pseudocode
Pseudocode has following disadvantages:
1. There are no accepted standards for writing pseudocodes and designer use their own style
while writing pseudocodes.
2. Pseudocode cannot be compiled and executed so its correctness cannot be verified by
using computers.
• Flowchart: A flowchart is a graphical/diagrammatical/Visual representation of a
sequence of instructions to be executed. Flowcharts use unique symbols/shapes to
indicate the flow of instructions and processes to be executed. Every shape or arrow
indicates the instruction to be carried out. Some of these shapes and their
representations are:
Symbols Meaning Symbols Meaning
Process- any type of Connector- connects
internal operation: sections of the
data transformation, flowchart so that the
data movement, logic diagram can maintain
operation, etc a smooth, linear flow
Input/ output- input or Terminal- indicates
output of data start or end of the
program or algorithm
Decision- evaluates a Flow lines- arrows
condition or that indicates the
statements and direction of the
branches depending progress of the
on whether the program or algorithm
evaluation is true or
false
General Rules for flowcharting
1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other entry points.
The exit point for all flowchart symbols is on the bottom except for the Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side.
4. Generally a flowchart will flow from top to bottom. However, an upward flow can be shown
as long as it does not exceed 3 symbols.
5. Connectors are used to connect breaks in the flowchart. Examples are:
• From one page to another page.
• From the bottom of the page to the top of the same page.
• An upward flow of more than 3 symbols
6. Subroutines and Interrupt programs have their own and independent flowcharts.
7. All flow charts start with a Terminal or Predefined Process (for interrupt programs or
subroutines) symbol.
8. All flowcharts end with a terminal or a contentious loop.
Example 1
Find the average of 2 numbers
Before developing the algorithm, let us first identify the input, process and output:
Start
• Input: two numbers
Input X,Y
• Process: add the numbers and divided by 2
• Output: average of the two numbers
Sum=X+Y
Algorithm
Step 1. Take 2 numbers x and y
Average = SUM/2
Step 2. Add the two numbers and store it in sum
Step 3. Divide sum by 2 and store in average Print Average
Step. Print average
The flowchart for the above example will be; Stop
Example 2
Write an algorithm to read values for three variables. U, V and W and find a value for result
from the formula. Result= U+V2/W
START
Solution
Step 1. Input values for u, v and w
INPUT U, V,W
Step 2. Compute values for result Uuuu,v,w U,V,W
Step 3. Print value of result
RESULT=U+(V 2)/W
Step 4. Stop
The flowchart is given as ;
PRINT RESULT
Example 3
STOP
Write an algorithm to find the square of a number.
• Input: Number whose square is required
• Process: Multiply the number by itself to get its square
• Output: Square of the number
Algorithm to find square of a number.
Step 1: Input a number and store it to num
Step 2: Compute num * num and store it in square
Step 3: Print square
The algorithm to find square of a number can be represented pictorially using flowchart as
shown below:
Example 4
Suppose you are given 20 numbers. Prepare the algorithm that’s add these numbers and find the
average. Draw the flowchart
Solution
Algorithm
Step 1. Set up a counter (I) which counts the number of times the loop is executed. Initialize
counter (I) to 1.
Step 2. Initialized sum to zero
Step 3. Input value and add to sum
Step 4. Increment counter (I) by 1
Step 5. Check how many times you have added up the number, if it is not up to the required
number of times, go to step (iii)
Step 6. Compute the average of the Numbers
Step 7. Stop
Start
I I, sum 0
Sum sum+1
I I+1
Is I <=20
Average=sum/20
Print average
Stop
Example 5
Draw a flowchart to solve the problem of a non-functioning light bulb.
Start
Is the bulb
switched Switch on
on?
Bulb
on
Call
Is it
electrician
burnt
Replace the bulb
Stop
Example: 6
Write an algorithm to calculate the simple interest using the formula.
Simple interest = P*N*R/100
Where p is principle amount, N is the number of years and R is the rate of interest.
Step 1: read the three input quantities P, N, and R.
Step 2: calculate simple interest as simple interest= P*N*R/100.
Step 3: print simple interest.
Step 4: stop
start
Read P ,N ,R
Calculate simple interest=
P*N*R/100
Print simple interest
Stop