Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
40 views33 pages

GE8151 Unit I

This document discusses algorithmic problem solving and the building blocks of algorithms. It begins by defining an algorithm as an ordered sequence of instructions to complete a task. The main building blocks of algorithms are identified as statements, state, control flow, and functions. Several examples of algorithms are provided, such as finding the minimum value in a list or calculating the area of a circle. The key characteristics of algorithms are defined as definiteness, finiteness, and effectiveness.

Uploaded by

Merbin Jose
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views33 pages

GE8151 Unit I

This document discusses algorithmic problem solving and the building blocks of algorithms. It begins by defining an algorithm as an ordered sequence of instructions to complete a task. The main building blocks of algorithms are identified as statements, state, control flow, and functions. Several examples of algorithms are provided, such as finding the minimum value in a list or calculating the area of a circle. The key characteristics of algorithms are defined as definiteness, finiteness, and effectiveness.

Uploaded by

Merbin Jose
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

1

GE8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING

UNIT I
ALGORITHMIC PROBLEM SOLVING

Algorithms, building blocks of algorithms (statements, state, control flow, functions),


notation (pseudocode, flowchart, programming language), algorithmic problem solving,
simple strategies for developing algorithms (iteration, recursion). Illustrative problems: find
minimum in a list, insert a card in a list of sorted cards, Guess an integer number in a range,
Towers of Hanoi.

Introduction
A computer is a programmable machine that receives input, stores and manipulates data, and
provides output in a useful format. In regards to today‟s computers, the “machine” part of the
computer is called the hardware, while the “programmable” part is called the software.

Software itself can be broken down into three main categories:


• System Software: is designed to operate the computer‟s hardware and to provide and
maintain a platform for running applications. (e.g., Windows, MacOS, Linux, Unix, etc.,)

• Middleware: is a set of services that allows multiple processes running on one or more
machines to interact. It can also allow data contained in one database to be accessed
through another. Middleware is sometimes called plumbing because it connects two
applications and passes data between them. (e.g., web servers, application servers).

• Application Software: is designed to help the user to perform one or more related
specific tasks. Depending on the work for which it was designed, an application can
manipulate text, numbers, graphics, or a combination of these elements. (e.g., office
suites, web browsers, video games, media players, etc.,)

A program is a sequence of instructions that can be executed by a computer to solve some


problem or perform a specified task. A programming language is an artificial language
designed to automate the task of organizing and manipulating information, and to express
problem solutions precisely.
Problem Solving is the sequential process of analyzing information related to a given
situation and generating appropriate response options. A programmer must analyze the problem,
develop instructions for solving the problem and then make use of computer to carry out the
developed instructions. The common stages in problem solving are,

1. Problem Analysis: Identify and understand the Problem.


2. Choose suitable approach: Find alternative ways to solve the problem and choose
appropriate approach.
3. Formulate a Model: Break the problem into smaller units or subtasks.
4. Develop an Algorithm
5. Write the Program
6. Test the Program: Check the correctness of the algorithm
7. Calculate efficiency
Mr. P. J. Merbin Jose
2

Once the problem is analyzed, the programmer makes use of tools, such as, algorithm,
flowchart and pseudocode to solve the problems.
In general the program development lifecycle includes Problem analysis, design,
implementation (coding), testing, documentation and maintenance.

NEED FOR LOGICAL ANALYSIS AND THINKING

Computer can perform variety of tasks like receiving data, processing it and producing useful
results. It cannot perform on its own. A computer needs to be instructed to perform a task.

The computer works on set of instructions, called computer program to carry out a particular
task, so that the computer can process that task.

Identify the Analyze the Select the


Problem solution Best

To produce an effective execution of the computer program, it is very important that the
programmer must take care of each and every step or instruction in a proper sequence.

To design a program, a programmer must determine three steps:


1. The instructions to be performed.
2. The sequence in which these instructions are to be performed.
3. The data required to perform these instructions.

For example, to calculate the sum of two numbers, read the value of two numbers A and B, add
A and B and store the sum value in C.

To solve the problem using computer, the following steps should be followed.

a) Problem must be analyzed thoroughly.


b) Solution method is broken down into a sequence of small tasks.
c) Based on the analysis, an algorithm must be prepared to solve the problem.
d) The algorithm is expressed in a precise notation. This notation is known as a computer
program.
e) The computer program is then fed into the computer.
f) The instruction in the program is executed one after other and finally outputs the expected
results.

PROPLEM SOLVING TECHNIQUES

There are three ways to represent the logical steps for finding the solution to a given problem.
1. Algorithm
2. Flowchart
3. Pseudocode
3

1.1 ALGORITHM

Definition:
Algorithm is an ordered sequence of finite, well defined, unambiguous instructions for
completing a task.
It is step-by-step procedures that perform a specific task or operation.

 Algorithm is an English-like representation of the logic which is used to solve the


problem.
 To accomplish a particular task, different algorithms can be written. They differ by their
time and space.
 The programmer selects the best suited algorithm for the given task to be solved.
 The algorithm can be implemented in many different languages by using different
methods and programs.
 The algorithm is independent of any programming language.

Guidelines for writing Algorithms


 An algorithm should be clear, precise and well defined.
 It should always begin with the word „Start‟ and end with the word „Stop‟.
 Each step should be written in a separate line.
 Steps should be numbered as Step 1, Step 2, and so on.

Characteristics/Properties of an algorithm

1. Definiteness: In the algorithm each and every instruction should be precise and
unambiguous. The instruction in an algorithm should not be repeated infinitely.
2. Finiteness: Ensure that the algorithm will terminate after a finite number of steps.
3. The algorithm should be written in sequence, and looks like normal English.
4. The desired result should be obtained only after the algorithm terminates.
5. Input: The data must be present before any operations can be performed on it. The initial
data is supplied by a READ instruction. A variable can be given initial value using the
SET instruction.
Example:
READ A, B
SET N=0
6. Output: After execution all the steps of the algorithm at least one output must be obtained.
The WRITE statement is used to print messages and variables.
7. Effectiveness: the designed algorithm should be feasible to convert in a computer
program.

Example of an algorithm
1) Algorithm to display the name, department

Step 1: Start
Step 2: Get/Read the name and department
Step 3: Print the name and department
Step 4: Stop

Mr. P. J. Merbin Jose


4

2.1) Algorithm to find the area of the


circle 2.2) Algorithm to find the area of the
Step 1: Start circle
Step 2: Read/ input the Radius r of the
Circle Step 1: Start
Step 3: Assign PI=3.14 Step 2: Read the value of radius r
Step 4: Calculate the Area = PI*r*r Step 3: Calculate, Area=3.14*r*r
Step 5: Print Area Step 4: Print the Area of the circle
Step 6: Stop Step 5: Stop

3) Algorithm to find the greatest among three numbers

Step 1: Start
Step 2: Read the three numbers A, B, C
Step 3: Compare A and B. If A is the greatest perform Step 4 else perform Step 5.
Step 4: Compare A and C. If A is the greatest, print “A is the greatest” else print “C is the
Greatest”.
Step 5: Compare B and C. If B is the greatest, print “B is the greatest” else print “C is the
Greatest”.
Step 6: Stop.

Advantages of Algorithm

i) It is a simple to understand step by step solution of the problem.


ii) It is easy to debug.
iii) It is independent of programming languages.
iv) It is compatible to computers, because each step of an algorithm can be easily coded into its
equivalent high level language.

1.2 BUILDING BLOCKS OF ALGORITHMS

The building blocks of algorithms include,


 Statements
 State
 Control flow and
 Functions
1.2.1) Statements/Instructions

Instruction: Commands given to the computer that tell what it has to do. (An instruction is a
single operation that describes a computation. When it executed it convert one state to other).
Statement: A section of code that represent a command or action.

1.2.2) State
Transition from one process to another process under specified condition with in a time is
called state.

Mr. P. J. Merbin Jose


5

The state of an algorithm is defined as its condition regarding stored data. The stored data
in an algorithm are stored as variables or constants. The state shows its current values or
contents.
The state of the instruction will be changed during execution.

1.2.3) Control flow


 The process of executing the individual statements in a given order is called control flow.
 The logic of a program may not always be executed in a particular order. The execution
of statements is based on a decision.
 The basic control flows needed for writing good and efficient algorithms are,
a) Sequence
b) Selection (Decision)
c) Iteration (Repetition or Looping)

a) Sequence
In sequence control flow, the instructions are executed in a linear order one after the other. The
following algorithm performs the steps in a purely sequential order.

Example: Algorithm to find sum of two Example: Algorithm to find sum of two
numbers numbers (second method)
Step 1: Start Step1: Start
Step 2: Read two numbers a and b Step2: Read the first num1
Step 3: calculate c = a + b Step3: Read the second num2
Step 4: Display c Step4: Calculate the Sum = num1+num2
Step 5: Stop Step5: Print Sum
Step6: Stop

b) Selection
 In selection control flow, the step to be executed next is based on a decision taken.
 If the condition is true, one part of the program will be executed, otherwise it will execute
the other part of the program.

Example: Write an algorithm to check whether a person is eligible to vote or not?


Step 1: Start
Step 2: Read age
Step 3: Compare if age >= 18 then print “Eligible to vote”
Step 4: Else print “Not eligible to vote”
Step 5: Stop

Example: Algorithm to find the biggest among three numbers

Step 1: Start
Step 2: Read the three numbers A, B, C
Step 3: Compare A and B. If A is greater, store A in MAX, else store B in MAX
Step 4: Compare MAX and C. If MAX is greater, print “MAX is greater” else print “C is
greater”
Step 5: Stop

Mr. P. J. Merbin Jose


6

c) Iteration
In some programs, one or more statements are executed again and again based upon
conditional test. i.e. executed more than one time. This type of execution is called looping or
repetition or iteration.

Example: Write an algorithm to print sum of natural numbers up to n


Step 1: Start
Step 2: Read N value
Step 3: Initialize loop counter i=1 and Sum=0
Step 4: Repeat the steps 4.1 and 4.2 until i <= N, when the condition becomes false,
go to step 5
Step 4.1: Sum= Sum + i
Step 4.2: Increment value of i by 1 i.e i++
Step 5: Print the value of Sum
Step 6: Stop

Example: An algorithm to print even numbers between 0 and 99. (First method)
Step 1: Start
Step 2: Read n or Initialize n=99
Step 3: Initialize i=2
Step 4: Repeat the steps 5 and 6 until i<=n, after that goto step 7
Step 5: Check if i%2= =0, then goto step 5.1 else goto step 6
Step 5.1: Print i and goto step 6
Step 6: Increase the value i=i+1 goto step 4
Step 7: Stop

Example: An algorithm to print even numbers between 0 and 99. (Second method)
Step 1: Start
Step 2: Read n or Initialize n=99
Step 3: Initialize i=2
Step 4: Repeat the steps 5 and 6 until i<=n, after that goto step 7
Step 5: Print i
Step 6: Increase the value i=i+2 goto step 4
Step 7: Stop

Example: An algorithm to print even numbers between 0 and 99. (Third method)
Step 1: Start
Step 2: Read n or Initialize n=99
Step 3: Initialize i=2
Step 4: Repeat the steps 4.1 and 4.2 until i<=n, after that goto step 5
Step 4.1: Print i
Step 4.2: Increase the value of i as i=i+2
Step 5: Stop

Mr. P. J. Merbin Jose


7

Fig: Flow chart for control flow statements

1.2.4) Functions
 Function is a sub program which consists of block of code (set of instructions) that
performs a particular task.
 Any complex problem will become simpler if the problem is broken in to smaller
problems. The functions are solution to smaller problems. These can be used to solve
bigger, complex problems.
 During algorithm design the complex problems are divided into smaller and simpler
tasks. These tasks are solved independently by functions.

Benefits of Using Functions


 Reduce program size and the program development time.
 High degree of code reusing
 Better readability
 Easy to debug and test
 Improved maintainability

Example: Algorithm for addition of two numbers using function

Main function()

Step 1: Start
Step 2: Call the function add()
Step 3: Stop

sub function add()

Step 1: Function start


Step 2: Read a, b values
Step 3: Add c = a + b
Step 4: Print c
Step 5: Return

Mr. P. J. Merbin Jose


8

1.3 NOTATION
A notation is a system of characters, expressions, graphics or symbols used in problem
solving process to represent technical facts to facilitate the best result for a problem.

Example: Pseudocode, Flowchart

1.3.1) PSEUDOCODE

“Pseudo” means imitation or false. “Code” means the set of statements or instructions written in
a programming language. Pseudocode is also called as “Program Design Language [PDL]”.

 Pseudo code consists of short, readable and formally styled English languages used for
explaining an algorithm.
 It does not include details like variable declaration, subroutines.
 It is easier to understand for the programmer or non-programmer to understand the
general working of the program, because it is not based on any programming language.
 It gives us the sketch of the program before actual coding.
 It is not a machine readable code.
 Pseudo code can‟t be compiled and executed.
 There is no standard syntax for pseudo code.

Rules for writing Pseudocode


 Statements should be written in simple English (or any preferable natural language) and
should be language independent.
 Steps must be understandable.
 Pseudocodes should be concise.
 Each instruction should be written in a separate line.
 Capitalize initial keyword such as READ, WRITE, IF, WHILE, UNTIL and so on.
 Each set of instructions is written from top to bottom, with only one entry and one exit.
 It should allow for easy transition from design to coding in programming language.

Common keywords used in pseudocode:

1 SET, INITIALIZE: Initialization


2 BEGIN, END: Begin is the first statement and end is the last statement.
3 INPUT, GET, READ: The keyword is used to inputting data.
4 COMPUTE, CALCULATE: used for calculation of the result of the given expression.
5 ADD, SUBTRACT, INITIALIZE used for addition, subtraction and initialization.
6 OUTPUT, PRINT, DISPLAY: It is used to display the output of the program.
7 IF, ELSE, ENDIF: used to make decision.
8 WHILE, ENDWHILE: used for iterative statements.
9 FOR, ENDFOR: Another iterative incremented/decremented tested automatically.

Advantages
 It is easier to develop a program from a pseudocode than with a flowchart.
 It is easy to translate pseudocode into a programming language.
 Unlike flowchart, pseudocode is compact and does not tend to run over many pages.

Mr. P. J. Merbin Jose


9

 As compared to a flowchart, it is easier to modify the pseudocode of program logic, when


program modifications are necessary.

Disadvantages/Limitations
 Does not provide visual representation of the program logic.
 There is no standardized style or format. Programmers use their own style of writing
pseudocode. So one pseudocode may be different from another.
 For a beginner, it is more difficult to follow the logic or write pseudo code as compared
to flowchart.
 Pseudocode cannot be compiled nor executed.

Examples: Pseudocode
Problem 1: Addition of two numbers
BEGIN
GET a, b
ADD c = a + b
PRINT c
END

Problem 2: Calculate sum and average for n numbers


BEGIN
INITIALIZE sum=0, i=1
READ n
FOR i <=n, then
COMPUTE sum = sum +i
CALCULATE i=i+1
END FOR
COMPUTE avg = sum/n
DISPLAY sum, avg
END

Problem 3: Calculate area of circle


BEGIN
READ radius, r
INITIALIZE pi=3.14
CALCULATE Area=pi * r *r
PRINT Area
END

Problem 4: Read Number n and print the integers counting up to n


BEGIN
READ n
INITIALIZE i to 1
FOR i <= n, then
DISPLAY i
INCREMENT i
END FOR
END

Mr. P. J. Merbin Jose


10

Problem 5: Find the greater number between two numbers


BEGIN
Read A, B
IF A < B
BIG = B
SMALL = A
ELSE
BIG = A
SMALL = B
WRITE BIG, SMALL
END

Problem 6: To determine whether a student is pass or fail


BEGIN
READ grade
IF grade >= 50
Print "pass"
ELSE
Print "fail“
END

Syntax for if else: Example: Greatest of two numbers


IF (condition)THEN BEGIN
statement READ a,b
... IF (a>b) THEN
ELSE DISPLAY a is greater
statement ELSE
... DISPLAY b is greater
ENDIF END IF
END
Syntax for For: Example: Print n natural numbers
FOR( start-value to end-value) DO BEGIN
statement GET n
... INITIALIZE i=1
ENDFOR FOR (i<=n) DO
PRINT i
i=i+1
ENDFOR
END
Syntax for While: Example: Print n natural numbers
WHILE (condition) DO BEGIN
statement GET n
... INITIALIZE i=1
ENDWHILE WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
11

1.3.2) FLOWCHARTS

 Flow chart is defined as graphical or diagrammatic or pictorial representation of the logic


for problem solving.
 A flowchart is drawn using boxes of different shapes with lines connecting them to show
the flow of control.
 The purpose of flowchart is making the logic of the program clear in a visual
representation.
 A flowchart is a picture of the separate steps of a process in sequential order.

Table: List of symbols

Advantages/Benefits of flowchart:

1. Communication: Flowcharts are better way of communicating the logic of a system to all.

2. Effective analysis: With the help of flowchart, problem can be analyzed in more effective
way.

3. Proper documentation: Program flowcharts serve as a good program documentation, which


is needed for various purposes.

4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and
program development phase.

5. Proper Debugging: The flowchart helps in debugging process.

6. Efficient Program Maintenance: The maintenance of operating program becomes easy with
the help of flowchart. It helps the programmer to put efforts more efficiently on that part.
12

Disadvantages/Limitation of using flowchart

1. Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart
becomes complex.

2. Difficult to modify: If alterations are required the flowchart may require re-drawing
completely.

3. Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes


a problem.

4. Cost: For large application the time and cost of flowchart drawing becomes costly.

Guidelines for Drawing a Flowchart


Flowcharts are usually drawn using some standard symbols; however, some special
symbols can also be developed when required. Some standard symbols, which are frequently,
required for flowcharting many computer programs.

1. The flowchart should be clear, neat and easy to follow.


2. While drawing a proper flowchart, all necessary requirements should be listed out in logical
order.
3. The flowchart must have a logical start and finish.

 Terminator: An oval flow chart shape indicates the start or end of the process,
usually containing the word “Start” or “End”.

 Only one flow line is used with a terminal symbol.

4. Only one flow line should come out from a process symbol.

 Process: A rectangular flow chart shape indicates a normal/generic process flow


step. For example, “Add 1 to X”, “M = M*F” or similar.

5. Only one flow line should enter a decision symbol. However, two or three flow lines may
leave the decision symbol.
13

 Decision: A diamond flow chart shape indicates a branch in the process flow.
This symbol is used when a decision needs to be made, commonly a Yes/No
question or True/False test.

6. If the flowchart becomes complex, it is better to use connector symbols to reduce the number
of flow lines.
 Connector: A small, labeled, circular flow chart shape used to indicate a jump in
the process flow. Connectors are generally used in complex or multi-sheet
diagrams.

7. Data: A parallelogram that indicates data input or output (I/O) for a process. Examples: Get X
from the user, Display X.

Input /Output

8. Delay: Used to indicate a delay or wait in the process for input from some other process.

9. The flow lines should not cross each other.

 Arrow: Used to show the flow of control in a process. An arrow coming from
