GE8151 Unit I
GE8151 Unit I
UNIT I
ALGORITHMIC PROBLEM SOLVING
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.
• 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.,)
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.
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.
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.
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.
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.
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
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
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.
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.
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.
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
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: 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
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.
Main function()
Step 1: Start
Step 2: Call the function add()
Step 3: Stop
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.
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.
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.
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
1.3.2) FLOWCHARTS
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.
4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and
program development phase.
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
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.
4. Cost: For large application the time and cost of flowchart drawing becomes costly.
Terminator: An oval flow chart shape indicates the start or end of the process,
usually containing the word “Start” or “End”.
4. Only one flow line should come out from a process symbol.
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.
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.
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.
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.
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
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.
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.
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
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
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
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
Main function:
BEGIN
GET n
CALL factorial(n)
PRINT fact
22
END
Eg: 5!=
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:
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.
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
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
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
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
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
True
If
(guess Number is higher
>num)
True
If
(guess < Number is lower
num)
If
(guess
==num)
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.
Following example demonstrate how this method works if the number to be chosen is 82.
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:
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)
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
Flow Chart: