Download as pdf or txt
Download as pdf or txt
You are on page 1of 70

Centre for School of Distance Education

Bharati Vidyapeeth
102 : ALGORITHM AND

(Deemed to be University), Pune, India


PROGRAM DESIGN
BCA

Writers Team

Author Unit No.

Dr. Baljeet Kaur 1 to 6


Assistant Profesor,
BV(DU) Institute of Management and
Entrepreneurship Development, Pune - 411 038.

REVIEW
COURSE SUBJECT FACULTY

BCA ALGORITHM AND Dr. Suvarna Patil


PROGRAM DESIGN
CONTENTS
Unit Contents Page No.

Introduction: Algorithm and Program Design


1.1 Introduction: Concept of Problem
1.2 Procedure and Algorithm
1.2.1 Understanding algorithms
1.3 Algorithm Representation through Pseudo - Code and Flow – Charts
1.3.1 Flowcharts
1.3.1.1 When to use flow charts?
1 11-24
1.3.1.2 How to create a flowchart?
1.3.1.3 Flowcharting rules:
1.3.2 Pseudocode:
1.3.2.1 Rules for writing a pseudo code:
1.3.2.2 Advantages of pseudo code:
1.3.2.3 Limitations of pseudo code:
1.4 Tracing of Algorithms

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.2 Structured programming languages 25-33
2.3 Basic control structures
2.3.1 Sequential control structures
2.3.2 Selection/conditional control structures
2.3.3 Iteration control structures

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.

Problem Analysis and Design 1


4.1 Problem Analysis and Design 1: Introduction
4.2 Design of algorithm for problem such as generating prime numbers
4 44-51
4.3 Evaluation of polynomial
4.4 Sum of first n factorials
4.5 Finding nth term of Fibonacci sequence.

Problem Analysis and Design 2


5.1 Problem Analysis and Design2: Introduction
5.2 Design of algorithm for problem such as finding largest and second
5 largest of list 52-58
5.3 Determining nth root of a number
5.4 Compute GCD
5.5 Base Conversion

Concept of Array, Sort and Search Technique


6.1 Concept of Array, Sort and Search Technique: Introduction of Array
6.2 Array manipulation such as removing the duplicates, Partitioning of
an array
6 6.3 listing of prime numbers 59-70
6.4 finding prime factor of a number
6.5 The problem of search and Merge
6.6 Linear, Binary search algorithms
6.7 The Problem of Sorting, Selection, Insertion and Bubble sort
Algorithm And
Program Design

CHAPTER – 1
INTRODUCTION: ALGORITHM AND
NOTES

PROGRAM DESIGN

1.1 Introduction: Concept of Problem


1.2 Procedure and Algorithm
1.2.1 Understanding algorithms
1.3 Algorithm Representation through Pseudo - Code and Flow – Charts
1.3.1 Flowcharts
1.3.1.1 When to use flow charts?
1.3.1.2 How to create a flowchart?
1.3.1.3 Flowcharting rules:
1.3.2 Pseudocode:
1.3.2.1 Rules for writing a pseudo code:
1.3.2.2 Advantages of pseudo code:
1.3.2.3 Limitations of pseudo code:
1.4 Tracing of Algorithms

1.1 INTRODUCTION: CONCEPT OF PROBLEM

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.

1.2 PROCEDURE AND ALGORITHM

A computer programmer cannot write instructions for a program unless he


does not know how to solve the problem manually. If he knows the steps to solve
a problem; it is important to put all the steps in proper sequence. While, writing
the steps, if any step is left or he writes the instruction in wrong sequence, the
programmer will get a wrong answer. So to get an effective program, all the
instructions should be written in correct sequence. Hence, to ensure that all the
instructions for the given problem are written in appropriate sequence, we must
plan the program before writing it. Planning a program involves defining correct
sequence of instructions to solve a problem.
Procedure is a recipe for completing a task. A procedure contains finite
sequence of steps to solve a problem. All the steps in processes are ordered in a
sequence. But a procedure can execute some sequence of steps in finitely,
depending upon the nature of problem or task. On the other side, an algorithm is
a procedure to solve a problem or completing a task. An algorithm always stops
Introduction: within a finite time. It means, if a problem has a solution then definitely it will
Algorithm and have an algorithm to achieve the solution in a finite number of steps. We can also
12 Program Design
say that if a problem does not have an algorithm, the problem doesn’t have a Algorithm And
feasible solution. Sometimes algorithms are also called effective procedures. Program Design

