0% found this document useful (0 votes)
14 views

Py Unit 1

Uploaded by

eshwarbala30
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Py Unit 1

Uploaded by

eshwarbala30
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

UNIT I- COMPUTATIONAL THINKING AND PROBLEM SOLVING 9


Fundamentals of Computing – Identification of Computational Problems - Algorithms, building blocks
of algorithms (statements, state, control flow, functions), notation (pseudo code, flow chart,
programming language), algorithmic problem solving, simple strategies for developing algorithms
(iteration, recursion).

Illustrative problems: find minimum in a list, insert a card in a list of sorted cards, and guess an integer
number in a range, Towers of Hanoi.

1.1 FUNDAMENTALS OF COMPUTING


 The term computer is derived from the word compute, which means to calculate.
 A computer is an electronic machine, devised for performing calculations and controlling operations
that can be expressed either in logical or numerical terms. With the help of instructions the computer is
able to process the information to achieve desired results.
 Computers were preceded by many devices which mankind developed for their computing
requirements. Some of those devices are sand tables, abacus, Napier bones, slide rule, Pascaline,
stepped reckoner, punch card machine, difference engine, analytical engine, and Hollerith's tabulator.

1.1.1 CHARACTERISTICS OF COMPUTERS


Speed:
 The computers process data at an extremely fast rate, at millions or billions of instructions per second.
 A computer can perform a huge task in a few seconds.
 The speed of a computer is calculated in MHz (Megahertz), that is, one million instructions per second.
Accuracy:
 The computers are also very accurate.
 The level of accuracy depends on the instructions and the type of machines being used.
 Since the computer is capable of doing only what it is instructed to do, faulty instructions for data
processing may lead to faulty results.
Reliability:
 Reliability is the measurement of the performance of a computer, which is measured against some
predetermined standard for operation without any failure.
 The major reason behind the reliability of computers is that, at hardware level, it does not require any
human intervention between its processing operations.
Storage Capability:
 Computers can store large amounts of data and can recall the required information almost
instantaneously.
 The main memory of the computer is relatively small and it can hold only a certain amount of data,
therefore, the data is stored on secondary storage devices such as magnetic tape or disks.
Versatility:
 Computers are quite versatile in nature.
 It can perform multiple tasks simultaneously with equal ease.
 For example, at one moment it can be used to draft a letter, another moment it can be used to play
music and in between, one can print a document as well.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Resource Sharing:
 In the initial stages of development, computers used to be isolated machines.
 With the tremendous growth in computer technologies, computers today have the capability to connect
with each other.
 Apart from device sharing, data and information can also be shared among groups of computers, thus
creating a large information and knowledge base.

1.1.2 GENERATIONS OF COMPUTERS


First Generation (1940-56): Vaccum Tubes
Second Generation (1956-63): Transistors
Third Generation (1964-1970): Integrated Circuits
Fourth Generation (1970s to till Date): Microprocessors
Fifth Generation( Present and Beyond): Artificial Intelligence

First Generation (1940-56): Vaccum Tubes:


 First generation computers were vacuum tubes/thermionic valve based machines.
 These computers used vacuum tubes for circuitry and magnetic drums for memory.
 Input was based on punched cards and paper tape and output was displayed in the form of printouts.
 First generation computers relied on binary-coded language (language of 0s and 1s) to perform
operations and were able to solve only one problem at a time.
Examples: ENIAC, EDVAC, and UNIVAC

Figure: Vaccum Tube


Characteristics of First Generation Computers
 These were the fastest computing devices of their times (computation time was in milliseconds).
 These computers were very large, and required a lot of space for installation.
 Since thousands of vacuum tubes were used, they generated a large amount of heat. Therefore, air
conditioning was essential.
 These were non-portable and very slow equipment’s.
 They lacked in versatility and speed.
 They were very expensive to operate and used a large amount of electricity.
 These machines were unreliable and prone to frequent hardware failures. Hence, constant maintenance
was required.
 Since machine language was used, these computers were difficult to program and use.

Second Generation (1956-63): Transistors


 Second generation computers used transistors, which were superior to vacuum tubes.
 Transistor is a small device, the physical size of computers was greatly reduced.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

 In second generation computers, magnetic cores were used as primary memory and magnetic disks as
secondary storage devices. However, they still relied on punched cards for input and printouts for
output.
 One of the major developments of this generation includes the progress from machine language to
assembly language.
 Assembly language used mnemonics (abbreviations) for instructions rather than numbers, for
example, ADD for addition and MULT for multiplication.
Examples: PDP-8, IBM 1401 and IBM 7090.

Figure: Transistors

Characteristics of Second Generation Computers


 These were smaller as compared to the first generation computers.
 The computational time of these computers was reduced to microseconds from milliseconds.
 These were more reliable and less prone to hardware failure. Hence, such computers required less
frequent maintenance.
 These were more portable and generated less amount of heat.
 Assembly language was used to program computers. Hence, programming became more time-efficient
and less cumbersome.
 Second generation computers still required air conditioning.

Third Generation (1964-1970): Integrated Circuits


 The development of the integrated circuit was the trait of the third generation computers. Also called
an IC, an integrated circuit consists of a single chip (usually silicon) with many components such as
transistors and resistors fabricated on it.
 Integrated circuits replaced several individually wired transistors. This development made computers
smaller in size, reliable, and efficient.
 Instead of punched cards and printouts, users interacted with third generation computers through
keyboards and monitors and interfaced with operating system.
Examples: NCR 395 and B6500.

Characteristics of Third Generation Computers


 They were able to reduce computational time from microseconds to nanoseconds.
 They were easily portable and more reliable than the second generation.
 These devices consumed less power and generated less heat. In some cases, air conditioning was still
required.
 The size of these computers was smaller as compared to previous computers.
 Since hardware rarely failed, the maintenance cost was quite low.
 Extensive use of high-level languages became possible.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Figure: IC

