Professional Documents
Culture Documents
Algorithm and Program Design
Algorithm and Program Design
Bharati Vidyapeeth
102 : ALGORITHM AND
Writers Team
REVIEW
COURSE SUBJECT FACULTY
Design of Algorithms
3.1 Design of Algorithm: Introduction
3.2 Developing Algorithm for Fundamental Problems:
3 3.2.1 Swapping 34-43
3.2.2 Counting
3.2.3 Finding the Sum, Product of a finite list of numbers
3.2.4 Finding maximum, minimum of a finite list of numbers
Unit Contents Page No.
CHAPTER – 1
INTRODUCTION: ALGORITHM AND
NOTES
PROGRAM DESIGN
I have a problem!
I need to thank, my aunt Mrs. Khanna for sending a birthday present to me.
There are many ways to send thank you message:
• I could send her an email.
• I could call her on the phone.
• I can send a Thanks message from post.
• I can write Thanks message on her Facebook wall.
• I could personally go to her house and saying thank you.
Introduction:
Algorithm and
Program Design 11
Algorithm And So, there are many ways to solve this problem. But the point is that I must
Program Design decide:
• How I want to solve the problem?
NOTES
• What is the appropriate tool to implement my plan?
In above case, I can use Postal service, telephone or internet as a tool to
solve my problem. Similarly, computer is a tool to implement the solution for a
given problem. Computer is only a tool; it needs a set of instructions to solve the
problem. These instructions specify the steps that a computer must follow to
implement a solution. An algorithm is a set of instructions to solve a problem.
So, to solve a problem, you must design an algorithm and this algorithm can be
translated into a computer program.
Problem solving requires thought process, planning, logical accuracy and
deep understanding of requirements. The challenging experience of problem
solving enhances the personal creativity and expression. If we use problem
solving in this spirit, the chances of success for computer problem solving are
greatly amplified. This chapter creates foundation for problem solving through
computers, understand the concepts of procedure and algorithms, how algorithms
can be represented through pseudo codes and flowcharts, tracing of the
algorithms. To understand all above concepts few examples are explained as
swapping, counting, finding the sum, product, maximum, minimum, of a list of
numbers.
Sample Algorithms
To get better understanding, let us discuss simple examples of Algorithm:
Example1: Average of Two numbers
1. START
2. Input: Two numbers
Introduction:
3. Add the two numbers Algorithm and
Program Design 13
Algorithm And
4. Divide the result by 2
Program Design
5. Return the result by step 2
NOTES 6. END
1.3.1 Flowcharts
Introduction: Flowcharts are a simple diagram that illustrates the sequence of operations
Algorithm and to be performed to get a solution of a problem. It allows you to identify sequence
14 Program Design
of flow of instructions that any product or service follow. Flowcharts can be Algorithm And
applied to anything from travel of invoice to flow of material to the steps in Program Design
making sales or things like servicing a product.
Flow charts are effective in determining how a process how the information NOTES
lose while solving the problem.
It is a pictorial representation of sequence of operations that are applied to
find the solution of a problem. It gives you at a glance view of a process.
1. Start/End
This symbols indicate the start, and, and pause state of a process in a
program logic flow. It is the first and the last symbol that is used in a
flowchart. If in a program logic there is an option for the pause(halt),
that situation can be indicated with the help of this symbol.
2. Process/task
This symbol represents any arithmetic or data manipulation operation. Introduction:
Arithmetic process involved addition, subtraction, multiplication, and Algorithm and
Program Design 15
Algorithm And division. Processes also represent logical process of moving data from
Program Design one memory location to another, for example assignment statements.
NOTES
3. Decision
This symbol indicates a point at which one or two more alternatives
are possible for a given problem.
Following few of the examples to represent where decision box can be used:
4. Flow control
Lines with arrowhead indicate the flow of operation in which sequence
of instructions are executed. The normal flow of institution in a
flowchart is from top to bottom and left to right. Arrowhead is used
when the flow of operation changes and they are used at the entry point
of all flowchart symbols. A good flowchart avoids crossing the flow
control lines.
Introduction:
Algorithm and
16 Program Design
5. Input/output Algorithm And
Program Design
This symbol indicates all the program to read input from input devices
(Keyboard, mouse, scanner)and write data to output devices (monitor,
printer). NOTES
Sample flowcharts
Let us understand the art of flowchart with the help of example. Let us
consider a student who appears for an examination for 10 subjects. Each subject
has maximum marks of 100. Name of the student, roll number, and marks
obtained in various subjects are input data for the problem. Draw a flowchart to
calculate percentage of marks obtained by a student and print it with his name
and roll number.
Solution
1.3.2 Pseudocode
Pseudo code is a representation of a programming logic. “Pseudo” means
Introduction: imitation and” code” means instructions written in a programming language.
Algorithm and Hence, pseudo code is an invitation of actual programming instructions. Pseudo
18 Program Design
code is written in a natural language that a computer cannot understand. But, Algorithm And
pseudo code uses a structure that resembles a set of computer instructions. When Program Design
a programmer uses pseudo code for planning a program, he can concentrate
solely on developing the logic of the program without worrying about the syntax NOTES
for writing the program instructions. Pseudo codes do not have any Syntax rules
for writing instructions. When the programmer is convinced with the program
logic, he can convert the pseudo code easily into suitable programming language.
As the pseudo code emphasizes more on program design, it is also known as
program design language (PDL).
For any Complex programming problem, the program logic can be
expressed by using following 3 simple logic control structures:
1. Sequence logic
2. Selection logic
3. Iteration or looping logic
By using these three logic structures, program logic becomes easy to
understand, as we can read them from top to bottom. This reduces program errors
and time spent in program testing. Writing the program logic by using these three
basic control structures is a scientific approach to solve a programming problem
and is termed as structured programming technique. In good programming
practices, programmer should develop program logic by using these three basic
logical structures.
So below are the pseudo codes for the three basic logical structures along
with their flowcharts:
1. Sequence logic
This logic performs instructions one after another in a sequence. Instructions
are executed in the order they have been written. Logic flow of the pseudo code
is from top to bottom. Figure 3 shows and flowchart and pseudo code for a
sequential logic structure.
Figure 3: flowchart and pseudo code for a sequential logic structure Introduction:
Algorithm and
Program Design 19
Algorithm And 2. Selection Logic
Program Design
Selection logic this logic is used for making decisions and for selecting the
proper passed out of two or more alternative path in program logic. It is also
NOTES known as decision logic. Selection logic is depicted as either an IF....THEN or
an IF.....THEN.....ELSE structure.
IF....THEN ...ELSE structure means that if the condition is true, then do
process 1, else if the condition is not true, do process 2.Hence, program logic
execute either process 1 or process 2 depending on whether the specified
condition is true or false.
Iteration logic
it is used to produce loops when one or more instructions may be executed
several times depending on some of the conditions. It uses structures called
DO...WHILE and REPEAT....UNTIL.
Introduction:
Algorithm and
20 Program Design
Algorithm And
Program Design
NOTES
TASK LIST
Read name, hourly rate, hours worked, deduction rate
Compute gross, deduction, net pay
Is gross<= 100?
Yes: calculate deduction
No: No deduction
PSEUDOCODE
READ name, hourlyRate, hoursWorked
grossPay= hourlyRate*hoursWorked
IF grossPay >= 100
deduction = grossPay * deductionRate
ELSE
deduction = 0
ENDIF
netPay = grossPay- deduction
WRITEname, grossPay, deduction, netPay
Following are some pseudo codes for problems like swapping, counting,
finding sum, product, maximum, minimum of a list of numbers.
1. Task: Swap Two numbers say a, b
*****
Introduction:
Algorithm and
24 Program Design
Algorithm And
Program Design
CHAPTER – 2
NOTES
CONCEPT OF STRUCTURED PROGRAMMING
AND PROCEDURE ORIENTED PROGRAMMING
2.1 Introduction
2.2 Types of programming languages
2.2.1 Procedural programming language
2.2.2 Structured programming languages
2.3 Basic control structures
2.3.1 Sequential control structures
2.3.2 Selection/conditional control structures
2.3.3 Iteration control structures
2.1 INTRODUCTION
Concept of Structured
Programming
and Procedure
26 Oriented Programming
Algorithm And
Program Design
2.3 BASIC CONTROL STRUCTURES
NOTES
Any computer programming problem can be written by using following
basic control structures:
1. Sequential control structures
2. Selection/conditional control structures
3. Decision/iteration control structures
Step 1: START
Step 2: READ three numbers a, b, c.
Step 3: find the SUM of 3 numbers.
Concept of Structured
Step 4: Divide the SUM by 3.
Programming
Step 5: END and Procedure
Oriented Programming 27
Algorithm And Flowchart for the given problem:
Program Design
NOTES
procedure Average()
READ a,b,c
set sum to 0, set average to 0
sum ← a+b+c // sum holds the value after adding a, b and c
average ← sum/3 // average holds the value after dividing sum by 3
WRITE “ Average of a,b and c is “average
end procedure
Concept of Structured
Programming
and Procedure
28 Oriented Programming
Algorithm And
Program Design
NOTES
Following are the sum of the control structures used for selection
• if
• if/else
• switch
If statement
This statement checks for the condition, if the condition is ‘true’, execute
the statements in the “if” block, otherwise it exists the “if block”.
Syntax
If-else
This condition is used when for a given problem you have two alternatives.
If the condition is satisfied, the statements in the” if block “ are executed,
otherwise, the statements in the “ else block” executed.
Syntax
Example
let us understand selection control structure with the help of an
algorithm and its flowchart and its Pseudo code. Concept of Structured
Programming
and Procedure
Oriented Programming 29
Algorithm And Given problem
Program Design
If the student’s marks are less than 40, the student is “Fail”, otherwise,
the student is “Pass”.
NOTES
Algorithm
Step 1: START
Step 2: READ Marks of a student say MARKS.
Step 3: If MARKS are less than 40, output “Fail” and go to Step 5.
Step 4: If MARKS are grater or equal to 40, output “Pass” and go to Step 5.
Step 5: END
Procedure Pass_Fail()
READ MARKS
If (MARKS < 40)
WRITE “Fail”
Else
WRITE “Pass “
End procedure
Concept of Structured
Programming
and Procedure
30 Oriented Programming
Switch case Algorithm And
Program Design
This statement is used when for a given problem or a variable you have
more than two alternatives or values respectively.
NOTES
Syntax
While
This statement associates condition with the sequence of statements. The
condition is evaluated before each iteration. If the condition is satisfied, the
sequences of statements are executed and the control goes back to the top of the
loop. If the condition is not satisfied the loop is not executed and the control goes
to the next statement after the loop. the number of hydration executed depends
upon some condition. As the condition is tested on the top of the loop, the number Concept of Structured
of time sequence executes could be zero also. Programming
and Procedure
Oriented Programming 31
Algorithm And Syntax
Program Design
NOTES
Do-while
This loop is quite similar to while loop. The only difference between while
and do while loop is that it executes the statements once before checking the
condition.
Syntax
For
In for loop the block of statements is executed repetitively for a specified
range described in condition. In while loop the number of times the loop execute
is unknown but in the phone, the number of iterations are known before the loop
is executed. In for loop condition we have to specify the lower bound from which
the loop starts and the upper bound till which the loop is executed. The range for
which the loop is executed calculated when the 4 rupees first time entered and is
never reevaluated. After each iteration the loop counter is incremented. By default
the iteration proceeds from lower bound to the higher bound. But, if the user
specified upper bound first and lower bound later then after each iteration the
loop counter is decremented.
Syntax
Concept of Structured
Programming
and Procedure
32 Oriented Programming
Algorithm And
Program Design
NOTES
*****
Concept of Structured
Programming
and Procedure
Oriented Programming 33
Algorithm And
Program Design
CHAPTER – 3
DESIGN OF ALGORITHMS
NOTES
It means memory location of variable X will store value 236 and memory
location of variable Y will store value 728. Our intention is that value at memory
location of variable X should be 728. After exchange of values following should
be the situation:
Final values of X and Y:
X Y
Design of Algorithms 35
Algorithm And The first equation (1) will cause the value of Y to be stored in variable X as
Program Design shown below:
X Y
NOTES
and after the execution of second equation(2), we will end up with the
situation expressed below:
X Y
This is not the expected result. After executing equation (1) and (2), we
could not get the desired results because when we made first assignment using
equation (1) as below:
X := Y;
The value of variable Y is copied into value of variable X. After this
assignment, we lost the value that is stored in variable X. We want to store the
value of X (which is lost now) in variable Y.
To get the desirable results we can state instructions in a following way:
new value of X := old value of Y;
new value of Y := old value of X;
It means when we are executing equation (2), we were not using the old
value of X. So to solve the problem we need to find out a way where we can save
the old value of X.
When we make following assignment:
X := Y;
At this level the value of Y will be copied into value of X. Before executing
this step we must know the value of X variable in to some other temporary
variable say temp. So we can replace equation (1) with following steps:
temp:= X;
X := Y;
After performing the steps, the situation will be as below:
X temp Y
36 Design of Algorithms
Now if we store the value of temp variable in Y as following Algorithm And
Program Design
Y := temp;
After execution of this stuff we have:
NOTES
X temp Y
If we revise the above process we can outline the process in the following
steps:
Algorithm description
Step 1 : START.
Step 2 : Save the value of variable X in variable temp.
Step 3 : assign to X the original value of Y.
Step 4 : assign to Y the original value of X that is now stored in Temp.
Swapping two variables is generally used in exchange mechanism in
programming which is implemented to accept two variables and return they
exchange values
Problem statement
We have a list of n students examination marks. We have to count number
of pass students out of N students. Assume (marks are in range of 0 to 100).
Student with their marks greater or equal to 50 is pass.
Algorithm development
Before developing and computer algorithm, try to solve the problem by
hand. Suppose you have list of numbers as following:
55,29,60,38,50,59,60
• You can start scanning the list from left direction.
• First mark is 55(check if it is >= 50), Hence first student is passed.
• second student has marks 29 ( so there is no change in count of pass
students)
• next student has 60 marks ( increment previous pass student count by 1)
• repeat this process for all the numbers in the list
Design of Algorithms 37
Algorithm And Now, you can observe that how the count of passed student is stored.
Program Design
When as student is pass: we increment the previous count value by 1.
So we can calculate current count as following:
NOTES
Current_ count = previous_count +1 ———————————-A
If the student is not passed then no change in current_count.
After this step, current_ count will become previous_count for next step step.
Previous_ count = current_ count———————————————B
Combining statements A and B:
current_ count = current_ count + 1 ——————————————C
Statement C, is a better way to replace A and B as there is no need to
consider previous_count. Statement C is a simple computing mechanism.
Algorithm development
Addition is a fundamental function that a computer does. When we are
given a set of N numbers and we perform addition manually, it is in a different
way. Computer does this addition with the help of arithmetic unit which is the
part of CPU. Let us first understand, how a computer adds two numbers by using
its arithmetic unit.
We can instruct arithmetic unit to add a set of n numbers by writing an
expression. Suppose we want to add 3 numbers say 250, 139 and 612. We can
write a simple expression as following:
S: = 250 +139 +612..............................A
Here the assignment operators evaluate the right hand side of statement A
and store the result in value in variable S. This statement will calculate
summation of 3 values. To add another three values we have to again write the
expression.
The better way to write statement A is as following where we replace values
by variables:
S: = X+Y+Z.........................................B
Statement B is a better way of representing summation:
• Statement B is more general.
• It is more useful than statement A.
The deficiency of statement b is that it can only add 3 numbers.
The general goal in designing algorithm is that, solution should be so simple
and general that it can be it can successfully handle a variety of input conditions.
The approach to formulate an algorithm to add n numbers in a computer is
completely different from conventional way of adding the n numbers.
Conventional way to add n numbers is following:
S: = (X1 + X2 + X3 + X4 + ................. + Xn)......................................C
OR
S:= ∑Xi ......................................D ( where i varies from 1 to n)
We can also write a statement like C. For writing statements, we need n
variables. We can find a better solution as computers are naturally designed to
do many things like:
Design of Algorithms 39
Algorithm And • Computers are well suited to do repetitive things.
Program Design
• the arithmetic unit of computer is designed in such a way that it can
add only two numbers at a time
NOTES
Therefore we have to formulate an algorithm for addition of N numbers that
can make use of above facts about computer. One way of doing this is that we
can add two numbers at a time as following:
S:= X1+X2......................(1)
Then we can add X3 to the Sum S calculated in statement (1) as following:
S:= S + X3.........................(2) (.......Similar to counting statement
current_count = current_count +1)
Similarly:
S:= S + X4
S:= S + X5
S:= S + X6
.
.
.
S:= S + Xn
You can notice that from Step 2 onward we are actually repeating the same
process over and over again. so we can write this whole process in general in ith
step as following:
S:= S + Xi+1.............................(3)
This statement is a general step that can be used in a loop to iteratively add
n numbers.
To use this statement it iteratively, we have to start with i=1 and we have to
provide initial value of S as so we can summarize the summation process as
following:
•· Initialize sum as S = 0
• repeat for all numbers(n times)
o read number
o sum = sum + number
• Write total sum of all numbers.
40 Design of Algorithms
3.2.4 To find maximum, minimum of a finite list of numbers Algorithm And
Program Design
Again finding maximum or minimum from a given list is a basic algorithm
where it can be used for problems like finding the eldest or youngest person in a
group of people or what was the maximum purchase from a list of customers. NOTES
Let us understand this problem with the help of an example.
Problem statement
Find the minimum from a given list of three numbers.
Algorithm development
CPU you makes use of logical control unit to solve this problem as here we
need to compare numbers with from each other.
Assume three numbers to be compared are a , b and c.
First compare a with b and a with c.
• If a is less than both b and c then the minimum number is a.
• If b is less than a and c then b is the minimum number.
• Similarly, if c is less than a and b then c is the minimum number.
Given the problem requirements there are two implications that will
determine the best solution of the problem:
1. You will have to check every number to get the solution
2. The best solution implies check every number just once
42 Design of Algorithms
Both the above problems are very specific to find minimum of given three Algorithm And
numbers. We should write an algorithm which can find out minimum from a Program Design
given list of N numbers.
In the next solution we have to check every number to get the solution. The NOTES
best solution should check every number just once. Following is the algorithm
that will find maximum as well as minimum from a given list of N numbers:
• Initialize variable as max to 0, max = 0.
• Initialize variable as min to 0, min = 0.
• Read a number say num from the list.
• If num is greater than max then assign max to num.
• If the number is less than minimum then assign num to min.
1: Maximum = 0
2: Minimum = 0
3: read(number)
4: if number > Maximum then Maximum = number
5: if number < Minimum then Minimum = number
6: Repeat from 3 as many times as needed
7: Print Maximum and Minimum
*****
Design of Algorithms 43
Algorithm And
Program Design
CHAPTER - 4
PROBLEM ANALYSIS AND DESIGN 1
NOTES
Problem
Design and algorithm to find all the prime numbers in first N positive
integers.
Problem Analysis
44 and Design 1
Algorithm development Algorithm And
Program Design
The efficient generation of prime numbers is an open Problem. There are
many ways to find out prime numbers in first N positive integers. Let us first
understand what the prime number is. NOTES
What is a Prime Number?
A prime number is a number that is only divisible by 1 or itself. For
example, 11 is only divisible by 1 or itself. Other Prime numbers 2, 3, 5, 7, 11,
13, 17....
Note: 0 and 1 are not prime numbers. 2 is the only even prime number.
Let us generate primes up to N using the sieve of Eratosthenes algorithm.
The sieve of Eratosthenes algorithm generates all the primes up to a given
limit. This is a common and fast algorithm used to generate a list of primes up to
a given limit. It works by making a list from 1 to N, and then iterating through
the list and progressively removing non-prime, composite numbers until only
primes are left in a list.
Example
For example, if we wanted to generate all the primes up to the number 30,
we first create a list of numbers from 1 to 30 and follow the numbered steps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
29 30
(Step 1) The algorithm starts at the first number, 1, and removes it because
it is not a prime number.
(Step 2) The next number is 2, which is a prime so it stays, but now all
multiples of 2 are removed from the list: 4, 6, 8, 10, etc.
2 3 5 7 9 11 13 15 17 19 21 23 25 27 29
(Step 3) The next number is 3, which is a prime so it stays, but now all
multiples of 3 are removed from the list: 6, 9, etc.
2 3 5 7 11 13 17 19 23 25 29
(Step 4) The next number is 5, which is a prime so it stays, but now all
multiples of 5 are removed from the list: 10, 15, etc.
2 3 5 7 11 13 17 19 23 29
Problem Analysis
and Design 1 45
Algorithm And (Step 5) All the numbers now, 7, 11, 13, etc., are all primes and there are
Program Design no more multiples of numbers we can remove from the list, so we are done and
the list that is left is our list of primes.
NOTES
Let us discuss another method for generating prime numbers
• We can check for prime numbers in the list one by one for all numbers.
• We need to divide an input number, say 17 from values 2 to 17 and check
the remainder. If the remainder is 0, number is not prime.
• No number is divisible by more than half of itself. So, we can modify
need to loop through just numberToCheck/2. If the input is 17, half is
8.5, and the loop will iterate through values 2 to 8
• If numberToCheck is entirely divisible by another number, we return
false, and loop is broken.
• If numberToCheck is prime, print the results
Polynomial Evaluation
Let us start with how to solve a polynomial. Following are the eight steps
to solve this problem:
Giving problem
Find the factorial of a number n, n>=0
Algorithm development
let us first understand what is the meaning of finding the factorial of a
number n.
we know that n! = 1*2*3*4*.....*(n-1)*n for n>=1
And by definition 0! = 1
While solving this problem computer will use its arithmetic unit. as we
know that computers arithmetic unit can only add two numbers. Similarly,
arithmetic and it can only multiply two numbers at a time.
Look at the pattern of factorial calculation as below:
0! =1
1! = 1*1
2! = 1*2
3! = 1*2*3
4! = 1*2*3*4
.
.
We see that 4! contains all the factors of 3!. only difference is the inclusion
of number 4. from this we can analyse that n! can always be obtained from (n-
1)! by multiplying it by n.
Like n! = n * (n-1)! for n>=1
We can write algorithm
Step 1: read n for which we need to calculate factorial
Step 2: set product p for 0!. Also set product count to 0.
Step 3: while less than and products have been calculated repeatedly do
the following:
a) Increment product count,
b) Compute the highest Product p by multiplying i buy the most
recent product.
Problem Analysis
Step 4: return the result of n!.
and Design 1 47
Algorithm And Pseudo code for factorial function
Program Design
int factorial(){
NOTES int num = 10;
int i;
int result = 1;
for(i =1; i<=num; i++){
result = result * i;
}
Algorithm Development
Given problem can be divided into two sub-problems:
• Compute factorial and
• Sum of n numbers that have been calculated as result of first part.
It would be helpful for you if you yourself integrate them into one, as that
would need proper understanding of both the concepts.
In the earlier section, we calculated the factorial of a given number. We can
modify the above algorithm to find sum of first n factorials as following:
Compute factorial
int factorial( int n){ int num = n;
int i;
int fact = 1;
for(i =1; i<=num; i++){
fact = fact * i;
Problem Analysis
48 and Design 1 }
Algorithm And
printf(“factorial = %d”, fact);
Program Design
return fact;
} NOTES
Problem Analysis
and Design 1 49
Algorithm And Algorithm development
Program Design
Fibonacci series is defined as a sequence of numbers in which the first two
numbers are 1 and 1, or 0 and 1, depending on the selected beginning point of
NOTES the sequence, and each subsequent number is the sum of the previous two. So,
in this series, the nth term is the sum of (n-1)th term and (n-2)th term.
How to Generate Fibonacci Series?
Mathematically, the nth term of the Fibonacci series can be represented as:
Xn = Xn-1 + Xn-2
The Fibonacci numbers up to certain term can be represented as:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144….. or 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
55, 89, 144….
the sum of every subsequent term is the sum of previous two terms as
follows:
First Term = 0
Second term = 1
Third Term = First + Second = 0+1 =1
Fourth term = Second + Third =1+1 = 2
Fifth Term = Third + Fourth = 2+1 = 3
Sixth Term= Fourth + Fifth = 3+2 = 5
Seventh Term = Fifth + Sixth = 3+5 = 8
Eighth Term = Sixth + Seventh = 5+8 = 13 … and so on to infinity!
Step 1: Start
Step 2: Initialize the variables, a=0, b=1 and Fibb =0
Step 3: Enter the number of terms of Fibonacci series to be printed say n
Step 4: Print First two terms of series
Step 5: Use loop for the following steps (initially i= 0)
Fibb = a + b
a=b
b= Fibb
increase value of i each time by 1(till i = n)
Step 6: print the value of Fibb
Step 7: End
*****
Problem Analysis
and Design 1 51
Algorithm And
Program Design
NOTES
CHAPTER - 5
PROBLEM ANALYSIS AND DESIGN 2
First, we will write an algorithm to find largest from a finite list and then
we can modify it to find second largest from a finite list.
Describe an algorithm for finding the maximum (largest) value in a finite
sequence of integers.
SOLUTION
1. Set the temporary maximum equal to the first integer in the sequence.
2. Compare the next integer in the sequence to the temporary maximum,
and if it is larger than the temporary maximum, set the temporary
Problem Analysis maximum equal to this integer.
52 and Design 2
3. Repeat the previous step if there are more integers in the sequence. Algorithm And
Program Design
4. Stop when there are no integers left in the sequence. The temporary
maximum at this point is the largest integer in the sequence.
NOTES
Pseudo code: Finding the Maximum Element in a finite sequence.
Let us write an algorithm to find largest and second largest from the list of
numbers:
Initialize two variables first and second to minimum integer value say
INT_MIN,
As this problem involves a real valued function A^(1/N) we can solve this
using Newton’s method, which starts with an initial guess and iteratively shift
towards the result. We can derive a relation between two consecutive values of
iteration using Newton’s method as follows,
Using above relation, we can solve the given problem. In below code we
iterate over values of x, until difference between two consecutive values of x
become lower than desired accuracy.
GCD of two numbers is the largest number that divides both of them. A
simple way to find GCD is to factorize both numbers and multiply common
factors.
For Example:
36 = 2* 2* 3*3
60 = 2*2*3*5
Problem Analysis
and Design 2 55
Algorithm And
Program Design
5.5 BASE CONVERSION
NOTES
Examples
Problem Analysis
56 and Design 2
Decimal to Binary Algorithm And
Program Design
Here is an example of using repeated division to convert 1792 decimal to
binary:
NOTES
Decimal to Octal
Here is an example of using repeated division to convert 1792 decimal to
octal:
Decimal to Hexadecimal
Here is an example of using repeated division to convert 1792 decimal to
hexadecimal:
Problem Analysis
and Design 2 57
Algorithm And The only addition to the algorithm when converting from decimal to
Program Design hexadecimal is that a table must be used to obtain the hexadecimal digit if the
remainder is greater than decimal 9.
NOTES
The addition of letters can make for funny hexadecimal values. For
example, 48879 decimal converted to hex is:
*****
Problem Analysis
58 and Design 2
Algorithm And
Program Design
CHAPTER - 6
CONCEPT OF ARRAY, SORT AND
NOTES
SEARCH TECHNIQUE
For example
168, Lakshmi_Road ( Street)
Lakshmi_Road [ 168] (array)
The house at each address corresponds to the memory storage unit of the
computer word (or byte) at each address in the array. People and furniture at
Sector are stored in houses; on the other side we store numbers or characters in
different array locations. We can retrieve a copy of a number or a character stored Concept of
in an array by referring the particular array location. Array, Sort and
Search Technique 59
Algorithm And We can refer a particular array location by using array name and suffix.
Program Design Arrays are very important in implementing computer algorithms. They simplify
the implementation of algorithms that must perform the same computations on
NOTES Collection of data. Use of Array leads to implementations that are more efficient
then we would have otherwise. The contents of Array locations can be changed
in the same way as we change the single variables.
Letus now consider more formal definition of array and how we can access
the different elements in an array.
“Array is a collection of variables of same type that are referenced by a
common name.” Specific element in an array is accessed by an index.
“An array is a finite, ordered set of homogeneous elements.”
By homogeneous- we mean that all the elements of the set are of same type.
By ordered set- we mean that each element of set has unique position and
can be accessed by referring to its position.
Therefore basic properties of Array are following
1. Homogeneity of its elements.
2. Ordering imposed on all the elements.
3. Finite number of elements.
How to access elements in an array?
An individual element of Array can be accessed by giving-> [ array name
+ index ]
Index is also known as subscript.
In any programming language arrays are stored in continuous memory
locations.
2. Multidimensional array
An array in which each element can be referenced by more than one
subscript is known as multidimensional array. Generally two
dimensional and three dimensional arrays are used.
Let us now discuss linear or one dimensional array in more detail.
Concept of
Array, Sort and
60 Search Technique
The above array can be described as following: Algorithm And
Program Design
Array name = X
Size of array =6
NOTES
Lower bound: smallest number that an index can have. [0]
Upper bound: largest number that an index can have.
Size of array = upper bound- lower bound +1
Array elements are stored in continuous memory locations. If we know
address of first element of Array say X[0], then we can find address of all other
elements.
Base address: address of the first element in the array.
We can apply various operations on the one dimensional arrays like:
• traversing
• searching
• sorting
Traversing
Traversing means assessing and processing each element of Array exactly
once.
For example
• To read all the elements in an array.
• To write all the elements of an array.
• Make some change in each element of an array.
Let us understand traversing problem with the help of an example:
Consider the problem of finding sum of n numbers accepted by user. in
earlier chapters we had written the algorithm for same problem without using
array. Let us write a new algorithm using array:
Step 1: Start
Step 2: read all the elements of Array X, for i=1 to i <= N as X[i] //X is
the name of array, I is index for array X.
Step 3: initialize variable SUM = 0;
Step 4: repeat for i= 1 to i <= N
SUM = SUM + X[i]
Step 5: write the sum of numbers as SUM
Step 6: End
Concept of
Array, Sort and
Search Technique 61
Algorithm And We can find out that this algorithm is simple than the previous algorithm
Program Design we had written without using array.
You can try to solve following problems with the help of array
NOTES
• From a given list of numbers, count the number of positive elements
and count the number of negative elements in the list.
• Find the greatest and the minimum from a list.
Problem
Preparing the grade of 50 students in a examination.
Solution
So to solve this problem we need to declare 50 different variables. But, if
in next session, 10 more students sit in the examination,
Then this will require a number of changes in the program and program
become so complex.
Two sources type of problems I need to define and declare an array.
Processing speed become fast with the declaration and use of array. because
of the simplicity they provide, arrays are used in various searching and sorting
algorithms.
Algorithm Description
Step 1: Establish an array a[1..N] of n elements.
Step 2: set loop index i to 2 to allow correct termination.
Step 3: compare successive pairs of elements until duplicate is encountered,
then set unique element count j.
Step 4: while always have not been examined do
A) if next pair not duplicate then
a.1) add 1 to unique element count j,
a.2) move later elements of the pair two array position determined
by unique element count j.
Concept of
Array, Sort and
Search Technique 63
Algorithm And
Program Design
6.5 THE PROBLEM OF SEARCH AND MERGE
NOTES
Searching: Linear, Binary search algorithms
Linear search
It is a search algorithm, it is also known as sequential search, it is suitable
for searching a set of data for a particular value.
• every element in the list is checked from starting until a match is found.
• it compares each element with the value being searched for stops when
that value is found or the end of array is reached.
Algorithm development
Let A is the array of n elements.
Therefore we have a list A[1], A[2], A[3], A[4],.........,A[n].
Suppose X is the element to be searched.
This algorithm will find the location of X in the array if it is in list otherwise
Concept of it will give a message-” element is not in the list.”
Array, Sort and
64 Search Technique
Algorithm And
Program Design
Step 1: start
Step 2: repeat for i= 1 to i <= n
NOTES
if (A[i] == X) then
Display “ element X found at i position.”
Exit.
Step 3: display “element not found in the list.”
Step 4: stop.
Binary search
Binary search Method can be used only for sorted list.
In this method, the value of the element in the middle of the list is compared
with the value of the element to be searched for. if the middle element is large,
the desired element may be in the behalf of the list. If the middle element is
smaller, the desired element may be in the lower half of the list.
Therefore every time domain of such is reduced by half.
Therefore logic behind the technique is given below as:
1. Find the first middle element of the array.
2. Compare the mid element with an item to be searched.
3. there are three cases
1. if it is desired element then search is successful.
2. if it is less than item then search only first half of the array.
3. if it is greater than desired element then search in the second half
of the array.
4. Repeat the above step until the element is found or exhaust in search
area.
Concept of
Array, Sort and
Search Technique 65
Algorithm And Step1 START
Program Design
[INITIALIZE THE VARIABLES]
Step2 BEG =1
NOTES
END= N&LOC=0
MID =int((BEG+END)/2)
Step3 Repeat the following step 4 while BEG<=END and
A[MID]!=x
Step4 if(x<A[MID]) then\
END =MID-1;
else
BEG =MID+1;
MID =int((BEG+END)/2)
Step5 if(x== A[MID])then
LOC=MID
Display “X found at LOC=MID”
Step6 if(LOC==0)
Display “X not found at list”
Sorting Algorithm
Sorting Algorithm are used to arrange random data into some order.
-data can be arranged in ascending order.
Different sorting algorithm are
* Bubble Sort.
* Insertion Sort.
* Selection Sort.
Concept of
Array, Sort and
66 Search Technique
BUBBLE SORT Algorithm And
Program Design
In this method adjacent elements of the list to be sorted are compared .If
the elements on the top is greater than the item immediately below it, they are
exchanged. NOTES
This process is carried out till the list is sorted.
After pass 1 =1st largest element is at the bottom.
After pass 2 =2nd largest element is at the second last position.
‘
‘
‘
And so on
Following is an example
Original Pass1 Pass2 Pass3 Sorted
List List
4 4 4 4 2
8 8 6 2 4
10 6 2 6 6
6 2 8 8 8
2 10 10 10 10
Step1 START
Step2 Repeat step 3and 4 for for I=1 to I=N-1
Step3 Repeat step 4 for J=1 to N-1
Step4 [exchange of elements]
if(A[J]>A[J+1]) then
{
TEMP =A[J]
A[J]=A[J+1]
A[J+1]=TEMP
}
Step5 Stop. Concept of
Array, Sort and
Search Technique 67
Algorithm And Selection sort
Program Design
Selection sort is a simple sorting technique that improves the performance
of the bubble sort.
NOTES
Logic of the selection sort works as follows
INSERTION SORT
In insertion sort we insert an element into its proper place in the previously
sorted sub list . Consider an array A with N elements.
Step can be started as
1) A[1] by itself is sorted
2) A[2] is inserted before or after AEN A[I] so that A[1] and A[2] are
sorted
3) Similarly A[3] is inserted so that A[1], A[2] and A[3] are sorted.
4) This process is continued till all the elements are sorted.
Original list: 10 8 4 6 2
Pass1 10
Pass2 8 10
Pass3 4 8 10
Pass4 4 6 8 10
Concept of
Array, Sort and Pass5 2 4 6 8 10
68 Search Technique
Algorithm- Insertion sort Algorithm And
Program Design
Let A is linear array with N elements
1) START NOTES
2) REPEAT STEP 2 TO 5 FOR I=2 TO I=N
3) Set TEMP=A[I]
POSITION= I-1
4) [Move down 1 position all elements greater than temp]
Repeat while [Temp< A[POSITION] & POSITION>=1]
{
A[POSITION+1]= A[POSITION]
POSITION=POSITION-1
5) [insert TEMP at proper position]
A[POSITION+1]=TEMP
6) STOP
*****
Concept of
Array, Sort and
Search Technique 69
Algorithm And References
Program Design
Text Book
1. Dromey R. G. : How to Solve it by a Computer.
NOTES
2. Sartaj Sahni: Data Structure, Algorithms and Applications in C++
(Ch II).
Web References
• https://coderbyte.com/algorithm/generate-n-primes-sieve-of-
eratosthenes-algorithm
• https://www.geeksforgeeks.org/tag/accenture/
• https://coderbyte.com/algorithm/generate-n-primes-sieve-of-
eratosthenes-algorithm
• http://docplayer.net/16267580-Flowchart-techniques.html
• http://faculty.ccri.edu/kelly/COMI1150/PseudocodeBasics.pdf
• https://www.eecs.yorku.ca/course_archive/2008-
09/S/1019/Website_files/14-the-growth-of-functions.pdf
Review questions
Chapter 1: Introduction: Algorithm and Program Design
1. Define algorithms. What are the properties of an algorithm that must
be considered to solve a problem using computer program?
2. What is the difference between a procedure and a program?
3. What are different ways to represent an algorithm?
4. What are flowcharts? Define different scenarios where flowcharts can
be used.
5. What are the basic symbols that are used to create flowchart? Draw
the symbols and also explain their functionality.
6. What are different flowcharting rules and guidelines?
7. Draw the flowchart for three simple logic controls:
a. Sequential logic
b. Selection logic
c. Iteration or looping logic
8. What are pseudo codes? write pseudocode for three simple logic
control structures:
a. Sequence logic
b. Selection logic
c. Iteration or looping logic
9. What are the rules for writing a pseudocode?
70 Chapter Heading
10. Write different advantages and limitations of pseudo code. Algorithm And
Program Design
11. Draw the flowchart, write pseudocode and algorithm for the following
problems:
a. swap two numbers a and b NOTES
Chapter 3:
1. Write an algorithm to swap two numbers.
2. Suppose you are given marks for list of N students. Count the number
of students who have scored more than 60%.
3. Suppose you are working in a mall, there was a sale by 3000 people
in a day. Count the number of people who chopped for more than 5000
rupee.
4. Suppose there is a group of people who are working in a company.
Count the number of people whose age is greater than 55 years.
Chapter Heading 71
Algorithm And 5. Student has appeared in an exam of 6th subjects. Find the total marks
Program Design obtained in all subjects and also calculate the percentage.
6. Submitted RS 5000 in a bank. Interest rate given by the bank is 8%.
NOTES Calculate the interest he will get after 5 years. Also calculate the
compound interest he will get after 5 years.
7. Result of 50 students is out. Find the student who got the maximum
marks.
8. For the above problem, also finds the student who got the second
highest marks.
9. Write an algorithm to find the greatest of three numbers.