1.2.1 Understanding algorithms NOTES


The simplest way to look upon algorithm is to take it as a recipe in cooking.
For example: recipe of cooking rice, which is a sequence of instructions,
where each instruction is very simple that a cook can follow to produce this dish.
Similarly, algorithm is sequence of instructions, each instruction can be taken by
computer to perform some part of task and at the end computer will solve the
problem. More precisely we can define algorithm as “ an effective method
expressed as finite list of well defined instructions for calculating a function.” or
“ an algorithm is a step by step procedure to solve a problem.”
An algorithm is an effective procedure in which a list of well defined
instructions is executed to complete a task. When a given problem is there in an
initial state, it is processed by well defined set of instructions (i.e. Algorithm)
and then it terminates to complete and give the output (Figure 1).

Figure : Algorithm takes Input and generates Output


Following are the properties of an algorithm that must be considered to
solve a problem using computer programs:
• Finiteness: an algorithm should have finite number of statements and the
solution should be achieved in a finite number of steps.
• There should not be any ambiguity to understand the statements.
• All, the steps of instructions should be properly sequenced.
• It should be clear in algorithm- what the input for a given input is and
what is the output.
• An algorithm must give an effective solution to the problem

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

Example2: (Pass/NoPass Grade) : if the student marks are less than 60 –


He is pass else he is not passed.
1. START
2. Input: One number as MARKS
3. If ( MARKS is greater than or equal to 70)
then
Set the grade to “pass”
else
Set the grade to “nopass”
End if
4. Return the grade End Average of Two numbers
5. END

1.3 ALGORITHM REPRESENTATION THROUGH PSEUDO


CODE AND FLOW-CHARTS

Algorithms can be represented by three ways


1. as Natural Language
2. as program
3. as flowchart
4. as pseudo code
An algorithm written in a programming language is known as a program.
Therefore, any program is an algorithm. Generally, programmers use flowchart
and pseudo code for designing algorithms for a problem. Use of flowchart and
pseudo code helps in developing effective and correct algorithm for a problem
before writing the program in a programming language. Programmers can select
any of the Representation based upon their choice.

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.3.1.1 When to use flow charts?


Flow charts are also known as process maps finding the solution of a
problem and they can be used in following scenarios:
1. They are used to identify flow of Information and materials during a
process to find the solution.
2. It determines, how many number of steps are involved in solving a
problem?
3. It also specified how many branches are there in a specific process.
4. It also identifies if there are infinite loop or there is a process which is
not going anywhere. Hence it identifies badly organized flows.

1.3.1.2 How to create a flowchart?


Flow charts can be created with the help of following four basic symbols:
1. Start/End
2. Process/task
3. Decision
4. Flow control
5. Input/Output

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:

Decision symbol also indicates the number of possible outgoing paths.


Each exit path is labeled with the condition upon which the program
logic takes that path for further execution.

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

Figure : Sample Flowchart


The above diagram ( figure 2) shows the flowchart of the algorithm for the Introduction:
given problem. The first symbol, which is labeled as “Start”, is a terminal symbol Algorithm and
Program Design 17
Algorithm And indicating the beginning of the flowchart. The second symbol, represented by a
Program Design rhombus is used for input and output.
This step read the input for the user as name, roll number, and marks
NOTES obtained by the students in 10 subjects. The third symbol is a processing symbol
the symbol indicates that at this step the computer at the marks of all the 10
subjects and stores the sum in a memory location named total. The fourth symbol
is again a processing symbol. This symbol indicates that at this stage program
calculates the percentage by dividing total by 10 and store the result in memory
location named percentage.
The fifth symbol is an input output symbol which writes the output data as
name of the student, roll number and percentage of marks obtained by the student.
It is important to note that all the input and output instructions are not the part of
logical steps. Search details are part of system design document and they are
included in a computer program as input and output instructions The Last symbol
“Stop” is a terminal symbol indicating the end of flowchart logic. The directed
flow of lines which connects various symbol in the flowchart indicate the
sequence of instruction execution.

1.3.1.3 Flowcharting rules


American national standards Institute (ANSI) has Indian a set of rules and
guidelines to standardize flowcharting process. The basic flowcharting rules and
guidelines are as follows:
1. First, chart the main line of the logic, and then incorporate details.
2. Maintain a consistent level of details for a given flowchart.
3. Do not chat every detail in a flowchart, otherwise the flowchart will
only be a graphical representation of all the statements of the
corresponding program.
4. Use common and statements that are easy to understand. Use
descriptive titles written in your own language rather than machine
oriented language.
5. Be consistent in using names and variables in a flowchart.
6. Keep a flowchart as simple as possible and avoid crossing the flow of
lines.
7. If you need a new page while drawing a flowchart, break the flowchart
at an input or output. Use properly label connectors to link portions of
the flowchart on different pages.

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.