Fourth Generation (1970s to till Date): Microprocessors

 The fourth generation is an extension of third generation technology.


 The Intel 4004 chip, which was developed in 1971, took the integrated circuit one step further by
locating all the components of a computer (central processing unit, memory, and input and output
controls) on a minuscule chip.
Examples: Apple II, Altair 8800, and CRAY-1.

Figure: Microprocessor

Characteristics of Fourth Generation Computers


 Fourth generation computers are microprocessor-based systems.
 These computers are very small.
 Fourth generation computers are the cheapest among all the other generations.
 They are portable and quite reliable.
 These machines generate negligible amount of heat, hence they do not require air conditioning.
 Hardware failure is negligible, so minimum maintenance is required.
 The production cost is very low.
 GUI and pointing devices enable users to learn to use the computer quickly.
 Interconnection of computers leads to better communication and resource sharing.

Fifth Generation( Present and Beyond): Artificial Intelligence

 Fifth generation computers will use mega chips, which will result in the production of microprocessors
having millions of electronic components on a single chip.
 They will use intelligent programming (AI) and knowledge-based problem-solving techniques.

1.1.3 CLASSIFICATION OF COMPUTERS

 Computers can be classified according to their purpose (whether the computer is meant for general-
purpose or special-purpose), data handling (whether the computer uses analog or digital data or
combination of both), and functionality (whether the computer handles large volume of data or small).
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

 According to general-purpose computer, as the name suggests, is designed to perform a range of


tasks.
 On the other hand, a special-purpose computer is designed to handle a specific problem or to perform
a single specific task.
 According to the basic data handling principle, computers can be classified into three categories:
analog, digital, and hybrid.
 A computing machine that works on the principle of measuring, in which the measurements obtained
are translated into desired data is known as analog computer.
 A computer that operates with information, numerical or otherwise, represented in a digital form is
known as digital computer.
 Hybrid computer incorporated the measuring feature of an analog computer and counting feature of a
digital computer.
 Based on physical size, performance and application areas, we can divide computers generally into
four major categories: micro, mini, mainframe, and super computers.
 A microcomputer is a small, low cost digital computer, which usually consists of a microprocessor, a
storage unit, an input channel, and an output channel, all of which may be on one chip inserted into one
or several PC boards. Microcomputers include desktop, laptop, and hand-held computers such as
PDAs.
 A minicomputer is a small digital computer, which normally is able to process and store less data than
a mainframe but more than a microcomputer, while doing so less rapidly than a mainframe but more
rapidly than a microcomputer.
 A mainframe is an ultra-high performance computer made for high-volume, processor-intensive
computing. It consists of a high-end computer processor, with related peripheral devices, capable of
supporting large volumes of data processing, high performance on-line transaction processing systems,
and extensive data storage and retrieval.
 Super computers are the special purpose machines, which are specially designed to maximize the
numbers of FLOPS. A super computer has the highest processing speed at a given time for solving
scientific and engineering problems.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

1.1.4 THE COMPUTER SYSTEM

 A computer can be viewed as a system, which consists of a number of interrelated components that
work together with the aim of converting data into information.
 To attain information, data is entered through input unit, processed by central processing unit (CPU),
and displayed through output unit.
 In addition, computers require memory to process data and store output.
 All these parts (the central processing unit, input, output, and memory unit) are referred to
as hardware of the computer.

Components of a computer
 The basic components of a computer system include input unit, central processing unit (CPU),
output unit, and storage unit.

 The input unit is formed by attaching various input devices such as keyboard, mouse, light pen, and so
on to a computer. An input device is an electromechanical device that accepts instructions and data
from the user.
 Some of the commonly used input devices are keyboard, pointing devices like mouse and joystick,
digital camera, and scanners.
 The central processing unit (CPU) referred to as the “brain” of a computer system, converts data
(input) into meaningful information (output). A CPU controls all internal and external devices,
performs arithmetic and logic operations, and operates only on binary data, that is, data composed of 1s
and 0s.
 The arithmetic/logic unit (ALU) contains the electronic circuitry that executes all arithmetic and
logical operations on the data made available to it.
 The control unit of the CPU contains circuitry that uses electrical signals to direct the entire computer
system to carry out, or execute, stored program instructions. This unit checks the correctness of
sequence of operations.
 Registers are special-purpose, high-speed temporary memory units that hold various types of
information such as data, instructions, addresses, and the intermediate results of calculations.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

 The output unit is formed by attaching output devices such as printer, monitor, and plotter to the
computer. An output device is used to present the processed data (results) to the user.
 A computer system incorporates storage unit to store the input entered through input unit before
processing starts and to store the results produced by the computer before supplying them to the output
unit.
 The output, which can be easily understood and used by human beings, are of two forms: hard copy
and soft copy.
 Based on the hard copy and soft copy outputs, the output devices are classified into: hard copy and
soft copy output devices. Printers and plotters are the most commonly used hard copy output devices.
The commonly used soft copy output is computer monitor.
 Memory classified into two broad categories: primary memory and secondary memory.
 Primary Memory, also known as main memory, stores data and instructions for processing and can be
further classified into random access memory (RAM) and read only memory (ROM).
 Secondary Memory, also known as auxiliary memory or external memory is used for storing
instructions (software programs) and data, since main memory is temporary and limited in size.

Applications:
 Science
 Education
 Medical and Health Care
 Engineering/Architecture/Manufacturing
 Entertainment
 Communication
 Business Application
 Publishing
 Banking

1.2 IDENTIFICATION OF COMPUTATIONAL PROBLEMS

PROBLEM SOLVING
 Problem solving is the systematic approach to define the problem and creating number of
solutions.
 The problem solving process starts with the problem specifications and ends with a correct
program.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Problem solving techniques

 Problem solving technique is a set of techniques that helps in providing logic for solving a problem.
 Problem solving can be expressed in the form of
Algorithms
Flowcharts.
Pseudo codes.
Programs