one symbol and ending at another symbol represents that control passes to the
symbol the arrow points to.

10. Function: Used to represent function call

Problem 1: Find the area of a circle of radius r.


14

Problem 2: Draw the flowchart to find the largest number between A and B

Problem 3: Flowchart for the problem of printing even numbers between 0 and 99.

Problem 4: Convert temperature Fahrenheit to Celsius.


15

Difference between Algorithm, Flowchart, and Pseudocode

S.No. ALGORITHM FLOWCHART PSEUDOCODE


An algorithm is a Flowchart is a pictorial Pseudocode is a readable,
sequence of instructions representation of an formally language
1.
used to solve a particular algorithm to solve a representation of the algorithm.
problem. particular problem.
It can be represented It uses different kind of It uses structured constructs of
2. using a flowchart or a boxes and lines for the programming language for
pseudocode. representation. representation.
The user needs The user does not require The user does not require the
knowledge to write an the knowledge of a knowledge of a programming
3. algorithm for a task. programming language to language to write or understand
draw or understand a a pseudocode.
flowchart.

1.3.3) PROGRAMMING LANGUAGE

A programming language is a set of symbols and rules for instructing a computer to


perform specific tasks. The programmers have to follow all the specified rules before writing
program using programming language. The user has to communicate with the computer using
language which it can understand.

Types of programming language


1. Machine language
2. Assembly language
3. High level language

1) Machine language:

The computer can understand only machine language which uses 0‟s and 1‟s. In machine
language the different instructions are formed by taking different combinations of 0‟s and 1‟s.

Advantages

i) Translation free
Machine language is the only language which the computer understands. For executing
any program written in any programming language, the conversion to machine language is
necessary. The program written in machine language can be executed directly on computer. In
this case any conversion process is not required.

ii) High speed


The machine language program is translation free. Since the conversion time is saved, the
execution of machine language program is extremely fast.

Disadvantage
 It is hard to find errors in a program written in the machine language.
 Writing program in machine language is a time consuming process.
16

iii) Machine dependent


According to architecture used, the computer differs from each other. So machine
language differs from computer to computer. So a program developed for a particular type of
computer may not run on other type of computer.

2) Assembly language
To overcome the issues in programming language and make the programming process
easier, an assembly language is developed which is logically equivalent to machine language but
it is easier for people to read, write and understand.

Assembly language is symbolic representation of machine language. Assembly languages


are symbolic programming language that uses symbolic notation to represent machine language
instructions. They are called low level language because they are so closely related to the
machines.

Example: ADD a, b

Assembler
Assembler is the program which translates assembly language instruction in to a machine
language.

Advantage
Easy to understand and use.
It is easy to locate and correct errors.

Disadvantage
i) Machine dependent
The assembly language program which can be executed on the machine depends on the
architecture of that computer.

ii) Hard to learn


It is machine dependent, so the programmer should have the hardware knowledge to
create applications using assembly language.

iii) Less efficient


 Execution time of assembly language program is more than machine language program.
 Because assembler is needed to convert from assembly language to machine language.

3) High level language


High level language contains English words and symbols. Hence, specified rules are to be
followed while writing program in high level language. The interpreter or compilers are used for
converting these programs in to machine readable form.
The programs that translate high level language to machine language are called
interpreter or compiler.

Compiler:
A compiler is a program which translates the source code written in high level language
in to object code which is in machine language. Compiler reads the whole program written in
17

high level language and translates it to machine language. If any error found, it display error
message on the screen.

Interpreter
Interpreter translates the high level language program in line by line manner. The
interpreter translates a high level language statement in a source program to a machine code and
executes it immediately before translating the next statement. When an error is found, the
execution of the program is halted and error message is displayed on the screen.

Advantages

1. Readability
2. High level language is closer to natural language so they are easier to learn and
understand.
3. Machine independent
4. High level language program have the advantage of being portable between machines.
5. Easy debugging
6. Easy to find and correct error in high level language

Disadvantage
Less efficient

1.4 ALGORITHMIC PROBLEM SOLVING


Every problem‟s solution starts with a plan and that plan is called an algorithm. So, an
algorithm is a plan for solving a problem. There are many ways to write an algorithm. Some are
very informal, some are quite formal and mathematical in nature, and some are quite graphical.
The development of an algorithm is the key step in algorithmic problem solving. Once an
algorithm is developed, it can be translated into a computer program in some programming
language.

The algorithmic problem solving process consists of five major steps:

Step 1: Obtain a description of the problem


Step 2: Analyze the problem
Step 3: Develop a high-level algorithm
Step 4: Refine the algorithm by adding more details
Step 5: Review the algorithm
Step 1: Obtain a description of the problem.
In the following discussion, the word client refers to a person who wants to find a solution to a
problem, and the word developer refers to a person who finds a way to solve the problem. The
developer must create an algorithm that will solve the client's problem.
The client is responsible for creating a description of the problem, but this is often the
weakest part of the process. It's quite common for a problem description to suffer from one or
more of the following types of defects:
 the description relies on unstated assumptions,