Figure 4: Flowchart for IF…THEN condition

Figure 5: Flowchart for IF…THEN…..ELSE condition

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

(DO….WHILE) (REPEAT –UNTIL)

1.3.2.1 Rules for writing a pseudo code


Following are the rules for writing a pseudo code:
1. Write only one statement per line
Any statement in your pseudo code should express just one action for
the computer. If the task list is properly drawn, then in most cases each
task will correspond to 1 line of pseudo code.

2. Capitalize initial keyword


In the example the key words like READ and WRITE are in Caps. Just
a few keyboards we will use writing pseudo codes like READ,
WRITE, IF ELSE, AND, WHILE, ENDWHILE, REPEAT, UNTIL

3. Indent to show hierarchy


We will use a particular indentation pattern in each of the design
structures:
Sequence: keep statements that are “stacked” in sequence all starting
in the same column.
Selection: indent the statements that fall inside the selection structure,
but not the keywords that form the selection.
Looping: indent the statements that Paul inside the loop, but not the
keywords that form the loop.

4. End multi-line structures


All the initial keyword must always in line with the last or end of the
structure.
Introduction:
Algorithm and
Program Design 21
Algorithm And 5. Keep statement language independent
Program Design
Resist the urge to write in whatever language you’re most comfortable
with. There may be special features available in the language you plan
NOTES to eventually write the program in. If you are sure it will be written in
that language, then you can use the features. If not, then avoid using
the special features.
Let us write a pseudo code for a given task. Let us assume following is the
task for which we have to write the pseudo code:

TASK LIST
Read name, hourly rate, hours worked, deduction rate
Compute gross, deduction, net pay
Is gross<= 100?
Yes: calculate deduction
No: No deduction

Write name, Bros, deduction, net pay

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

1.3.2.2 Advantages of pseudo code


Following are some of the advantages of using pseudocode
• Converting a pseudocode to a programming language is much easier than
converting a flowchart.
• As compared to flowchart, it is easier to modify a pseudocode of program
Introduction: logic when program modifications are necessary.
Algorithm and
22 Program Design
• Writing of pseudocode involves much less time and effort and drawing Algorithm And
an equal and flowchart. Program Design

1.3.2.3 Limitations of pseudo code NOTES


It also suffers from some of the limitations, following are the limitations:
• In the cases of pseudo code, a graphic representation of program logic is
not available.
• There are no standard rules to follow for using a pseudo code to stop
different programs use their own style of writing pseudo code and hence
communication problem occurs due to lack of standardization.
• As compared to flowchart beginners open find it more difficult to write
pseudo code of program logic or to follow program logic from pseudo
code.

1.4 TRACING OF ALGORITHMS

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

procedure swap()READ a,b


WRITE a,b // will print values of a and b
set temp to 0
temp ← a
a←b // a holds value of b
b ← temp // b holds value of a stored in temp
WRITE a,b // will print swapped values of a and b
end procedure

2. Task : Find Sum of two numbers


procedure sum()
READ a,b
set sum to 0
sum ← a+b // sum holds the value after adding a and b
WRITE “Sum of and b is “ sum
Introduction:
end procedure Algorithm and
Program Design 23
Algorithm And 3. Task: Find Maximum number in a given list of numbers
Program Design
Suppose A is an array
NOTES procedure maximum()
READ list of N numbers
DO WHILE
set sum to 0
sum ← a+b // sum holds the value after adding a and b
WRITE “ Sum of and b is “ sum
end procedure

*****

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 Oriented Programming


Programming language consists of instructions that are designed for the
understanding by a computer. On the other side computer processors only
understand machine code that is in the form of binary data that is one and zeros.
It is difficult for user to understand machine code and design the instructions in
the form of machine code. It is easy for developers to understand the problem
and write instructions in high level languages written in English. Programming
platforms that use high level language es for coding are more understandable
than machine code and also provide greater portability.
As human beings, we can feel and think. To communicate with other
persons, we need language for communication. On the other side computers
cannot speak. Programming languages which we can speak to the computers and
get our work done. Programming languages generally used English language.
Unlike human beings, computers cannot get our intention. So we have to be very
specific and we need to describe in detail what is a intent and provide every little
detail. Nowadays, there are many programming languages like perl, python, Java,
Microsoft Dot Net. Programming languages are mainly used to express
algorithms. Generally, instructions in many languages need to be stated in Concept of Structured
Programming
imperative form and in other languages utilize declarative form.
and Procedure
Oriented Programming 25
Algorithm And
Program Design
2.2 TYPES OF PROGRAMMING LANGUAGES
NOTES
Procedure oriented programming and structured programming are two main
types of programming languages. Let us discuss these different programming
languages platform:

2.2.1. Procedural programming language


In this environment statements are executed in a sequence which leads to a
result. It consists of a set of different procedures and it’s set of code for each
procedure. This programming language execute the set of instructions in order
will stop these languages are based on concept Defined by the procedure calls
also it means the statements are organized into procedures which are also known
as subroutines or functions. The advantage of using procedures is that they are
compact and it is very easy to define the scope of the procedure. As the
instructions are executed in a step-by-step manner, it becomes easy to follow the
small programs. The examples of procedure procedural programming languages
are Pascal, FORTRAN, and COBOL.

2.2.2 Structured programming languages


Structured programming language emphasizes more on separating program
data from its functionality. It is based on top down approach methodology, where
main problem are broken down into small problems or modules. This concept
was formalized in year 1966 by Corrado Bohm and Giuseppe Jacopini. They
explained a theoretical computer program design with the help of loops,
sequences and decisions. Following are some of the characteristics of structure
programming language:
• Top down approach for problem solving: here main problem is divided
into some problems and hence simplifies the problem solving.
• Modularization of program structure: here we can break large instructions
into separate and smaller in set of instructions in modules, subroutine or
smaller subprograms.
• structured code for individual modules: different control structures can
be used to determine the exact flow of instructions to be executed like
conditional statements(if then else), loop statements (for, while loop)
Examples of structured programming languages are Pascal, C, Ada

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

2.3.1. Sequential control structures


In sequential execution all the statements are executed one by one in a
sequential order. This is default mode of execution of statements. Statements are
executed in the order in which they are written as shown in figure 1.

Figure 1: Sequential execution of statements


Example
let us understand sequence control structure with the help of an algorithm
and its flowchart and its Pseudocode. Consider the following problem of finding
average of three numbers.
Given problem: find average of three numbers.
Algorithm:

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

Pseudo code for the given problem

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

2.2.2 Selection/conditional control structures


It includes decision making and branching statements. in a given problem,
if you have to choose between two or more alternative paths, these control
statements can help you in making selection. Depending on the weather a
condition is true or false decision control structure can skip execution a block of
instructions and allow and another block of instructions to be executed.

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

Flowchart for the given problem:

Pseudo code for the given problem

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

2.3.2. Iterative control structures


These control structures are used to repetitively execute a block of code of
instructions at a time until a specified condition is true. following the three types
of loops:
• while
• do/while
• for 4

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

2.4 BENEFITS OF STRUCTURED PROGRAMMING AND


PROCEDURE ORIENTED PROGRAMMING

Following are some of the advantages of using structured programming


language or procedural programming language:
• As structured programming approach which divides a complex problem
into simple subprograms or modules, this approach reduces the
complexity of a program as it uses divide and conquer.
• As we will be using logical structures, it is easy to find out what is flow
of control of instructions.
• As main problem can be divided into different modules, multiple
programmers can work on different parts of the project independently at
the same time. This improves the productivity.
• What is once return can be reused many times? It reduces complexity
and increases reliability.

*****

Concept of Structured
Programming
and Procedure
Oriented Programming 33
Algorithm And
Program Design

CHAPTER – 3
DESIGN OF ALGORITHMS
NOTES

3.1 Design of Algorithm: Introduction


3.2 Developing Algorithm for Fundamental Problems:
3.2.1 Swapping
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

3.1 DESIGN OF ALGORITHM: INTRODUCTION

Nowadays, computers are used to perform a variety of tasks. This entire


task can be completed with the high speed. Set of instructions are used to perform
computation on steps. In the last chapter we have studied that computer use
different type of instructions to perform various activities. Some instructions are
used for storing information; some instructions are used for doing arithmetic,
and some instructions are used for comparing the information. These basics
instructions are used to make Complex instructions.
One of the most basic mechanisms is to interchange values associated with
two variables. This logic is the basic of many sorting algorithms. The basic
mechanism of Counting is also associated with many other computational
procedures. This basic algorithm is sometimes used for summing a set of data.
There are many problems that can be solved by repeating the basic
mechanism over and over again. For example, to add a set of N numbers,
successive numbers can be added to accumulated sum previous numbers. These
kinds of iterative processes/repetitive processes must change a variable or
information in the mechanism so that iterative process can be terminated.
Computer Solution for the problem is important to write the instructions in
a way so that an iterative solution is possible. There are many problems then we
can solve very easily like finding the maximum number from a given set. If we
try to find out iterative solution for these simple problems, we find it difficult.
This problem happens because we do not explicitly formulate or understand the
method to solve the problem we can directly come to a solution for these simple
problems. On the other side computers cannot think in that way. By using
34 Design of Algorithms iterative processes we can find simple solution for Complex problems.
It is important for a student to know computer information and how they Algorithm And
manipulate them permission? After understanding the basics we will be in a Program Design
position to tell more Complex problem that will be discussed in next chapter.
NOTES

3.2 DEVELOPING ALGORITHM FOR FUNDAMENTAL


PROBLEMS

3.2.1 Swapping: exchange the values of two variables


Given problem
Given two variables, x and y, exchange the value of x and y.
Algorithm development
This is one of the very basic problem which is used in many fundamental
mechanism like sorting of data and data manipulation. To understand this
problem, let us take one example.
Suppose variable X is assigned value 236 and variable Y is assigned a value
728 as shown below:
Starting values of X and Y:
X Y

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

To change the values of a variable we can use an assignment operator(:=)


and perhaps somebody can make following assignments to exchange the value
of X and Y:
X : = Y; _____________ (1)
Y : = X; _____________ (2)

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

3.2.2 Counting Problem


Counting is a problem, with the given list of data you have to count number
of items/values that satisfies a particular criteria/condition. Counting is a very
basic algorithm which is used in computer algorithms. Let us take a problem of
counting.

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.

We can summaries the pass counting in following steps

• scan the list of n marks


o read marks
o if it satisfies the pass criteria, add 1 to pass count.
• Initiate the count value, should be initialized to zero.
• Read the list of marks from n student.
• initialize count C = 0
• repeat for all students(n times)
o read marks
o if it is pass (>= 50) add 1 to the count.
• Write total number of pass students.

Example application where counting can be used


• In a mall, count the number of customers who have shop for more than
rupees 5000.
• Count the number of people who have not paid their electricity bill for
a particular month.

3.2.3 Finding the Sum, Product of a finite list of numbers

Finding Sum or Product of N numbers


In many problems we have to find the sum of a given list or find the product
of a given list. Suppose we have to find sum of the marks of the students in
different subjects or we have to calculate the total bill after purchasing various
38 Design of Algorithms
items. Summation mechanism is very basic algorithm which can be used to find Algorithm And
algorithm for above problems. Let us understand the problem with an example. Program Design

Given problem NOTES


Suppose we have to find sum of a list of N numbers and return their sum.

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.

Pseudo code for above problem

int min(int a, int b, int c){


if (a <= b && a <= c){
return a;
}
if (b <= a && b <= c){
return b;
}
if (c <= a && c <= b){
return c;
}
}

There’s the way with the minimum number of comparisons.


Following is the better way to write this algorithm
• Compare a with b, if a is less than b then compare a with c, if a is less
than c, we can print a is the minimum value.
• If a is greater than c, it means c is the minimum value. Design of Algorithms 41
Algorithm And • If none of the comparison result is true then we can compare b with c,
Program Design if b is less than c, then b is the minimum number otherwise c is the
minimum number.
NOTES
Pseudo code for above problem

int min(int a, int b, int c)


{
if (a < b){
if (a < c){
return a;
}
else{
return c;
}
}
else{
if (b < c){
return b
}
else{
return c;
}
}
}

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

It would be something like that


Similar algorithm can be written for finding the maximum of three numbers.
the only thing we need to do is to change less than symbol with the greater than
symbol.

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.

Pseudo code for above problem

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

4.1 Problem Analysis and Design 1: Introduction


4.2 Design of algorithm for problem such as generating prime numbers
4.3 Evaluation of polynomial
4.4 Sum of first n factorials
4.5 Finding nth term of Fibonacci sequence.

4.1 PROBLEM ANALYSIS AND DESIGN 1: INTRODUCTION

In the long history of mathematics, theory of numbers and factorizing


methods has been extensively studied. Even today also the studies are quite
relevant and useful.
With the development of computers, understanding and the application of
these algorithms has become very important. Many of the algorithms developed
long before and now are very much part of computer applications. For example:
prime numbers are used in many applications. Recently developed method of
encrypting text to make it contents obscure to any outside observer rely on the
fact that the product of two very large prime numbers is effectively impossible
to factorize in an acceptable time with non factoring methods. Prime numbers
also play role in past methods for Information retrieval that employee hashing
algorithm.
In this chapter we are going to design many algorithms like finding the
prime numbers, evaluation of polynomial, sum of first n factorials and find the
nth term of a Fibonacci sequence.

4.2 DESIGN OF ALGORITHM FOR PROBLEM SUCH AS


GENERATING PRIME NUMBERS

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

4.3 EVALUATION OF POLYNOMIAL

Polynomial Evaluation
Let us start with how to solve a polynomial. Following are the eight steps
to solve this problem:

Step 1: read X,N


Step 2: repeat the following instruction for all the Ns ( i= 1 to N)
read coefficients ai
Step 3: latest assign a value to variable p
p = ai * N
Step 4: repeat the following instructions from largest value of N to N=1 (
for i =N to 1)
p = (ai -1) + xp
Step 5: Print p

4.4 SUM OF FIRST N FACTORIALS

This problem can be divided in two parts


a) Find factorial of a number
Problem Analysis b) Find sum of first n factorials
46 and Design 1
a) Find factorial of a number Algorithm And
Program Design
Factorial of N items gives you the number of ways you can arrange the
given items. For example if there are two coins then you can arrange them in 2o
different ways. Likewise if you have three coins then there are 6 ways you can NOTES
arrange them.

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;
}

printf(“factorial = %d”, result);


return 0;
}

Sum of first n factorials


Problem Statement
Find the sum of first n factorials.

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

Sum of n numbers that have been calculated as result of first part.

printf(“ Enter a number num “);


scanf(“%d”,&num);
int Sum = 0;

for(i =1; i<=num; i++){


f= factorial (num);
sum = sum + f;
}

4.5 FINDING NTH TERM OF FIBONACCI SEQUENCE

Let us first understand, what is Fibonacci sequence?


The Fibonacci sequence is a series of numbers where a number is found by
adding up the two numbers before it.
Starting with 0 and 1, the sequence goes 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and
so forth.
Written as a rule, the expression is x(n) = x(n-1) + x(n-2)
Named after Fibonacci, also known as Leonardo of Pisa or Leonardo
Pisano, Fibonacci numbers were first introduced in his Liber abaci in 1202.
The son of a Pisan merchant, Fibonacci traveled widely and traded
extensively. Math was incredibly important to those in the trading industry, and
his passion for numbers was cultivated in his youth.
Knowledge of numbers is said to have first originated in the Hindu-Arabic
arithmetic system, which Fibonacci studied while growing up in North Africa.
Prior to the publication of Liber abaci, the Latin-speaking world had yet to be
introduced to the decimal number system. He wrote many books about geometry,
commercial arithmetic and irrational numbers. He also helped develop the .

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!

Let us write Fibonacci Series Algorithm


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
Problem Analysis b=Fibb
50 and Design 1
Algorithm And
increase value of i each time by 1(till i = n) Program Design
print the value of Fibb
Step 6: End NOTES

If we want to print a specific nth term in Fibonacci series , then we can


modify the above algorithm as following:

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

5.1 Problem Analysis and Design2: Introduction


5.2 Design of algorithm for problem such as finding largest and second
largest of list
5.3 Determining nth root of a number
5.4 Compute GCD
5.5 Base Conversion

5.1 PROBLEM ANALYSIS AND DESIGN2: INTRODUCTION

In this chapter, consider some advanced problems for algorithm writing.


for example: finding the second largest in a list, calculating the gcd of two
numbers, perform base conversions. application of gcd definitely help in a lot
of problems for example: gcd helps in Arithmetic for solving fractions, it also
helps in solving space issues where you have to store two quantities of different
dimensions, helps to find commonality where we can use either to two three
times or three two times to bring a six. There are cases where you need to
distribute, For example: what if same 10 chocolates were to be given to 5 kids
instead of 2. GCD has application in measurements and construction field.

5.2 DESIGN OF ALGORITHM FOR PROBLEM SUCH AS


FINDING LARGEST AND SECOND LARGEST OF LIST

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,

first = second = INT_MIN