Analysis - In this stage we should find what the problem should do.
Design - The way or method of how our problem is solved.
Development - The method found in design is then coded here in a given programming language.
Testing -Here we verify that the program written is working correctly.
Implementation – Finally the program is ready to use.

1.3 BUILDING BLOCKS OF ALGORITHM

Algorithm
 It is defined as a sequence of instructions that describe a method for solving a problem.
 In other words it is a step by step procedure for solving a problem.
 Should be written in simple English.
 Each and every instruction should be precise and unambiguous.
 Instructions in an algorithm should not be repeated infinitely.
 Algorithm should conclude after a finite number of steps.
 Should have an end point.
 Derived results should be obtained only after the algorithm terminates.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Qualities of a good algorithm


 The following are the primary factors that are often used to judge the quality of the
algorithms.
Time – To execute a program, the computer system takes some amount of time. The lesser is the time
required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory space. The lesser is
the memory required, the better is the algorithm.
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given problem, some of
these may provide more accurate results than others, and such algorithms may be suitable.

 An algorithm is constructed using following blocks.


 Statements
 States
 Control flow
 Function
Statements
 Statements are simple sentences written in algorithm for specific purpose.
 Statements may consists of assignment statements, input/output statements, comment statements
Example:
Read the value of ‘a’ //This is input statement
Calculate c=a+b //This is assignment statement
Print the value of c // This is output statement
Comment statements are given after // symbol, which is used to tell the purpose of the line.

States
 An algorithm is deterministic automation for accomplishing a goal which, given an initial state, will
terminate in a defined end-state.
 An algorithm will definitely have start state and end state.

Control Flow
 Control flow which is also stated as flow of control, determines what section of code is to run in
program at a given time.
 There are three types of flows, they are
 Sequential control flow
 Selection or Conditional control flow
 Looping or repetition control flow

Sequential control flow


 The name suggests the sequential control structure is used to perform the action one after
another.
 Only one step is executed once.
 The logic is top to bottom approach.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Example
Description: To find the sum of two numbers.
Step 1: Start
Step 2: Read the value of ‘a’
Step 3: Read the value of ‘b’
Step 4: Calculate sum=a+b
Step 5: Print the sum of two number
Step 6: Stop

Selection or Conditional control flow


 Selection flow allows the program to make choice between two alternate paths based oncondition. It
is also called as decision structure

Basic structure:

IF CONDITION is TRUE then


perform some action
ELSE IF CONDITION is FALSE then
perform some action

Example
Description: finding the greater number
Step 1: Start
Step 2: Read a
Step 3: Read b
Step 4: if a>b then
print a is greater
Step 5: else
print b is greater
Step 6: Stop

Repetition control flow

Basic Structure:

Repeat until CONDITION is true


Statements

 Repetition control flow means that one or more steps are performed repeatedly until some condition is
reached.
 This logic is used for producing loops in program logic when one or more instructions may need to be
executed several times or depending on condition.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Example:
Description: to print the values from 1 to n
Step 1: Start
Step 2: Read the value of ‘n’
Step 3: Initialize i as 1
Step 4: Repeat step 4.1 until i< n
Step 5: Print i
Step 6: Stop

Function
 A function is a block of organized, reusable code that is used to perform a single, related action.
Function is also named as methods, sub-routines.
Elements of functions:
 Name for declaration of function.
 Body consisting local declaration and statements.
 Formal parameter.
 Optional result type.

Basic Syntax

function_name(parameters)
function statement1
…………………...
……………………
function n statements
function_name(parameters)
end function
Algorithm for addition of two numbers using function
main function()
Step 1: Start
Step 2: Call the function add()
Step 3: Stop

sub function add()


Step1: Function start
Step2: Get a,bValues
Step 3: add c=a+b
Step 4: Print c
Step 5: Return

1.3 NOTATIONS OF AN ALGORITHM


 Algorithm can be expressed in many different notations, including Natural Language, Pseudo
code, flowcharts and programming languages.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

 Natural language tends to be verbose and ambiguous.


 Pseudocode and flowcharts are represented through structured human language.
 A notation is a system of characters, expressions, graphics or symbols designs used among each others
in problem solving to represent technical facts, created to facilitate the best result for a program.

1. Pseudocode
 Pseudocode is an informal high-level description of the operating principle of a computer
program or algorithm.
 It uses the basic structure of a normal programming language, but is intended for human reading
rather than machine reading.
 It is text based detail design tool. Pseudo means false and code refers to instructions written in
programming language.
 Pseudocode cannot be compiled nor executed, and there are no real formatting or syntax rules.
The pseudocode is written in normal English language which cannot be understood by the computer.

Example:
Pseudocode: To find sum of two numbers
READ num1, num2
sum=num1+num2
PRINT sum

Basic rules to write pseudocode:


 Only one statement per line.
 Statements represents single action is written on same line.
 For example to read the inputs, all the inputs must be read using single statement.
 Capitalized initial keywords.
 The keywords should be written in capital letters.
Input: READ, OBTAIN, GET, and PROMPT
Output: PRINT, DISPLAY, and SHOW
Compute: COMPUTE, CALCULATE, and DETERMINE
Initialize: SET and INITIALIZE
Add One: INCREMENT
Example:
Pseudocode: Find the total and average of three subjects
READ name, department, mark1, mark2, mark3
Total=mark1+mark2+mark3
Average=Total/3
WRITE name, department, mark1, mark2, mark3
 Indent to show hierarchy
 Indentation is a process of showing the boundaries of the structure.
 End multi-line structures
 Each structure must be ended properly, which provides more clarity.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Example:
Pseudocode: Find greatest of two numbers
READ a, b
IF a>b then
PRINT a is greater
ELSE
PRINT b is greater
ENDIF

 Keep statements language independent.


 Pseudocode must never written or use any syntax of any programming language.

Advantages of Pseudocode
 Can be done easily on a word processor
 Easily modified
 Implements structured concepts well
 It can be written easily
 It can be read and understood easily
 Converting pseudocode to programming language is easy as compared with flowchart.

Disadvantages of Pseudocode
 It is not visual
 There is no standardized style or format

2. Flowchart
 A graphical representation of an algorithm.
 Flowcharts is a diagram made up of boxes, diamonds, and other shapes, connected by arrows.
 Each shape represents a step in process and arrows show the order in which they occur.
Flowchart Symbols
S.No Name of Symbol Type Description
symbol
1. Terminal Oval Represent the start and
Symbol stop of the program.

2. Input/Output Parallelogra Denotes either input or


symbol m output operation.

3. Process symbol Rectangle Denotes the process to


be carried

4. Decision Diamond Represents decision


symbol making and branching
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

5. Flow lines Arrow lines Represents the


sequence of steps and
direction of flow.
Used to connect
symbols.

6. Connector Circle A connector symbol is


represented by a circle
and a letter or digit is
placed in the circle to
specify the link. This
symbol is used to
connect flowcharts.
Rules for drawing flowchart
 In drawing a proper flowchart, all necessary requirements should be listed out in logicalorder.
 The flow chart should be clear, neat and easy to follow. There should not be any room for ambiguity
in understanding the flowchart.
 The usual directions of the flow of a procedure or system is from left to right or top to bottom.
 Only one flow line should come out from a process symbol.

 Only one flow line should enter a decision symbol, but two or three flow lines, one for each
possible answer, cap leave the decision symbol.

 Only one flow line is used in conjunction with terminal symbol.

 If flowchart becomes complex, it is better to use connector symbols to reduce the number of
flow lines.
 Ensure that flowchart has logical start and stop.

Advantages of Flowchart
Communication: Flowcharts are better way of communicating the logic of the system.
Effective Analysis With the help of flowchart, a problem can be analyzed in more effective way.
Proper Documentation: Flowcharts are used for good program documentation, which is needed for
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

various purposes.
Efficient Coding: The flowcharts act as a guide or blue print during the system analysis and program
development phase.
Systematic Testing and Debugging: The flowchart helps in testing and debugging the program
Efficient Program Maintenance The maintenance of operating program becomes easy with the help of
flowchart. It helps the programmer to put efforts more efficiently on that part.

Disadvantages of Flowchart
Complex Logic: Sometimes, the program logic is quite complicated. In that case flowchart
becomes complex and difficult to use.
Alteration and Modification: If alterations are required the flowchart may require re- drawing
completely.
Reproduction: As the flowchart symbols cannot be typed, reproduction becomes problematic.

3. Control Structures using flowcharts and Pseudocode

Sequence Structure
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Conditional Structure
 Conditional structure is used to check the condition. It will be having two outputs only (True or False)
 IF and IF…ELSE are the conditional structures used in Python language.
 CASE is the structure used to select multi way selection control. It is not supported in Python.
IF

IF… ELSE
 IF…THEN…ELSE is the structure used to specify, if the condition is true, then execute Process1, else,
that is condition is false then execute Process2

Yes
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Example:

Iteration or Looping Structure


 Looping is generally used with WHILE or DO...WHILE or FOR loop.
 WHILE and FOR is entry checked loop
 DO…WHILE is exit checked loop, so the loop will be executed at least once.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

 In python DO…WHILE is not supported.


 If the loop condition is true then the loop gets into infinite loop, which may lead to system crash.

Programming Language
 A programming language is a vocabulary and set of grammatical rules for instructing a computer or
computing device to perform specific tasks.
 In other word it is set of instructions for the computer to solve the problem.
 Programming Language is a formal language with set of instruction, to the computer to solve a
problem.
 The program will accept the data to perform computation.
Program= Algorithm +Data Need for Programming Languages
 Programming languages are also used to organize the computation.
 Using Programming language we can solve different problems.
 To improve the efficiency of the programs.

Types of Programming Language


In general Programming languages are classified into three types. They are
 Low – level or Machine Language
 Intermediate or Assembly Language
 High – level Programming language
Machine Language
 Machine language is the lowest-level programming language (except for computers that utilize
programmable microcode).
 Machine languages are the only languages understood by computers. It is also called as low level
language.
Example code:
100110011
111001100
Assembly Language
 An assembly language contains the same instructions as a machine language, but the instructions
and variables have names instead of being just numbers.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

 An assembler language consists of mnemonics, mnemonics that corresponds unique machine


instruction.
Example code:
start
add x,y
sub x,y
High – level Language
 A high-level language (HLL) is a programming language such as C, FORTRAN, or Pascal that
enables a programmer to write programs that are more or less independent of a particular type of
computer.
 Such languages are considered high-level because they are closer to human languages and further from
machine languages.
 Ultimately, programs written in a high-level language must be translated into machine language by a
compiler or interpreter.
Example code: print(“Hello World!”)
High level programming languages are further divided as mentioned below

Language Type Example


Interpreted Programming Language Python, BASIC, Lisp
Functional Programming Language Clean, Curry, F#
Compiled Programming Language C++,Java, Ada, ALGOL
Procedural Programming Language C,Matlab, CList
Scripting Programming Language PHP,Apple Script, Javascript
Markup Programming Language HTML,SGML,XML
Logical Programming Language Prolog, Fril
Concurrent Programming Language ABCL, Concurrent PASCAL
Object Oriented Programming Language C++,Ada, Java, Python

Interpreted Programming Language


 Interpreter is a program that executes instructions written in a high-level language.
 An interpreter reads the source code one instruction or one line at a time, converts this line into
machine code and executes it.

Compiled Programming Languages


 Compile is to transform a program written in a high-level programming language from source code
into object code. This can be done by using a tool called compiler.
 A compiler reads the whole source code and translates it into a complete machine code program to
perform the required tasks which is output as a new file.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Interpreted vs. Compiled Programming Language

Interpreted Programming Language Compile Programming Language


Scans entire program and translates it as
Translates one statement at a time whole
into machine code
It takes less amount of time to analyze It takes large amount of time to analyze
the the
source code but the overall execution source code but the overall execution
time is slower time is comparatively faster
Generates intermediate object code
No intermediate object code is generated, which
hence are memory efficient further requires linking, hence requires
more memory
Continues translating the program until It generates the error message only after
first error is met, in which case it stops. scanning the whole program. Hence
Hence debugging
debugging is easy. is comparatively hard.
Eg: Python, Ruby Eg: C,C++,Java

1.4 ALGORITHMIC PROBLEM SOLVING:

 Algorithmic problem solving is solving problem that require the formulation of an algorithm for the
solution.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Understanding the problem


 Understanding the given problem is very important before solving the problem.
 Understand the problem and clarify the doubts before going into next stage.
 Correct algorithm should work for all possible inputs.
 In this stage analyze what are all the inputs, required data, analyze who is going to use this system and
what is the desired output.
Ascertaining the Capabilities of the Computational Device
 The second step is to find out the capabilities of a machine.
 The instructions are executed one after another, one operation at a time,
 Depending on the capability of machine, algorithm is classified as
(i) Sequential algorithm (ii) Parallel algorithm

Choosing between exact and approximate problem solving


 The next decision is to choose between solving the problem exactly or solving it approximately. Based
on this, the algorithms are classified as exact and approximation algorithms. There are three issues to
choose an approximation algorithm.
1. There are certain problems like extracting square roots, solving non-linear equations which
cannot be solved exactly.
2. If the problem is complicated, it slows the operations. E.g. traveling salesman problem.
3. This algorithm can be a part of a more sophisticated algorithm that solves a problem
exactly.
Deciding on data structures
Data structures play a vital role in designing and analyzing the algorithms. Some of the algorithm design
techniques also depend on the structuring data specifying a problem's instance.
Algorithm + Data structure = Programs
Algorithm design techniques
An algorithm design technique is a general approach to solving problems algorithmically that is
applicable to a variety of problems from different areas of computing. Learning these techniques is
important for two reasons.
1. They provide guidance for designing for new problems.
2. Algorithms are the cornerstones of computer science.
Algorithm design techniques make it possible to classify algorithms according to an underlying
design idea; therefore, they can serve as a natural way to both categorize and study algorithms.

Methods of specifying an algorithm


 Flowcharts and pseudo code are used for specifying an algorithm.
 Flowchart is a pictorial representation of algorithm.
 A Pseudocode, which is a mixture of a natural language and programming language like constructs.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Proving an algorithm's correctness


 Correctness has to be proved for every algorithm.
 To prove that the algorithm gives the required result for every legitimate input in a finite amount of
time.
 A technique used for proving correctness by mathematical induction because analgorithm’s iterations
provide a natural sequence of steps needed for such proofs.
Analyzing an Algorithm
1. Efficiency.
Time efficiency: indicating how fast the algorithm runs,
Space efficiency: indicating how much extra memory it uses
2. Simplicity.
 An algorithm should be precisely defined and investigated with mathematical
expressions.
 Simpler algorithms are easier to understand and easier to program.
 Simple algorithms usually contain fewer bugs.

Coding an algorithm
 Programming the algorithm by using some programming language.
 Validity is done through testing and debugging.
 Inputs should fall within a range and hence require no verification. The analysis has to be done in various
sets of inputs.
 A good algorithm is a result of repeated effort and work.
 The program's stopping or terminating condition has to be set.
 Another important issue is the question of whether or not every problem can be solved by an algorithm.
 And the last, is to avoid the ambiguity which arises for a complicated algorithm.

Simple strategies for developing algorithm:


They are two commonly used strategies used in developing algorithm
 Iteration
 Recursion

Iteration
 The iteration is when a loop repeatedly executes till the controlling condition becomes false.
 The iteration is applied to the set of instructions which we want to get repeatedly executed.
 Iteration includes initialization, condition, and execution of statement within loop and update
(increments and decrements) the control variable.
 A sequence of statements is executed until a specified condition is true is called iterations.
for loop
while loop
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Recursions:
 A function that calls itself is known as recursion.
 Recursion is a process by which a function calls itself repeatedly until some specified
condition has been satisfied.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Algorithm for factorial of n numbers using recursion:


Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop
Sub function factorial(n):
Step1: if(n==1) then fact=1 return fact
Step2: else fact=n*factorial(n-1) and return fact

Pseudo code for factorial using recursion:


Main function:
BEGIN
GET n
CALL
factorial(n)
PRINT fact
Sub function factorial(n):
IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Difference between Recursive algorithm and Iterative algorithm


Recursive algorithm:

o In recursive algorithm, the function calls itself until the condition is met.
o It is slower than iteration.
o It uses more memory than iteration.
o Recursion is like a selection structure, and which makes code smaller and clean.
o Tracing the code will be more difficult in the case large programs.

Iterative algorithm:

o Iterative algorithm is a repetition process until the condition fails.


o Here code may be longer but it is faster than recursive.
o It consumes less memory.
o If the loop condition is always true in such cases it will be an infinite loop.

ILLUSTRATIVE PROBLEMS
1. Guess an integer in a range
Algorithm:
Step1: Start
Step 2: Declare n, guess
Step 3: Compute
guess=input
Step 4: Read guess
Step 5: If guess>n, then
Print your guess is too high
Else
Step6:If guess<n, then
Print your guess is too low
Else
Step 7:If guess==n,then
Print Good job
Else
Nope
Step 8: Stop

Pseudocode:
BEGIN
COMPUTE guess=input
READ guess,
IF guess>n
PRINT Guess is high
ELSE
IF guess<n
PRINT Guess is low
ELSE
IF guess=n
PRINT Good job
ELSE
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Nope
END

2. Find minimum in a list