18

 the description is ambiguous,


 the description is incomplete,
 the description has internal contradictions.
These defects arise due to carelessness by the client. Part of the developer's responsibility is
to identify defects in the description of a problem, and to work with the client to remedy those
defects.
Step 2: Analyze the problem.
The purpose of this step is to determine both the starting and ending points for solving the
problem. This process is similar to a mathematician determining what is given and what must be
proven. A good problem description makes it easier to perform this step.
Asking the following questions often helps to determine the starting point.
 What data are available?
 Where is that data?
 What formulas pertain to the problem?
 What rules exist for working with the data?
 What relationships exist among the data values?
When determining the ending point, we need to describe the characteristics of a solution. In other
words, how will we know when we're done? Asking the following questions often helps to
determine the ending point.
 What new facts will we have?
 What items will have changed?
 What changes will have been made to those items?
 What things will no longer exist?
Step 3: Develop a high-level algorithm.
An algorithm is a plan for solving a problem, but plans come in several levels of detail.
It's usually better to start with a high-level algorithm that includes the major part of a solution,
but leaves the details until later.
Step 4: Refine the algorithm by adding more detail.
A high-level algorithm shows the major steps that need to be followed to solve a
problem. Our goal is to develop algorithms that will lead to computer programs. Consider the
capabilities of the computer and provide enough detail so that someone else could use our
algorithm to write a computer program.
For larger, more complex problems, it is common to go through this process several
times. Each time, more details are added to the previous algorithm, for further refinement. This
technique of gradually working from a high-level to a detailed algorithm is often called stepwise
refinement.
Stepwise refinement is a process for developing a detailed algorithm by gradually adding
details to a high-level algorithm.
19

Step 5: Review the algorithm.


The final step is to review the algorithm. First, work through the algorithm step by step to
determine whether or not, it will solve the original problem. Asking these questions and seeking
their answers is a good way to develop skills that can be applied to the next problem.
 Does this algorithm solve a very specific problem or does it solve a more general
problem? If it solves a very specific problem, should it be generalized?
For example, an algorithm that computes the area of a circle having radius 5.2 meters
(formula π*5.22) solves a very specific problem, but an algorithm that computes the area of
any circle (formula π*R2) solves a more general problem.
 Can this algorithm be simplified?
For example, one formula for computing the perimeter of a rectangle is:
length + width + length + width
A simpler formula would be:
2.0 * (length + width)
 Is this solution similar to the solution to another problem? How are they alike? How are
they different?

For example, consider the following two formulae:


Area Rectangle = length *width
Area Triangle = 0.5 * base * height

Similarities: Each computes an area. Each multiplies two measurements.


Differences: Different measurements are used. The triangle formula contains 0.5.
Hypothesis: Perhaps every area formula involves multiplying two measurements.
Once an algorithm is developed, translate it into a computer program in some
programming language.

1.5 SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS


1.5.1) ITERATION
A sequence of statements is executed until a specified condition is true is called iterations.
a) for loop
b) While loop
a) for loop
The 'for' loop used only when we already knew the number of iterations.
The „for‟ loop starts with the initial value of the loop counter and terminates when the
final value of the loop counter is reached. Since the „for‟ loops iterate a fixed number of times in
advance, they are also known as definite repetition loops.
Example:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
20

Output:
apple
banana
cherry

Flowchart

b) while Loop

Usually the 'while' loop is used when the number of iteration are not exactly known. It is
helpful when we don‟t know exactly how many times loop body will be executed.

In a while loop, test_expression is checked first. If it is true, the loop body will be
executed, otherwise it will not. After one iteration, the test_expression is checked again. This
process continues until the test_expression evaluates to False.

Since the number of times a loop will iterate is not known in advance, this type of loop is
also known as indefinite repetition loop.

Flowchart

Example:
count = 0
while(count < 3):
count = count + 1
print("Hai Hello")
Output:
21

Hai Hello
Hai Hello
Hai Hello

1.5.2) RECURSION

 A function that calls itself is known as recursion.


 Recursion is a process by which a function calls itself repeatedly until some specified
condition has been satisfied.

Example: Finding the factorial of a number using Recursion

Main function

Step 1: Start
Step 2: Read number n
Step 3: Call the subroutine factorial(n)
Step 4: Display the returned value as F
Step 5: Stop

Sub function factorial (n)

Step 1: Check whether given number n is equal to 1. If true the return 1 otherwise goto Step2
Step 2: Multiply the given number n with function call factorial() passing argument n-1 and store
the result in variable fact.
fact = n * factorial(n-1)
Step 3: Return the variable fact

Pseudo code for factorial using recursion

Main function:

BEGIN
GET n
CALL factorial(n)
PRINT fact
22

END

Sub function factorial(n):