2) Start traversing the list,
a) If the current element in list say ai is greater than first. Then update
first and second as,
second = first
first = ai
b) If the current element is in between first and second,
then update second to store the value of current variable as
second = ai
3) Return the value stored in first and second.

5.3 DETERMINING NTH ROOT OF A NUMBER

N-th root of a number


Given two numbers N and A, find N-th root of A. In mathematics, Nth root
of a number A is a real number that gives A, when we raise it to integer power
N. These roots are used in Number Theory and other advanced branches of
mathematics.
Problem Analysis
and Design 2 53
Algorithm And Examples
Program Design
Input : A = 81
N=4
NOTES
Output : 3
3^4 = 81

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,

According to Newton’s method


x (K+1) = x(K) – f(x) / f’(x)
Here f(x) = x^(N) – A
So f’(x) = N*x^(N - 1)
and x(K) denoted the value of x at Kth iteration
putting the values and simplifying we get,
x(K + 1) = (1 / N) * ((N - 1) * x(K) + A / x(K) ^ (N - 1))

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.

5.4 COMPUTE GCD

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

GCD = Multiplication of Common Factors


= 2*2*3
= 12
Problem Analysis
54 and Design 2
Basic Euclidean Algorithm for GCD Algorithm And
Program Design
The algorithm is based on below facts
• If we subtract smaller number from larger (we reduce larger number), NOTES
GCD doesn’t change. So if we keep subtracting repeatedly the larger of
two, we end up with GCD.
• Now instead of subtraction, if we divide smaller number, the algorithm
stops when we find remainder 0.
Below is a recursive C function to evaluate GCD using Euclid’s algorithm.

// C program to demonstrate Basic Euclidean Algorithm


#include <stdio.h>
// Function to return gcd of a and b
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
// Driver program to test above function
int main()
{
int a = 10, b = 15;
printf(“GCD(%d, %d) = %dn”, a, b, gcd(a, b));
a = 35, b = 10;
printf(“GCD(%d, %d) = %dn”, a, b, gcd(a, b));
a = 31, b = 2;
printf(“GCD(%d, %d) = %dn”, a, b, gcd(a, b));
return 0;
}

Problem Analysis
and Design 2 55
Algorithm And
Program Design
5.5 BASE CONVERSION
NOTES

Convert from any base to decimal and vice versa


Given a number and its base, convert it to decimal. The base of number can
be anything such that all digits can be represented using 0 to 9 and A to Z. Value
of A is 10, value of B is 11 and so on. Write a function to convert the number to
decimal.

Examples

Input number is given as string and output is an integer.

Input: str = “1100”, base = 2


Output: 12

Input: str = “11A”, base = 16


Output: 282

Input: str = “123”, base = 8


Output: 83

A repeated division and remainder algorithm can convert decimal to binary,


octal, or hexadecimal.
1. Divide the decimal number by the desired target radix (2, 8, or 16).
2. Append the remainder as the next most significant digit.
3. Repeat until the decimal number has reached zero.

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

6.1 Concept of Array, Sort and Search Technique: Introduction of Array


6.2 Array manipulation such as removing the duplicates, Partitioning of
an array
6.3 listing of prime numbers
6.4 finding prime factor of a number
6.5 The problem of search and Merge
6.6 Linear, Binary search algorithms
6.7 The Problem of Sorting, Selection, Insertion and Bubble sort

6.1 CONCEPT OF ARRAY, SORT AND SEARCH


TECHNIQUE: INTRODUCTION OF ARRAY

The concept of array is widely used in computing. By using array we can


store and organize data in Computer memory. By using array we can efficiently
refer data elements and we can perform computations over data elements. There
are different ways in which arrays can be used for computation.
To understand arrays in a better way, we can think of Array as a street with
the row of houses. All houses shares the same street name. But each house in the
street has a unique address to distinguish it from others. The address of the house
is made of two parts, name of the street and number of the plot. The street name
corresponds to the array name and the street number corresponds to the suffix.

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.

There are two types of array


1. Linear or one dimensional array
An array in which each element can be referenced by one subscript is
known as one dimensional array.

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.

Why we should use array?


In array, a collection of data is given a common name.
This can be explained by taking an example as following:

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.

6.2 ARRAY MANIPULATION SUCH AS REMOVING THE


DUPLICATES, PARTITIONING OF AN ARRAY

Removal of duplicates from an ordered array


Problem definition: Remove all the duplicates from an ordered array and
contract the array accordingly.
Algorithm development:
Let us take an example. Suppose following is the array from which we have
to remove the duplicates.