Algorithm:
Step 1: Start
Step 2: Read n
Step 3:Initialize i=0
Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5
Step4.1: Read a[i]
Step 4.2: i=i+1 goto step 4
Step 5: Compute min=a[0]
Step 6: Initialize i=1
Step 7: If i<n, then go to step 8 else goto step 10
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Step 8: If a[i]<min, then goto step 8.1,8.2 else goto 8.2


Step 8.1: if min=a[i]
Step 8.2: i=i+1 goto 7
Step 9: Print min
Step 10: Stop

Flowchart

Pseudocode:
BEGIN
READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
COMPUTE min=a[0]
FOR i=1 to n, then
IF a[i]<min, then
CALCULATE min=a[i]
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

INCREMENT i
ELSE
INCREMENT i
END IF-ELSE
END FOR
PRINT min
END

3. Insert a card in a list of sorted cards

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

Pseudocode:
BEGIN
READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
READ item
FOR i=n-1 to 0 and item<a[i], then
CALCULATE a[i+1]=a[i]
DECREMENT i
END FOR
COMPUTE a[i+1]=a[i]
COMPUTE n=n+1
FOR i=0 to n, then
PRINT a[i]
INCREMENT i
END FOR
END
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Flowchart:

4. Towers of hanoi
This problem was introduced by French mathematician Edouard lucas in 1883.
Problem:
 Given 3 posts labeled as A, B, and C. Now, in post A, there are n disk of different sizes arranged in
the order of largest disk at the bottom, smallest disk on the top. Post B and C are empty.
 The objective is to move the n disks from post A to post C, obeying the following rules:

Rule 1: Only one disk can be moved from one post to another post at a time.
Rule 2: A disk can be placed only on a top of a larger disk
Rule 3: A disk can be moved from top only
Rule 4: No disk can be placed on top of smaller disk.
Post A is known as Source
Post B is known as Auxiliary
Post C is known as Destination
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

If n=1  Move disk A to C

If n = 2  Move disk 1 A to B
Move disk 2 A to C
Move disk 1 B to C
If n = 3
Initial Condition
Step 1: Move disk 1 from post A to C
Step 2: Move disk 2 from post A to B
Step 3: Move disk 1 from post C to B
Step 4:Move disk 3 from post A to C
Step 5: Move disk 1 from post B to A
Step 6: Move disk 2 from post B to C
Step 7: Move disk 1 from post A to C

If n=4
Initial condition:
Step 1: Move disk 1 from post A to B
Step 2: Move disk 2 from post A to C
Step 3: Move disk 1 from post B to C
Step 4: Move disk 3 from post A to B
Step 5: Move disk 1 from C to A
Step 6: Move disk 2 from post C to B
Step 7; Move disk 1 from post A to B
Step 8: Move disk 4 from post A to C
Step 9: Move disk 1 from post B to C
Step 10: Move disk 2 from post B to A
Step 11: Move disk 1 from post C to A
Step 12: Move disk 3 from post B to C
Step 13:Move disk 1 from post A to B
Step 14:Move disk 2 from post A to C
Step 15:Move disk 1 from post B to C

A recursive algorithm for Tower of Hanoi can be driven as follows –