IF(n= =1) THEN


fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)

Recurrence relation problems are examples of recursion.


Consider the problem to find n!
n!=n*(n-1)!

Eg: 5!=

# An example of a recursive function to find the factorial of a number


def factorial(n):
print "This is a recursive function to find the factorial of an integer"
if n = = 1:
return 1
else:
return (n * factorial(n-1))
num = 4
print("The factorial of", num, "is", factorial(num))

When we call this function with a positive integer, it will recursively call itself by decreasing the
number. Actual execution of recursive function is given below:

factorial(4) # 1st call with 4


4 * factorial(3) # 2nd call with 3
4 * 3 * factorial(2) # 3rd call with 2
4 * 3 * 2 * factorial(1) # 4th call with 1
4 * 3 * 2 * 1 # return from 4th call as number=1
4 * 3 * 2 # return from 3rd call
4 * 6 # return from 2nd call
24 # return from 1st call
23

Advantages of Recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.

Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.

Recursion and iteration:


Recursion and iteration both repeatedly executes the set of instructions. Recursion is
when a statement in a function calls itself repeatedly. The iteration is when a loop repeatedly
executes until the controlling condition becomes false. The primary difference between recursion
and iteration is that is a recursion is a process, always applied to a function. The iteration is
applied to the set of instructions which we want to get repeatedly executed.

BASIS FOR
RECURSION ITERATION
COMPARISON
Basic The statement in a body of function Allows the set of instructions to be
calls the function itself. repeatedly executed
Iteration includes initialization,
In recursive function, only termination condition, and execution of
Format condition (base case) is specified. statement within loop and update
(increments and decrements) the
control variable.
A conditional statement is included in The iteration statement is repeatedly
Termination the body of the function to force the executed until a certain condition is
function to return without recursion reached.
call being executed.
If the function does not converge to If the control condition in the
Condition some condition called (base case), it iteration statement never becomes
leads to infinite recursion. false, it leads to infinite iteration.
Infinite Infinite recursion can crash the Infinite loop uses CPU cycles
Repetition system. repeatedly.
Recursion is always applied to Iteration is applied to iteration
Applied
functions. statements or "loops".
The stack is used to store the set of
Stack new local variables and parameters Do not uses stack.
each time the function is called.
Recursion possesses the overhead of
Overhead No overhead
repeated function calls.
Speed Slow in execution. Fast in execution.
Size of Code Recursion reduces the size of the code. Iteration makes the code longer.
24

1.6 ILLUSTRATIVE PROBLEMS

1.6.1 Find minimum in a list

Description
To find the minimum value into an array of items, Take the first element and compare its
value against the values of other elements. Finally we find the minimum.

Algorithm:

Step 1: Start
Step 2: Read number of elements „n‟ and elements of a List
Step 3: Assign the first value of list as minimum value
Step 4: Compare this value from 1st position to n-1th position
Step 5: When a value is smaller than the present minimum value is found, it becomes the new
minimum
If List[i] < min then
min = List[i]
Step 6: Repeat the step until i becomes n
Step 7: Display min is the smaller number
Step 8: Stop

Flow Chart:
25

Example: Consider an array


0 1 2 3 4
50 40 5 9 45
Step 1: 0 1 2 3 4
50 40 5 9 45 min = 50
Step 2: 0 1 2 3 4
50 40 5 9 45 min = 40
Step 3: 0 1 2 3 4
50 40 5 9 45 min = 5
Step 4: 0 1 2 3 4
50 40 5 9 45 min = 5
Step 5: 0 1 2 3 4
50 40 5 9 45 min = 5
Once we reached at nth location of the array, terminate the procedure of finding minimum value.
Now the minimum value is 5.

1.6.2. Insert a card in a list of sorted cards


Description
To insert a card in the sorted card, we must increase the list size with 1. We can insert a
new card in the appropriate position by comparing each element‟s value with the new card.
When the position is found, we have to move the remaining elements by one position up and the
card can be inserted.

Consider the cards are sorted in following manner


5 6 8 9 10

Now the card is,

7
Steps
0 1 2 3 4 5

5 6 8 9 10

0 1 2 3 4 5

5 6 7 8 9 10
26

Algorithm:

Step 1: Start
Step 2: Read n
Step 3: Initialize i = 0
Step 4: If i < n, then goto step 4.1, 4.2 else goto step 5
Step 4.1: Read a[i]
Step 4.2: i = i + 1 goto step 4
Step 5: Read item
Step 6: Calculate i = n - 1
Step 7: If i >= 0 and item<a[i], then go to step 7.1, 7.2 else goto step 8
Step 7.1: a[i+1] = a[i]
Step 7.2: i = i - 1 goto step 7
Step 8: Assign a[i+1] = item
Step 9: Compute n = n + 1
Step 10: Assign i = 0
Step 11: If i < n, then goto step 11.1, 11.2 else goto step 12
Step 11.1: Print a[i]
Step 11.2: i = i + 1 goto step 10