Concept of (Before removing the duplicates)


Array, Sort and
62 Search Technique
Algorithm And
Program Design
(After removing the duplicates)
NOTES
Now we have to find an appropriate process to remove the duplicates from
a given list. By looking at the example array we can find out that each element
in the original array has more as far as to the left as possible after removing the
duplicate. The algorithm should find duplicates in the original data. Duplicate
is identified when two adjacent elements are equal in value.
Following is the method that can be used to identify duplicate and compress
the array.
1. Create an auxiliary array temp [] to store unique elements.
2. Traverse input array and one by one copy unique elements of arr[] to
temp[]. Also keep track of count of unique elements. Let this count be j.
3. Copy j elements from temp[] to arr[] and return j

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.

6.3 LISTING OF PRIME NUMBERS

Already discussed in previous chapter

6.4 FINDING PRIME FACTOR OF A NUMBER

Already discussed in previous chapter

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

Searching for an element in a list is the process of checking, if a specified


element is present in the list and determining the location of the desired element
in the list.
We will discuss two searching algorithms
1. Linear search
2. binary search

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.

Advantage of Linear search


• It is easy to understand•
• it is not required the array to be ordered

Disadvantage of Linear search


• if there are 20000 items in the array and you are searching the element
that is at 19999 position, then we would have to search for entire list.
Best case: it is the value is equal to first element tested, in which only one
comparison is needed.
Worst case: is that value is not in the list or it is last item in the list, in
which case and comparisons are needed.

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.

Algorithm – Binary Search


Suppose A= Array name
B=Size of Array
X= Element to be searched.
Algorithm will find the location of X in array or otherwise give the massage
that the element is not found.

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”

6.6 THE PROBLEM OF SORTING, SELECTION,


INSERTION AND BUBBLE SORT

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

Algorithm –Bubble Sort.


Let A is linear array with N elements.

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

Step1 Find the minimum value in the list.


Step2 Swap it with the first position.
Step3 Repeat the above steps for remaining elements of list(Starting at
the second position).

Original Pass1 Pass2 Pass3 Sorted


List List
31 11 11 11 11
25 25 12 12 12
12 12 25 22 22
22 22 22 25 25
11 31 31 31 31
During pass1 ,find the smallest elements using a linear scan and swap it
into the first position in the list , then the during pass2 ,find the second smallest
element by scanning the remaining listand so on.

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

b. find sum of two numbers


c. find maximum numbers in a given list of numbers
d. Find minimum number in a given list of numbers.
e. Find the average of given list of numbers.
f. Find all the even numbers till a given natural number N.
g. Find sum of all odd numbers till a given natural number N.
h. Find all the numbers divisible by 3 till natural number N.
i. Find if the given number is even or odd.
j. Find if the given number is divisible by 4 or not.
Chapter 2: concept of structured programming and procedure
oriented programming
1. What are different types of programming languages? Differentiate
between procedure oriented programming and structured
programming.
2. What are the characteristics of structured programming?
3. Draw the flowchart and write an algorithm list of students. If the
student marks are less than 50, then the student is “fail", otherwise the
student is pass.
4. What is switch case? In which scenario we can use switch statement?
Write pseudo code for the switch statement.
5. What are different programmings constructs for iterative control
structures?
6. What are different benefits of using structured programming or
procedural oriented programming?

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.

Chapter 4: Problem analysis and design 1


1. Find list of prime numbers till a natural number N.
2. Write an algorithm to evaluate polynomials.
3. Write an algorithm to find an atom of a Fibonacci sequence.

Chapter 5: problem analysis and design 2


1. Suppose there is a list of students whose height is listed. Find the
student with highest height and the second highest height.
2. Write an algorithm to find the GCD of two numbers.
3. Write an algorithm to convert a binary number to a decimal number.
4. Write an algorithm to convert a binary number to hexadecimal number.
5. Write an algorithm to convert a decimal number to a binary number.

Chapter 6: Concept of Array, Sort and Search Technique


1. What is an array? What is the purpose of an array and how an array
is useful for solving computing problems?
2. What are the different applications where array can be used?
3. What are different types of arrays and also list their applications.
4. Write an algorithm to find duplicates in an array.
5. Write an algorithm to find prime factor of a number.
6. Write an algorithm to do linear search and binary search.
7. Compare the efficiency of linear search and binary search.
8. Explain the following sorting algorithm and compare their efficiency:
a. bubble sort
b. Insertion sort
c. selection Sort
*****
72 Chapter Heading

You might also like