START
Procedure Hanoi((n, source, dest, aux)
if(n == 1) then
Move disk from source to destination.
else:
Hanoi(n-1, source, auxiliary, destination)
Move disk from source to destination
Hanoi(n-1, auxiliary, destination, source)
endif
End Procedure
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Stop
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

UNIT I- COMPUTATIONAL THINKING AND PROBLEM SOLVING

2 MARKS

1. What is an algorithm?
a. Algorithm is a set of rules for solving a problem in finite number of steps.
b. An algorithm defined as a finite sequence of explicit instructions.
c. Algorithm can have steps that repeat (iterate) or require decisions (logic and comparison) until
the task is completed.

2. Write an algorithm two accept two numbers compute the sum and print the result.
Step 1: Start
Step 2: Read two values in ‘A’ and ‘B’
Step 3: Add ‘A’ and ‘B’ and store the result in ‘C’
Step 4: Display ‘C’
Step 5: Stop

3. List the symbols used in drawing the flowchart.

4. Define recursive function.


 A function calls itself again and again till the base condition (stopping condition) is
satisfied.
 Recursive algorithms are mostly used to solve complicated problems when their
application is easy and effective. For example Tower of Hanoi algorithm is made easy
by recursion.

5. Distinguish between algorithm and program.

S.No Algorithm Program


1 Algorithm is finite Program is need not to be finite
2 Algorithms are written using natural Programs are written using a specific
language or algorithmic language. programming language

6. Write an algorithm to find the minimum number in a given list of numbers.


Step 1: Start the Program
Step 2: Read the elements one by one in the list ‘A’
Step 3: find the minimum in the list ‘A’ using the function min(A)
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Step 3: Stop

7. Differentiate: algorithm, flowchart and pseudocode.

8. Define Function.
 Function is self contained block.
 It is used to perform specific task
 Larger programs are subdivided into smaller one by the use of functions (Modular
programming)
 Functions are also named as methods, subroutines or procedures.

9. Define programming language.


Computer programming languages are used to communicate instructions to the
computer. They are based on certain syntactic and semantic rules, which define the
meaning of each of the programming language construct.
E.g. 1. Interpreted programming languages, 2. Functional programming languages

10. Differentiate: Recursion and Iteration.

S.No Recursion Iteration


Function calls itself until the base iteration means repetition of process until the
1
condition is reached. condition fails
Iterative approach involves four steps,
Only base condition (terminate
2 initialization, condition, execution and
condition) is specified.
updation.
Recursion keeps your code short and
3 Iterative approach makes your code longer.
simple.
Recursion is slower than iteration due to
4 Iteration is faster.
overhead of maintaining stack.
Recursion takes more memory than
5 iteration due to overhead of maintaining Iteration takes less memory.
stack.

11. Write the characteristics of a good algorithm.


1. Time – To execute a program, the computer system takes some amount of time. The
lesser is the time required, the better is the algorithm.
2. Memory – To execute a program, computer system takes some amount of memory
space. The lesser is the memory required, the better is the algorithm.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

3. Accuracy – Multiple algorithms may provide suitable or correct solutions to a given


problem, some of these may provide more accurate results than others, and such
algorithms may be suitable.

12. List any five programming languages.


1. Interpreted programming languages
2. Functional programming languages
3. Compiled programming languages
4. Procedural programming languages
5. Object oriented programming language

13. What is Pseudo code?


 Set of instructions that mimic programming language instructions.
 It is an outline of a program, written in a form that can be easily converted into real
programming statements.
 Pseudocode uses plain English statements also known as PDL(Program Design
Language).
14. Write an algorithm to convert Celsius to Fahrenheit.
Step 1: Start the program
Step 2: Read Celsius
Step 3: Calculate Fahrenheit using the formula (Celsius*1.8) +32
Step 4: Print Fahrenheit
Step 5: Stop
15. Draw a flow chart to find largest of two numbers.

16. Write a Pseudocode to find area of a circle.


1. START
2. SET initial zero to Area.
3. READ the radius of the circle
4. FIND the area of the circle using formula
5. Area = 3.14 * r*r
6. WRITE output of area of the circle
7. STOP
17. Give the Python code to find the minimum among the list of 10 numbers.
A=[2,4,6,8,100,12,14,89,56,32]
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

B=min(A)
print(B)

PART B

1. What is an algorithm? Explain the building blocks of an algorithm.


2. Explain algorithmic problem solving with neat diagram.
3. Differentiate recursion and iteration. Explain the problem of Tower of Hanoi with 3 disks.
4. Write a recursive algorithm to solve towers of Hanoi problem.
5. Identify the simple strategies for developing an algorithm.
6. Write an algorithm to insert a card into a list of sorted cards.
step 1: Start the program
step 2: Read the elements in sorted order in the ‘list’
step 3: Read the element to be inserted in 'n'
step 4: Execute loop i from 0 to length of list until list element greater than 'n'
step 5: update the new list by inserting 'n' in the list by using the formula
list=list[:i]+[n]+list[i:]
step 6: Print the new list

Program:
list=[1,2,4,9,13]
n=10
for i in range(len(list)):
if(list[i]>n):
index=i
break
list=list[:i]+[n]+list[i:]
print(list)

7. Outline the algorithm for displaying the first n odd numbers.


Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 7
Step 5: Print i value and compute i=i+2
Step 6: go to step 4
Step 7: Stop
8. Outline the algorithm for displaying the first n natural numbers.
Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 7
Step 5: Print i value and increment i value by 1
Step 6: go to step 4
Step 7: Stop
9. Outline the algorithm for displaying the first n Even numbers.
Step 1: Start
Step 2: get n value.
Step 3: initialize i=2
Step 4: if (i<=n) go to step 5 else go to step 7
Step 5: Print i value and compute i=i+2
Step 6: go to step 4
Step 7: Stop
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

10. Draw a flowchart to accept three distinct numbers find the greatest and print the result.

11.Draw a flow chart to find sum of n numbers(AU 2018)

38
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

39
1. Write a program to find the area and circumference of the circle.

Algorithm:

Step 1: Start
Step 2: Input the radius of the circle.
Step 3: Find the area and circumference of the circle using the formula
Area 3.14*r*r
Circumference 2 * 3.14 *r
Step 4: Print the area and circumference of the circle
Step 5: Stop

Pseudocode:
Set initial zero to Area, Circumference
READ the radius of the circle
Find the area and circumference of the circle using formula
Area = 3.14 * r*r
Circumference = 2*3.14*r
WRITE output of area and circumference of the circle
Stop
Flow Chart

Start

Read r

Area = = 3.14 * r*r


Circumference=2*3.14*r

Print area, circumference

Stop 14
2. Write a program to find the roots of the quadratic equation.

Algorithm:

Step 1: Start
Step 2: Enter the value of a,b ,c
Step 3: Find the value of ‘D’ of using the formula
D b * b - 4*a*c
Step 4: If D is greater than or equal to zero then find the two roots are
root 1 (-b+sqrt(d))/(2*a)
root 2 (-b-sqrt(d))/(2*a)
Step 5: Print the two roots, root1,root2
Step 6: If D is not greater than or equal to zero, then print the roots are imaginary.
Step 7: Stop Flow Chart:

Pseudocode:
Start
Set initial zero to root1,root2
READ the value of a,b,c
Read a,b,c
Find descriminant
D b*b – 4*a*c
IF D>=0 THEN D=b*b – 4*a*c

Calculate root1 = (-b + sqrt(D))/(2*a)


root2 = (-b – sqrt (D)) / (2*a) No
ELSE If D >
=0
Roots are imaginary
Yes
ENDIF
WRITE root1,root2 Root 1 [ -b + sqrt(d)]/(2*a)
Root 2 [ -b - sqrt(d)]/(2*a)
Stop

Print root 1,
root 2

15 Stop
3. Write a program to find the factorial of the given number.

Algorithm:

Step 1: Start
Step 2: Read the value of n
Step 3: Set initial values to Fact i 1
Step 4: is i < = n else Goto step 6
Step 4.1 : Fact Fact * i
Step 4.2 : i i+1
Step 5: Goto Step 4
Step 6 : Print Fact
Step 7 : Stop

Pseudocode Flow Chart


Set initial one to fact, i
READ n value to find Factorial
IF ( I <=n) THEN Start
Fact = Fact * i
i = i +1
Read n
ENDIF
WRITE the factorial of the number
i=1

No
If i<
=n

Yes

Fact=Fact * i Print fact

i=i+1
Stop

16
4. Write a program to find the given number is an Armstrong number or not.

Algorithm:

Step 1: Start
Step 2: Enter the value of n
Step 3: Assign a n, r = 0, sum =0
Step 4: If n > 0 ELSE Goto Step 6
Step 4.1 : r n mod 10
Step 4.2 : sum sum + r * r * r
Step 4.3 : n n div 10
Step 5: Goto Step 4
Step 6: IF a == sum THEN print Armstrong
ELSE print not Armstrong
Step 7: Stop

Pseudocode:

Set initial a=n, sum=0, r=0


READ the value of n
WHILE (n>0)
r = n % 10
sum = sum+r*r*r*
n = n//10
ENDWHILE
Repeat while until the condition fail
IF (sum ==a) THEN
WRITE the result is Armstrong

ELSE
WRITE the result is not Armstrong
ENDIF
Stop

17
FlowChart

Start

Read n

a=n
Sum=0

No
is
n>0
Yes

r= n mod 10
Sum = Sum + r *
r*r
n = n div 10

if No
a=
Sum
Yes

Print not
Print
Armstrong
Armstrong

Stop

18
5. Write a program to find whether the number is prime or not.

Algorithm: Flow Chart:

Step 1: Start
Step 2: Assign i 2 Start

Step 3: READ n
Step 4: REPEAT Steps 4.1, 4.2
i =2
UNTIL i < = n-1
Step 4.1 : IF (n mod i =0) THEN
Read n
Step 4.1.1: Prime not Prime
Step 4.1.2: Exit
Step 4.2 : i i+1
Step 5: IF (i=n) Then if No
i<=n
Step 6: Print Prime
Step 7: Stop Yes

Pseudocode:
if
Set initial 2 to i n % i ==0

READ n
IF (i<=n-1)
IF (n mod i=0)
Prime not Prime
WRITE “ Not Prime “
EXIT
ENDIF A
i = i+1
IF (i =n)
i=i+1
WRITE “Prime”
ENDIF
ENDIF
Stop if = n
No
Yes

Yes Print prime


A
Stop

19
6. Write a program to find the largest of three numbers.

Algorithm: Flow Chart

Step 1: Start
Step 2: READ a,b,c Start
Step 3: IF (a>b) and (a>c ) Then
Step 3.1 : Print ‘A is Big’
ELSE
Read a,b,c
Step 4: IF (b>c) Then
Step 4.1 : Print ‘B is big’
ELSE Yes
Step 4.2: Print ‘C is Big’ if a>b and a >c
Step 5: Stop
No Print A is
Big
Pseudocode: Yes
if b > c
READ the value for a,b ,c Print B is
IF (a>b and a>c ) THEN No big
WRITE ‘A is Big ’
Print C is Big
ELSE IF ( b > c) THEN
WRITE ‘ B is Big ’
ELSE
WRITE ‘ C is Big’ Stop
ENDIF
Stop

𝑥3 𝑥5 𝑥7 𝑥𝑛
7. Write a program to solve the series s =x - + + +
3! 5! 7! 𝑛!
Algorithm:

Step 1: Start
Step 2: Read the value of x,n
Step 3: Assign s 0 , term x, i 1
Step 4: The value of the term incremented to get next term and the term is added to s.

20
Step 5: s s+ term
Step 6: term = term * x* x(-1) / (i+1) (i +2)
Step 7: i i+2
Step 8: Repeat step 5 to step 7 WHILE (i <=n)
Step 9: Stop

Pseudocode:

Set initial to s, term = x, i =1


WHILE (i <=n)
s = s + term
term = (term *x*x(-1) / (i+1)*(i+2))
i= i+2
ENDWHILE
Repeat while until the condition fail
WRITE the Result
Stop

Flow Chart :

Start

Read x,n

s =0 term = x i =1

while i < = n

s = s + term
𝑡𝑒𝑟𝑚∗∗(−1)
term = (𝑖+1)(𝑖+2)
i = i +2

Print s

Stop
21
8. Write a program to find minimum and maximum number from the list.

Algorithm:

Step 1: Start the program


Step 2: READ the upper limit of the array ‘n’
Step 3: READ an array a[] of ‘n’ numbers
Step 4: Assign first array value to
MAX a[0] and MIN a[0]
Step 5: For i =2 to n
Step 6: if a[i] > MAX then MAX = a[i]
Step 7: if a[i] < MIN then MIN= a[i]
Step 8: Repeat Step 5 to Step 7 until loop reached to ‘n’
Step 9: Print MAX, MIN
Step 10: Stop

Pseudocode:

Set initial i
READ n
READ an array a[] of ‘n’ numbers
Set MAX = a[0], MIN = a[0]
FOR i =2 to n
if a[i] > MAX then MAX = a[i]
if a[i] < MIN then MIN = a[i]
end-if
Print MAX, MIN
Stop

22
Flow Chart

Start

Read n

For i = 1 to n

Read a[i]

Max a[0] Min a[1]

for i =2 to n

If Yes
Yes
a[i] > Max

Max = a[i]
No
No
Yes
If Yes
a[i] < Min

No Min = a[i]
No

Print MAX, MIN

23
Stop
9. Write a program for Insertion Sort

Algorithm:

Step 1: Start of the program


Step 2: If it is the first element, it is already sorted. Return 1
Step 3: Pick next element
Step 4: Compare with all elements in the sorted sub-list
Step 5: Shift all the elements in the sorted sub-list that s greater than the value to be
stored.
Step 6: Insert the value
Step 7: Repeat until list is stored
Step 8: Stop

Pseudocode:

FOR I =1 to length(A) inclusive


do:
n = A[i]
Position = i
WHILE Position > 0 and A [Position-1]>n
do:
A[Position]=A[Position – 1]
Position = Position -1
END WHILE
ENDFOR

24
Flow Chart:

Start

for i = 1 to length array

Read n

n = A[i]

Position = i

while
Position > 0 and
A[Position] > n

No

A[Position] = A[Position-1]
Position = Position -1
Positio Yes

A[Position] = n

Stop

25

You might also like