Step 12: Stop

Pseudocode:

BEGIN
READ n
FOR i = 0 to n, then
READ a[i]
INCREMENT i
END FOR
READ item
FOR i = n - 1 to 0 and item<a[i], then
CALCULATE a[i+1] = a[i]
DECREMENT i
END FOR
ASSIGN a[i+1] = item
COMPUTE n = n + 1
ASSIGN i = 0
FOR i = 0 to n, then
PRINT a[i]
INCREMENT i
END FOR
END
27

Flow Chart

1.6.3. Guess an integer number in a range


Description

Imagine you are trying to guess a number in a range. The objective is to randomly
generate integer number from 0 to n. Then the user has to guess the number. If the user guesses
the number correctly, output an appropriate message.

If the guessed number is less than the random number generated, output the message
“Your guess is lower than the number. Guess again”, otherwise output the message, “Your guess
is higher than the number. Guess again”.
28

Then the user enters another number. This process is repeated until the player enters the
correct number.

Algorithm:
Step 1: Start
Step 2: Generate the random number, num
Step 3: Repeat the following steps until the player has guessed the correct number.
3.1 Enter the number to guess
3.2 if(guess is equal to num)
Print “You guessed the correct number”
else
if(guess<num)
Print “Your guess is lower than the number. Guess again”
else
Print “Your guess is higher than the number. Guess again”
Step 4: Stop
Flow Chart:
start

Generate random number, num

Read guessed number, guess

True
If
(guess Number is higher
>num)

True
If
(guess < Number is lower
num)

If
(guess
==num)

Guessed number is correct

stop
29

Example:
Consider to guess a number between 1 and 100. The number selected for guess is 82.
Now the user wants to guess this number.

The best strategy is choosing 50 as the first guess. If that guess is high, then the user
should guess 25. If 50 is low than guess 75. Each guess, select a new midpoint by adjusting the
lower range or the upper range of the numbers, which becomes the next guess.

This strategy will eventually guess the correct number.

Following example demonstrate how this method works if the number to be chosen is 82.

Guessing game – Secret number is 82


30

1.6.4. Tower of Hanoi


Tower of Hanoi is one of the classical problems of computer science. The problem states
that,
1) There are three Stands (Stand X, Y, Z) on which a set of disks, each with a
different diameter, are placed.
2) Initially, the disks are stacked on Stand X, in order of size, with the largest disk at the
bottom.

In figure 1(a), the three stands are displayed in the initial state. The Stand X contains three
disks and there are no disks on Stand Y and Z.

Fig 1(a)

The objective is, to move an entire stack of disks from Stand X to Stand Z. Three simple
rules are followed:

1. Only one disk can be moved at a time.


2. Each move consists of taking the upper disk from one of the stacks and placing it on top
of another stack. In other words, a disk can only be moved if it is the uppermost disk on a
stack. Only top-most disk can be moved to another needle.
3. No larger disk may be placed on top of a smaller disk.

In figure 1(b), the top-most disk is moved from Stand X to Z. The arrow indicates the movement
of disk from one stand to another stand.

In figure 1(c), the disk from the X stand moves to the Y stand.

In figure 1(d), the disk from Z stand moves to Y stand, Stand Y has two disks.

In figure 1(e), the disk from the X stand moves to the Z stand. Now there is no disk in the X
stand.

In figure 1(f), the disk from the Y stand moves to the X stand.

In figure 1(g), the disk from the Y stand moves to the Z stand. The Y stand contains no disk.
31

In figure 1(h), the disk from the X stand moves to the Z stand. Thus, the Z stand contains all the
three disks of the X stand shown in Figure 1(a). Thus, the problem is solved.

Fig 1(b)

Fig 1(c) Fig 1(d)

Fig 1(e) Fig 1(f)

Fig 1(g) Fig 1(h)


32

Algorithm:
Step 1: Start
Step 2: Read n
Step 3: Calculate move=pow(2,n)-1
Step 4: Function call T(n,Beg,Aux,End) recursively until n=1
Step 4.1: If (n= =1), then goto step 5 else goto step 4.2
Step 4.2: T(n-1,Beg,End,Aux)
T(1,Beg,Aux,End) , Move disk from source to destination
T(n-1,Aux,Beg,End)
Step 5: Stop

Pseudocode:

BEGIN
READ n
CALCULATE move=pow(2,n)-1
FUNCTION T(n,Beg,Aux,End) Recursively until n=1
PROCEDURE T(n,Beg,Aux,End)
IF (n= =1) THEN
No disk to move
ELSE
T(n-1,Beg,End,Aux)
T(1,Beg,Aux,End), move disk from source to destination
T(n-1,Aux,Beg,End)
END PROCEDURE
END

Mr. P. J. Merbin Jose


33

Flow Chart:

Mr. P. J. Merbin Jose

You might also like