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

Py Unit - 1

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

Py Unit - 1

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

1.

1 Introduction to Programming Concepts


Computer programs are collections of instructions that tell a computer how
to interact with the user, interact with the computer hardware and process data.
The first programmable computers required the programmers to write explicit
instructions (understandable by machines) to directly manipulate the hardware of
the computer. This “machine language” instructions was very tedious to write. By
contrast, higher level languages such as “C”, C++, Pascal, Cobol, Fortran, ADA and
Java are called “compiled languages” are easier to write. In a compiled language,
the programmer writes more general instructions and a compiler (a special piece
of software) automatically translates these high level instructions into machine
language.
We can contrast compiled programming languages with interpreted
programming languages. In an interpreted programming language, the statements
that the programmer writes are interpreted as and when the program is running.
Some popular interpreted languages include Basic, Visual Basic, Perl, Python, and
shell scripting languages such as those found in the UNIX, Linux and MacOS X
environment.
Programming Paradigm
Paradigm can also be termed as a method to solve problem or to do task.
Programming paradigm is an approach to solve a problem using any programming
language. In other words, it is a method to solve a problem using tools and techniques
that are available to us following a standard approach. There are lots of programming
languages that are known but all of them need to follow a strategy when they are
implemented and this methodology/strategy is paradigms.
1. 2 Problem Solving and Python Programming

1.1. Need for Programming


1.1.1. Program Logic
A program logic (also known as logic model, or outcome hierarchy) is used
to instruct a computer software program on how to perform a specific task The
program logic is represented as a linear sequence of steps needed to perform a
specific task to meet its desired outcomes. This generally consists of identifying the
inputs, activities, outputs, and outcomes (from immediate, to long term). A program
logic should ideally be developed in the project planning stage.
1.1.2. Program Design
Designing is a process that an organization uses to develop a program. It
is most often an iterative process involving research, consultation, initial design
testing and redesign. A program design is the plan of action that results from that
process. It requires three steps. They are:
1. An algorithm is a step-by-step description of the solution.
2. A flowchart is a diagrammatic representation of the solution.
3. A pseudocode is a high-level description of an algorithm for the selected
solution. Pseudocode uses structured programming constructs.
1.1.3. Programming Language Statements
It is an instruction written in a high-level language that commands the
computer to perform a specified action. A program written in such a language
formed by a sequence of one or more statements. A statement may have internal
components (e.g., expressions).
1.1.4. Program Documentation and Maintenance
Documentation is the information that describes the product to its users. It
consists of the product technical manuals and online information (including online
versions of the manuals and help facility descriptions).
Software maintenance is the modification of a software product after delivery
to correct faults, to improve performance or other attributes. The program may
require updating, sign of errors, etc, during the maintenance phase.
Algorithmic Problem Solving 1.3

1.2 Algorithms
In computing, we focus on the type of problems categorically known as
algorithmic problems, where their solutions are expressible in the form of algorithms.
The term ‘algorithm’ was derived from the name of Mohammed al-Khowarizmi, a
Persian mathematician in the ninth century. Al-Khowarizmi Algorismus (in
Latin) Algorithm.
An algorithm is a well-defined computational procedure consisting of a set of
instructions that takes some value or set of values, as input, and produces some
value or set of values, as output. In other word, an algorithm is a procedure that
accepts data; manipulate them following the prescribed steps, so as to eventually fill
the required unknown with the desired value(s).

People of different professions have their own form of procedure in their line
of work, and they call it by different names. For instance, a cook follows a procedure
commonly known as a recipe that converts the ingredients (input) into some culinary
dish (output), after a certain number of steps.
1.2.1 The Characteristics of a Good Algorithm
££ Precision : the steps are precisely stated (defined).
££ Uniqueness : results of each step are uniquely defined and only depend
on the Input and the result of the preceding steps.
££ Finiteness : the algorithm stops after a finite number of instructions are
executed.
££ Effectiveness : algorithm should be most effective among many different
ways to solve a problem.
££ Input : the algorithm receives zero or more finite number of inputs.
££ Output : the algorithm produces one or more finite number of outputs.
££ Language Independent : the algorithm is not dependent of any
language
££ Correctness : Algorithm returns correct output in a finite number of
steps
1. 4 Problem Solving and Python Programming

1.2.2 Building Blocks of Algorithm (Instructions, State, Control Flow,


Functions)
An algorithm is an effective method that can be expressed within a finite
amount of space and time and in a well-defined formal language for calculating a
function. Starting from an initial state and initial input, the instructions describe a
computation that, when executed, proceeds through a finite number of well-defined
successive states, eventually producing “output” and terminating at a final ending
state.
They could be used for sorting sets of numbers or for more complicated tasks,
like recommending user content on social media. Algorithms typically start with
initial input and instructions that describe a specific computation. When the
computation is executed, the process produces an output.
For example,
An algorithm to add two numbers :
1. Take two number as inputs
2. Add numbers using the + operator
3. Display the result.
1.2.3. How do algorithms work?
Algorithms can be expressed as natural languages, programming languages,
pseudocode, flowcharts and control tables. Natural language expressions are rare, as
they are more ambiguous. Programming languages are normally used for expressing
algorithms executed by a computer.
Algorithms use an initial input along with a set of instructions. The input is the
initial data needed to make decisions and can be represented in the form of numbers
or words. The input data gets through a set of instructions, or computations, which
can include arithmetic and decision-making processes. The output is the last step in
an algorithm and is normally expressed as more data.
For example, a search algorithm takes a search query as input and runs it
through a set of instructions for searching through a database for relevant items
to the query. Automation software acts as another example of algorithms, as
automation follows a set of rules to complete tasks. Many algorithms make up
automation software, and they all work to automate a given process.
Algorithmic Problem Solving 1.5

1.2.4. Qualities of a Good Algorithm


££ Input and output should be defined precisely.
££ Each step in the algorithm should be clear and unambiguous.
££ Algorithms should be most effective among many different ways to solve
a problem.
££ An algorithm shouldn’t include computer code. Instead, the algorithm
should be written in such a way that it can be used in different
programming languages
Example

1.2.5. Building Blocks of Algorithm


So if we see how to build a good algorithm it has been proven that any algorithm
can be constructed from the basic building blocks. These blocks will give a complete
idea of the algorithm with the below details:
££ Incoming information : The values or data that are needed to find the
solution for a given problem (input)
££ Step numbers : Positions in algorithm. This we can mention explicitly
or can be understood implicitly
1. 6 Problem Solving and Python Programming

££ Control flow : It is an order in which individual statements, instructions


are evaluated
££ Statements: It tells which data variable to update and in what manner
££ Outgoing information: The values or data that give solution for the
given input (output)
Statements : Statement is a single action in a computer.

In a computer statements might include some of the following actions


1. input data - information given to the program
2. process data - perform operation on a given input
3. output data - processed result
State : Transition from one process to another process under specified condition
within a time is called state.
The state of an algorithm is defined as its condition regarding stored data. The
stored data in an algorithm are stored as variables or constants. The state shows its
current values or contents.
Because an algorithm is a precise list of precise steps, the order of computation
is always crucial to the functioning of the algorithm. Instructions are usually
assumed to be listed explicitly, and are described as starting “from the top” and
going “down to the bottom”, an idea that is described more formally by flow of control.
Control flow : The process of executing the individual statements in a given
order is called control flow.
In computer science, control flow (or flow of control) is the order in which
individual statements, instructions or function calls of an algorithm are executed
or evaluated.
For complex problems our goal is to divide the task into smaller and simpler
functions during algorithm design. So a set of related sequence of steps, part of
larger algorithm is known as functions.
The control flow can be executed in three ways
1. Sequence 3. Iteration
2. Selection
Sequence : All the instructions are executed one after another is called as
sequence execution.
Algorithmic Problem Solving 1.7

A sequence is a series of steps that occur one after the other, in the same order
every time. Consider a car starting off from a set of lights. Imagine the road in front
of the caris clear for many miles and the driver has no need to slow down or stop.
The car will start in first gear, then move to second, third, fourth and finally fifth. A
good driver (who doesn‘t have to slow down or stop) will move through the gears in
this sequence, without skipping gears.
Step 1: Start
Step 2: get a,b
Step 3: calculate c = a + b
Step 4: Display c
Step 5: Stop

Selection : A selection statement causes the program control to be transferred


to a specific part of the program based upon the condition.
If the conditional test is true, one part of the program will be executed, otherwise
it will execute the other part of the program.

Example: Write an algorithm to check whether he is eligible to vote?


Step 1: Start
Step 2: Get age
Step 3: if age >= 18 print “Eligible to vote”
Step 4: else print “Not eligible to vote”
Step 6: Stop
1. 8 Problem Solving and Python Programming

Iteration : In some programs, certain set of statements are executed again


and again based upon conditional test. i.e. executed more than one time. This type
of execution is called looping or iteration.
Iteration is sometimes called repetition, which means a set of steps which are
repeated over and over until some event occurs. Consider the driver at the red light,
waiting for it to turn green. She will check the lights and wait, check and wait. This
sequence will be repeated until the lights turn green.
Example : Write an algorithm to print all natural numbers up to n
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

Functions : Function is a sub program which consists of a block of code(set


of instructions) that performs a particular task.
For complex problems, the problem is divided into smaller and simpler tasks
during algorithm design.
Benefits of Using Functions
1. Reduction in line of code 4. Information hiding
2. code reuse 5. Easy to debug and test
3. Better readability 6. Improved maintainability
Example : Algorithm for addition of two numbers using function
Main function()
Step 1: Start
Step 2: Call the function add()
Step 3: Stop
sub function add()
Step 1: Function start
Step 2: Get a, b Values
Step 3: add c=a+b
Step 4: Print c
Step 5: Return
Algorithmic Problem Solving 1.9

1.2.6. Advantages of algorithm


££ It is a step wise description of a solution to a given problem, which makes
it easy to understand.
££ It uses a definite procedure to solve a problem.It is not dependent on
any programming language, so it is easy to understand for anyone even
without programming knowledge.
££ Every step in an algorithm has its own logical sequence so it is easy to
debug.
££ By using algorithms, the problem is broken down into smaller pieces
or steps hence, it is easier for programmers to convert it into an actual
program.
1.2.7. Disadvantages of algorithm
££ Algorithm is not a computer program, it is rather a concept of how the
program should be written.
££ It is time consuming, an algorithm needs to be developed first, which is
then converted into flowchart and then into a computer program
££ It is difficult to show branching and looping statements
1.2.8. Examples for algorithms
Example - 1
Find the largest among three numbers.
1. 10 Problem Solving and Python Programming

Start
Declare variables a,b and c.
Read variables a,b and c.
If a > b
If a > c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b > c
Display b is the largest number.
Else
Display c is the greatest number.
Stop

Example - 2
Find the roots of a Quadratic equation: ax^2 + bx + c = 0

Start
Declare variables a, b, c, D, x1, x2, rp and ip;
Calculate discriminant
D ← b2-4ac
If D ≥ 0
r1 ← (-b+√D)/2a
r2 ← (-b-√D)/2a
Display r1 and r2 as roots.
Else
Calculate real part and imaginary part
rp ← -b/2a
ip ← √(-D)/2a
Display rp+j(ip) and rp-j(ip) as roots
Stop

Example - 3
Find the factorial of a number.
Algorithmic Problem Solving 1.11

Start
Declare variables n, factorial and i.
Initialize variables
factorial ← 1
i←1
Read value of n
Repeat the steps until i = n
factorial ← factorial*i
i ← i+1
Display factorial
Stop

Example - 4
Check whether a number is prime or not
Start
Declare variables n, i, flag.
Initialize variables
flag ← 1
i←2
Read n from the user.
Repeat the steps until i=(n/2)
If remainder of n÷i equals 0
flag ← 0
Go to step 6
i ← i+1
If flag = 0
Display n is not prime
else
Display n is prime
Stop

1.3 Notations of Algorithm


Algorithms can be expressed in many different notations, including Step-
Form, pseudocode, flowchart and programming language. Natural language tends
1. 12 Problem Solving and Python Programming

to be verbose and ambiguous, and is rarely used. Pseudo code and flowcharts are
structured ways to express algorithms. Pseudo-code is something that represents
the algorithm through structured human language. Flowchart is something that
represents the algorithm graphically. Programming languages are intended for
expressing algorithms in a form that can be executed by a computer.
1.3.1 Algorithm as Step-Form
It is a step - by - step procedure for solving a task or problem. The steps must
be ordered, unambiguous and finite in number. It is English like representation of
logic which is used to solve the problem.
Some guidelines for writing Step-Form algorithm are as follows:
££ Keep in mind that algorithm is a step-by-step process.
££ Use begin or start to start the process.
££ Include variables and their usage.
££ If there are any loops, try to give sub number lists.
££ Try to give go back to step number if loop or condition fails.
££ Use jump statement to jump from one statement to another.
££ Try to avoid unwanted raw data in algorithm.
££ Define expressions.
££ Use break and stop to terminate the process.
For accomplishing a particular task, different algorithms can be written. The
different algorithms differ in their requirements of time and space. The programmer
selects the best suited algorithm for the given task to be solved.
Let as look at two simple algorithms to find the greatest among three numbers,
as follows:
Algorithm
Step 1: Start.
Step 2: Read the three numbers A,B,C.
Step 3: Compare A and B. If A is greater perform step 4 else perform step 5.
Step 4: Compare A and C. If A is greater, output -A is greater else output -C is
greater.
Step 5: Compare B and C. If B is greater, output -B is greatest else output -C
is greatest.
Step 6: Stop.
Algorithmic Problem Solving 1.13

1.3.2 Pseudocode
What is pseudocode?
“Pseudo” means initiation or false.
“Code” means the set of statements or instructions written in a programming
language.
Pseudocode is also called “Program Design Language [PDL]”.
Pseudocode is an informal way of programming description that does not
require any strict programming language syntax. It is used for creating an outline or
a rough draft of a program. Pseudocode summarizes a program’s flow, but excludes
underlying details. System designers write pseudocode to ensure that programmers
understand a software project’s requirements and align code accordingly.
1.3.2.1. How can one describe a pseudocode?
Pseudocode is not an actual programming language. So it cannot be compiled
into an executable program. It is composed of simple English language syntaxes to
write code for programs before it is actually converted into a specific programming
language that cannot be understood by the computer. This is done to identify top
level flow errors, and understand the programming data flows that the final program
is going to use. This helps to save time during actual programming as conceptual
errors have been already corrected .
Firstly, program description and functionality is gathered and then pseudocode
is used to create statements to achieve the required results for a program. Detailed
pseudocode is inspected and verified by the designer’s team or programmers to match
design specifications. Catching errors or wrong program flow at the pseudocode
stage is beneficial for development as it is less costly than catching them later. Once
the pseudocode is accepted by the team, it is rewritten using the vocabulary and
syntax of a programming language. The purpose of using pseudocode is an efficient
key principle of an algorithm. It is used in planning an algorithm with sketching out
the structure of the program before the actual coding takes place.
1.3.2.2. Rules for writing Pseudocode
1. Write one statement per line
2. Capitalize initial keywords (READ, WRITE, IF, WHILE, UNTIL).
3. Indent to show hierarchy.
1. 14 Problem Solving and Python Programming

4. End multi line structure.


5. Keep statements language.
1.3.2.3. Solving Sample Pseudocode
Example - 1
Pseudocode which get grades and calculate the average with help of
counter
Initialize total to zero
Initialize counter to zero
Input the first grade
while the user has not as yet entered the sentinel
add this grade into the running total
add one to the grade counter
input the next grade (possibly the sentinel)
if the counter is not equal to zero
set the average to the total divided by the counter
print the average
else
print ‘no grades were entered’

Example - 2
Pseudocode which will accept two numbers from user and calculate
their sum and display the result.
Begin
Number s1,s2,sum
output(“Input number1: ”)
Input s1
output(“Input number2: ”)
Input s2
sum=s1+s2
Output sum
End
Algorithmic Problem Solving 1.15

Example - 3
Write a pseudocode to calculate and print the class average.
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Set the class average to the total divided by ten
Print the class average.

Example - 4
Pseudocode which will accept input from the user and calculate the
area and perimeter of a rectangle and execute the output on the screen.
Begin
Number b1,b2,area,perimeter
Input b1
Input b2
area =b1*b2
perimeter=2*(b1+b2)
Output area
Output perimeter
End

Example - 5
What will be the output of the following pseudocode ?
Integer i
Set i = 3
do
print i + 3
i=i-1
while(i not equals 0)
end while
1. 16 Problem Solving and Python Programming
Example - 6
Write a pseudocode that accepts two numbers from the user (dividend
and divisor), testing to make sure that the divisor number is not zero, and
displaying their quotient.
Declare variables: dividend, divisor, quotient
Prompt user to enter dividend and divisor
Get dividend and divisor
IF divisor is equal to zero, THEN
DO
Display error message, “divisor must be non-zero”
Prompt user to enter divisor
Get divisor
WHILE divisor is equal to zero
ENDIF
Display dividend and divisor
Calculate quotient as dividend/divisor
Display quotient

Example - 7
Pseudocode which will determine a student’s final grade and indicate
whether he is getting pass mark or fail mark. The final grade is calculated
as the average of three marks.
Input a set of 3 marks
Calculate their average by summing and dividing by 3
if average is below 50
Print “FAIL”
else
Print “PASS”

Example - 8
Write a pseudocode that accepts ‘n’ value of input from the user and
calculate the sum of n numbers.
Algorithmic Problem Solving 1.17

Initialize the value of sum = 0


DISPLAY “Input value of n”
ACCEPT n
FOR(i = 1, i < n, i++)
Input a value
sum=sum + value
END FOR
Output sum

1.3.2.4. Advantages of pseudocode


1. It can be easily modified as compared to flowchart.
2. Its implementation is very useful in structured design elements.
3. It can be written easily.
4. It can be read and understood easily.
Advantages of pseudocode over flowchart
Converting a pseudocode to a programming language is very easy compared
with converting a flowchart to a programming language.
1.3.2.5. Disadvantage of pseudocode
1. It is not visual.
2. We do not get a picture of the design.
3. There is no standardized style or format.
Disadvantages of pseudocode over flowchart
For a beginner, it is more difficult to follow the logic or write pseudocode as
compared to flowchart.
1.3.3. Flow chart
A flowchart is a graphical representation of an algorithm. These flowcharts
play a vital role in the programming and are quite helpful in understanding the logic
of complicated problems. Flowcharts were introduced by Frank Gilberth in 1921,
and they were called “Process Flow Charts’’ at the beginning.
A flowchart is a diagram made up of boxes, diamonds and other shapes,
connected by arrows - each shape represents a step in the process, and the arrows
show the order in which they occur. Once the flowchart is drawn, it becomes easy to
write the program in any high level language.
1. 18 Problem Solving and Python Programming

Elements that may be included in a flowchart are a sequence of actions,


materials or services entering or leaving the process (inputs and outputs), decisions
that must be made, people who become involved, time involved at each step, and/or
process measurements.
When to use a flowchart?
1. To develop understanding of how a process is done
2. To study a process for improvement
3. To communicate to others how a process is done
4. When better communication is needed between people involved with the
same process
5. To document a process
6. When planning a project
Types of Flowcharts
There are many different types of flowcharts. There are flowcharts for analysts,
designers, managers or programmers for their understanding.
££ Document flowcharts have the purpose of showing existing controls over
a document-flow through the components of the system. This chart is
read from left to right and explain the flow of documents through various
business units.
££ Data flowcharts have the purpose of showing the controls governing data
flows in the system. Data flowcharts are used primarily to show how data
is transmitted through the system rather than the control flow. System
flowcharts show the controls located at the physical or resource level.
££ System flowcharts show the flow of data through the major components
of the system such as data entry, programs, storage media, processors
and communication networks. Program flowcharts shows the controls
placed internally to the program within a system.
££ Program flowchart is a gift to programmers as it makes programming
task very easy and systematic
Flowcharting Symbols
££ Process / Operation Symbols
££ Branching and Control of Flow Symbols
££ Input and Output Symbols
Algorithmic Problem Solving 1.19

££ File and Information Storage Symbols


££ Data Processing Symbols

Process / Operation Symbols in Flowchart


Symbol Name Description

Show a Process or action step. This is the


Process
most common symbol used in flowchart.

A Predefined Process symbol is a marker


Predefined
for another process orseries of process. This
Process
shape commonly depicts sub-processes or
(Subroutine)
subroutines.

It is used when the process flow step is an


Alternate Process
alternate to the normal process step.

The Delay flowchaart symbol depicts any


Delay
waiting period that is part of a process.

Any process step that is a Preparation


Preparation process flow step, such as a set-up
operation.

Manual Manual Operations flow chart shapes show


Operation which process steps are not automated.

Branching and Control of Flow Symbols in Flowchart


Symbol Name Description
Flow Line
Flow line connectors show the direction
(Arrow,
that the process flows.
Connector)
Terminator
Terminators show the start and stop points
(Terminal Point,
in a process.
Oval)
1. 20 Problem Solving and Python Programming

Indicates a question or branch in the


Decision
process flow.

Connector It is used to show a jump from one point in


(Inspection) the process flow to another.

Off-Page Off-Page Connector shows continuation of a


Connector process flow chart onto another page.

This symbol shows the merging of multiple


Merge (Storage)
processes or information into one.

Extract This symbol shows when a process splits


(Measurement) into parallel paths.

The logical Or symbol shows when a


Or process diverges - usually for more than
two branches.
The logical Summing Junction flow chart
Summing
shape is shows when multiple branches
Junction
converge into a single process.

Input and Output Symbols in Flowchart


Symbol Name Description
The Data flowchart shape indicates inputs
Data (I/O)
to and outputs from a process.
Document flowchart symbol is for a process
Document
step that produces a document.
Multi-Document flowchart symbol is for
Multi-Document a process step that produces a multiple
documents.
Indicates a process step where information
Display
is displayed.
Algorithmic Problem Solving 1.21

Manual Input flowchart gets the input


Manual Input
manually into a system.
This symbol is companion to the punched
Card tape flowchart shapes. This shape is seldom
used.
Punched Tape symbol is used for input into
Punched Tape
old computers and CNC machines.

File and Information Storage Symbols in Flowchart


Symbol Name Description

A general Data Storage flowchart shape


Stored Data
used for any process step that stores data.

The most universally recognizable symbol


Magnetic Disk
for a data storage location, this flowchart
Database
shape depicts a database.
Direct Access
Direct Access Storage is a like Hard Drive.
Storage

It is used in programming flowcharts to


Internal Storage
store information in memory.

Sequential
Although it looks like a ‘Q’, the symbol is
Access Storage
supposed to look like a reel of tape.
(Magnetic Tape)

Data Processing Symbols in Flowchart


Symbol Name Description
The Collate flowchart shape indicates a
process step that requires organizing data
Collate
or information according to a standard
format.
1. 22 Problem Solving and Python Programming

Indicates the sorting of data, information,


Sort
materials into some pre-defined order.

Even though many symbols are available, the most commonly used
symbols in the flowchart are:

Advantages of flowcharts
1. Communication - Flowcharts are better way of communicating the logic
of a system.
2. Effective analysis - With the help of flowchart, problem can be analysed
in more effective way.
3. Proper documentation - Flowcharts are used for good program
documentation, which is needed for various purposes.
4. Efficient Coding - Flowcharts act as a guide or blueprint during the
systems analysis and program development phase.
5. Proper Debugging - Flowchart helps in debugging process.
6. Efficient Program Maintenance - The maintenance of running program
becomes easy with the help of flowchart.
Advantages of flowchart over pseudo code
££ Flowcharts provide an easy method of communication about the logic
and offer a good starting point for the project because they are easier to
create than pseudocode in the beginning stages.
££ Pseudocode provides a beneficial bridge to the project code because it
closely follows the logic that the code will.
Algorithmic Problem Solving 1.23

Disadvantages of a flowcharts
££ Complex logic Sometimes, the program logic is quite complicated. In
that case, flowchart becomes complex and clumsy.
££ Alterations and Modifications - If alterations are required the flowchart
may require re-drawing completely.
££ Reproduction- As the flowchart symbols cannot be typed, reproduction of
flowchart becomes a problem.
Disadvantages of flowchart over pseudo code
Forming a flowchart is a time consuming work and the branching and looping
statements are difficult to show here while in pseudo code it was easy to show the
branches and loops and are clearly understandable.
Simple Examples
Example - 1
Write an algorithm, pseudocode and flowchart to find the sum of two numbers.
Algorithm

Start
Enter the input value A and B
Find Sum = A + B
Display the value of Sum
Stop

Pseudocode
ENTER the input value A and B
Find Sum
Sum = A + B
PRINT Sum
STOP
1. 24 Problem Solving and Python Programming

Flow chart

Example - 2
Write an algorithm, pseudocode and flowchart to find the greatest of
three numbers.
Algorithm
Start
Get A, B, C
if(A>B) goto (A>C) else goto (B>C)
If(A>C) print A else print C
If(B>C) print B else print C
Stop

Pseudocode
BEGIN
READ a, b, c
IF (a>b) THEN
IF(a>c) THEN
DISPLAY a is greater
ELSE
DISPLAY c is greater
END IF
Algorithmic Problem Solving 1.25

ELSE
IF(b>c) THEN
DISPLAY b is greater
ELSE
DISPLAY c is greater
END IF
END IF
END

Flowchart

Example - 3
Write an algorithm,pseudocode and draw a flowchart that will read
the two sides of a rectangle and calculate its area.
Algorithm
Start
Input Length,Breadth
Area = Length*Breadth
Print Area
Stop
1. 26 Problem Solving and Python Programming

Pseudocode
Read Length,Breadth
CALCULATE Area = Width*Length
Print Area

Flowchart

Example - 4
Write an algorithm, pseudocode and flowchart to swap two variables
without using temporary variables.
Algorithm
Start the program
Read the value of A,B
To swap without using another value is
A←A+B
B←A-B
A←A-B
Print the values of A and B
Stop
Algorithmic Problem Solving 1.27

Pseudocode
SET initial A,B
READ the value A,B
To interchange the value use
A=A+B
B=A-B
A=A-B
WRITE the values of c,d

Flowchart

Example - 5
Write an algorithm, pseudocode and flowchart to generate the
fibonacci series.
Algorithm
Start
Assign a ←0,b←1,sum←0
READ n
Input i←2
IF(i<=n)
Sum =a+b
a=b
b=sum,i++
Print sum
Go to IF condition
ELSE
Stop
1. 28 Problem Solving and Python Programming

Pseudocode
Start
Declare variable a,b,c,n,i
Initialize variable a=1, b=1, i=2
Read n from user
Print a and b
Repeat until i&lt;n
c=a+b
print c
a=b, b=c
i=i+1
Stop

Flowchart
Algorithmic Problem Solving 1.29

Example - 6
Write an algorithm, pseudocode and flowchart for calculating area and
circumference of a circle.
Algorithm
Start
get r value
Calculate A=3.14*r*r
Calculate C=2.3.14*r
Display A,C
Stop

Pseudocode
BEGIN
READ r
CALCULATE A and C
A=3.14*r*r
C=2*3.14*r
DISPLAY A
END

Flowchart
1. 30 Problem Solving and Python Programming

Example - 7
Write an algorithm, pseudocode and flowchart for calculating simple
interest.
Algorithm
Start
get p,n,r value
Calculate
SI = (p*n*r)/100
Display S
Stop

Pseudocode
BEGIN
READ P, n, r
CALCULATE S
SI=(p*n*r)/100
DISPLAY SI
END

Flowchart
Algorithmic Problem Solving 1.31

Example - 8
Write an algorithm, pseudocode and flowchart to check leap year or
not.
Algorithm
Start
get y
if(y%4==0) print leap year
else print not leap year
Stop

Pseudocode
BEGIN
READ y
IF (y%4==0) THEN
DISPLAY leap year
ELSE
DISPLAY not leap year
END IF
END

Flowchart
1. 32 Problem Solving and Python Programming

1.3.4 Programming Language


Programming language, any of various languages for expressing a set
of detailed instructions for a digital computer. Such instructions can be executed
directly when they are in the computer manufacturer-specific numerical form
known as machine language, after a simple substitution process when expressed
in a corresponding assembly language, or after translation from some “higher-level”
language.
Although there are many computer languages, relatively few are widely used.
A programming language is a notation for writing programs, which are specifications
of a computation or algorithm.
A programming language may also describe computation on some, possibly
abstract, machine. It is generally accepted that a complete specification for a
programming language includes a description, possibly idealized, of a machine or
processor for that language.
Quality of programming language
££ The following are the qualities of a programming language;
££ Languages are not designed to provide a means for having a two-way
dialog with a computer.
££ It is a set of instructions specified by the human on what the computer
should do.
££ Provides a way for humans to communicate to computers
££ It always follows grammar; hence there is no ambiguity
££ A system will be able to infer the computer language
Characteristics of a programming Language
££ A programming language must be simple, easy to learn and use, have
good readability, and be human recognizable.
££ Abstraction is a must-have Characteristics for a programming language
in which the ability to define the complex structure and then its degree
of usability comes.
££ A portable programming language is always preferred.
££ Programming language’s efficiency must be high so that it can be easily
converted into a machine code and executed consumes little space in
memory.
Algorithmic Problem Solving 1.33

££ A programming language should be well structured and documented so


that it is suitable for application development.
££ Necessary tools for the development, debugging, testing, maintenance of
a program must be provided by a programming language.
££ A programming language should provide a single environment known as
Integrated Development Environment(IDE).
££ A programming language must be consistent in terms of syntax and
semantics.
1.3.5 ALGORITHMIC PROBLEM SOLVING
Algorithmic problem solving is solving problems that require the formulation
of an algorithm for the solution.
Algorithms and algorithmic problem solving occupy a central place in computer
science and engineering. Algorithmic problem solving is a great starting point for
students beginning their computer science and engineering studies. While students
may have been exposed to problem solving techniques during their middle and high
school, they would gain a new perspective by focusing on algorithmic aspects.
Algorithmic problem solving can be approached starting with an informal notion
of an algorithm. Students do not need any experience with computer programming
to develop their algorithmic thinking skills. Simple English language constructions
and mathematical notation are sufficient to express sophisticated algorithms.
1. 34 Problem Solving and Python Programming

Steps for algorithmic problem solving


Understanding the Problem
It is the process of finding the input of the problem that the algorithm solves.It
is very important to specify exactly the set of inputs the algorithm needs to handle.A
correct algorithm is not one that works most of the time, but one that works correctly
for all legitimate inputs.
Ascertaining the Capabilities of the Computational Device:
If the instructions are executed one after another, it is called sequential
algorithm.If the instructions are executed concurrently, it is called parallel algorithm.
Choosing between Exact and Approximate Problem Solving
The next principal decision is to choose between solving the problem exactly
or solving it approximately.Based on this, the algorithms are classified as exact
algorithm and approximation algorithm.
Deciding a data structure
Data structure plays a vital role in designing and analysis 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 (or “strategy” or “paradigm”) 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 of utmost
importance for the following reasons.
First, they provide guidance for designing algorithms for new problems,
Second, algorithms are the cornerstone of computer science
Methods of Specifying an Algorithm
Pseudocode is a mixture of a natural language and programming language-
like constructs. Pseudocode is usually more precise than natural language, and its
usage often yields more succinct algorithm descriptions.
In the earlier days of computing, the dominant vehicle for specifying algorithms
was a flowchart, a method of expressing an algorithm by a collection of connected
geometric shapes containing descriptions of the algorithm’s steps.
Algorithmic Problem Solving 1.35

Programming language can be fed into an electronic computer directly. Instead,


it needs to be converted into a computer program written in a particular computer
language. We can look at such a program as yet another way of specifying the
algorithm, although it is preferable to consider it as the algorithm’s implementation.
Proving an Algorithm’s Correctness
Once an algorithm has been specified, you have to prove its correctness. That
is, you have to prove that the algorithm yields a required result for every legitimate
input in a finite amount of time.
A common technique for proving correctness is to use mathematical induction
because an algorithm’s iterations provide a natural sequence of steps needed for
such proofs.
It might be worth mentioning that although tracing the algorithm’s performance
for a few specific inputs can be a very worthwhile activity, it cannot prove the
algorithm’s correctness conclusively. But in order to show that an algorithm is
incorrect, you need just one instance of its input for which the algorithm fails.
Analysing 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
Most algorithms are destined to be ultimately implemented as computer
programs. Programming an algorithm presents both a peril and an opportunity.A
working program provides an additional opportunity in allowing an empirical
analysis of the underlying algorithm. Such an analysis is based on timing the
program on several inputs and then analysing the results obtained
Simple strategies for developing Algorithm
Developing an algorithm is a very important step in problem-solving. There
are different types of strategies that could be used to develop an algorithm to solve
a problem. Two of the most frequently used strategies are:
1. 36 Problem Solving and Python Programming

££ Iteration ££ Recursion
Iteration
Iteration is a process wherein a set of instructions or structures are repeated in
a sequence, a specified number of times or until a condition is met. Once a problem
is clear then the logic of the solution could be implemented using an iteration where
it could run multiple times to achieve a specific outcome
1. for loop
2. while loop
Syntax for For
FOR( start-value to end-value) DO
Statement
...
ENDFOR

Example: Print n natural numbers


BEGIN
GET n
INITIALIZE i=1
FOR (i<=n) DO
PRINT i
i=i+1
ENDFOR
END

Syntax for While


WHILE (condition) DO
Statement
...
ENDWHILE

Example : Print n natural numbers


Algorithmic Problem Solving 1.37

BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END

1.4 Recursion
Recursion is a technique in which a function calls itself repeatedly until a
concluding situation happen. A function which utilizes this technique is called a
recursive function.
A recursive algorithm is an algorithm which calls itself with “smaller (or
simpler)” input values, and which obtains the result for the current input by applying
simple operations to the returned value for the smaller (or simpler) input. More
generally if a problem can be solved utilizing solutions to smaller versions of the
same problem, and the smaller versions reduce to easily solvable cases, then one can
use a recursive algorithm to solve that problem.
1. 38 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
BIN

Sub function factorial(n)


IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)
Algorithmic Problem Solving 1.39

1.5 Some More Illustrative Examples


1.5.1 Find minimum in a list
Consider the following requirement specification:
A user has a list of numbers and wishes to find the minimum value in the list.
An Algorithm is required which will allow the user to enter the numbers, and which
will calculate the minimum value that are input. The user is quite happy to enter a
count of the numbers in the list before entering the numbers.
Finding the minimum value in a list of items isn‘t difficult. Take the first
element and compare its value against the values of all other elements. Once we
find a smaller element we continue the comparisons with its value. Finally we find
the minimum.

Figure 1: Steps to Find Minimum Element 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]
1. 40 Problem Solving and Python Programming

Step 6: Initialize i=1


Step 7: If i<n, then go to step 8 else goto step 10
Step 8: If a[i]<min, then goto
step 8.1,8.2 else goto 8.2
Step 8.1: min=a[i]
Step 8.2: i=i+1 goto 7
Step 9: Print min
Step 10: Stop

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]
INCREMENT i
ELSE
INCREMENT i
END IF-ELSE
END FOR
PRINT min
END
Algorithmic Problem Solving 1.41

Flowchart

1.5.2 Insert a card in a list of sorted cards


Insert a Card in a List of Sorted Cards – is same as inserting an element into
a sorted array.
We start from the high end of the array and check to see if that’s where we
want to insert the data. If so, fine. If not, we move the preceding element up one and
then check to see if we want to insert x in the - hole left behind. We repeat this step
as necessary.
Thus the search for the place to insert x and the shifting of the higher elements
of the array are accomplished together.
1. 42 Problem Solving and Python Programming

Figure 1.2: Steps to 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 lse goto st 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
Algorithmic Problem Solving 1.43

FOR i=0 to n, then


PRINT a[i]
INCREMENT i
END FOR
END

Flowchart
1. 44 Problem Solving and Python Programming

1.5.3 Guess an integer in a range


Let’s play a little game to give an idea of how different algorithms for the same
problem can have wildly different efficiencies. The computer is going to randomly
select an integer from 1 to N and ask you to guess it. The computer will tell you if
each guess is too high or too low. We have to guess the number by making guesses
until you find the number that the computer chose. Once found the number, think
about what technique used, when deciding what number to guess next?
Maybe you guessed 1, then 2, then 3, then 4, and so on, until you guessed
the right number. We call this approach linear search, because you guess all the
numbers as if they were lined up in a row. It would work. But what is the highest
number of guesses you could need? If the computer selects N, you would need N
guesses. Then again, you could be really lucky, which would be when the computer
selects 1 and you get the number on your first guess. How about on average? If the
computer is equally likely to select any number from 1 to N, then on average you’ll
need N/2 guesses.
But you could do something more efficient than just guessing 1, 2, 3, 4, …,
right? Since the computer tells you whether a guess is too low, too high, or correct,
you can start off by guessing N/2. If the number that the computer selected is less
than N/2, then because you know that N/2 is too high, you can eliminate all the
numbers from N/2 to N from further consideration. If the number selected by the
computer is greater than N/2, then you can eliminate 1 through N/2. Either way,
you can eliminate about half the numbers. On your next guess, eliminate half of the
remaining numbers. Keep going, always eliminating half of the remaining numbers.
We call this halving approach binary search, and no matter which number from
1 to N the computer has selected, you should be able to find the number in at most
log2N+1 guesses with this technique. The following table shows the maximum
number of guesses for linear search and binary search for a few number sizes:
Algorithmic Problem Solving 1.45

Highest Max Linear Max Binary Search


Number Search Guesses Guesses

10 10 4

100 100 7

1000 1000 10

10,000 10,000 14

1,00,000 1,00,000 17

1,000,000 1,000,000 20

Algorithm
Step 1: Start
Step 2: Declare hidden, guess
Step 3: Compute hidden= Choose a random value in a range
Step 4: Read guess
Step 5: If guess=hidden, then Print Guess is hit
Step 6: Else Print Guess not hit,Print hidden
Step 6: Stop

Pseudocode
BEGIN
COMPUTE hidden=random value in range
READ guess
IF guess=hidden, then
PRINT Guess is hit
ELSE
PRINT Guess not hit
PRINT hidden
END IF-ELSE
END
1. 46 Problem Solving and Python Programming

Flowchart

1.5.4 Tower of Hanoi


Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs)
and more than one rings is as depicted in Figure. These rings are of different sizes
and stacked upon in an ascending order, i.e. the smaller one sits over the larger one.

Figure 1.3 Tower of Hanoi


The mission is to move all the disks to some another tower without violating
the sequence of arrangement. A few rules to be followed for Tower of Hanoi are:
Algorithmic Problem Solving 1.47

Rules
££ Only one disk can be moved among the towers at any given time.
££ Only the “top” disk can be removed.
££ No large disk can sit over a small disk.

Figure 1.4 Step by Step Moves in ESolving Three Disk Tower of Hanoi Problem
Algorithm
To write an algorithm for Tower of Hanoi, first we need to learn how to solve
this problem with lesser amount of disks, say → 1 or 2. We mark three towers with
name, source, destination and aux (only to help moving the disks). If we have only
one disk, then it can easily be moved from source to destination tower.
If we have 2 disks
££ First, we move the smaller (top) disk to aux tower.
££ Then, we move the larger (bottom) disk to destination tower.
££ And finally, we move the smaller disk from aux to destination tower.
So now, we are in a position to design an algorithm for Tower of Hanoi with
more than two disks. We divide the stack of disks in two parts. The largest disk (nth
disk) is in one part and all other (n-1) disks are in the second part.
1. 48 Problem Solving and Python Programming

Our ultimate aim is to move disk n from source to destination and then put all
other (n-1) disks onto it. We can imagine to apply the same in a recursive way for all
given set of disks.
The steps to follow are
Step 1 - Move n-1 disks from source to aux
Step 2 - Move nth disk from source to dest
Step 3 - Move n-1 disks from aux to dest

A recursive Step based algorithm for Tower of Hanoi can be driven as follows:
Algorithm
Step 1: Start
Step 2: Read n
Step 3: Calculate move=pow(2,n)-1
Step 4: Function call T(n,Beg,Aux,End) recursively until n=0
Step 4.1: If n=0, then goto
Step 5 :else goto step 4.2
Step 4.2: T(n-1,Beg,End,Aux) T(1,Beg,Aux,End) , Move disk from source to
destination T(n-1,Aux,Beg,End)
Step 5: Stop

Pseudocode
BEGIN
READ n
CALCULATE move=pow(2,n)-1
FUNCTION T(n,Beg,Aux,End) Recursively until n=0
PROCEDURE
IF n=0 then,
No disk to move
Else
T(n-1,Beg,End,Aux)
T(1,Beg,Aux,End), move isk from source to destination
T(n-1,Aux,Beg,En )
END PROCEDURE
END
Algorithmic Problem Solving 1.49

Flowchart

Two Marks Questions With Answers


1. Define Computer.
A computer is an electronic data processing device, which accepts and stores
data input, processes the data input, and generates the output in a required
format.
2. Define algorithm.
The sequence of steps to be performed in order to solve a problem by the
computer is known as an algorithm.
Programs = Algorithms + Data
3. What are the steps involved in algorithm development process?
The algorithm development process consists of five major steps.
Step 1: Obtain a description of the problem.
Step 2: Analyze the problem.
Step 3: Develop a high-level algorithm.
Step 4: Refine the algorithm by adding more detail.
Step 5: Review the algorithm.
4. State some of the properties of an algorithm.
££ Finiteness ££ Definiteness
1. 50 Problem Solving and Python Programming

££ Effectiveness ££ Feasibility
££ Input ££ Generality.
££ Output
5. Describe different notations in algorithm and classify each.
Algorithms can be expressed in many different notations, including Natural
Language, pseudo code, flowcharts and programming languages.
Natural language tends to be verbose and ambiguous, and is rarely used.
Pseudocode and flowcharts are structured ways to express algorithms.
Programming languages are intended for expressing algorithms in a form that
can be executed by a computer.
6. Define Pseudocode.
Pseudocode is an informal language used by programmers to develop algorithms.
Pseudocode is a “text-based” detail design tool.
Example
Enter value
If value greater than 10
Say “your number is greater than 10”
If value less than 10
Say “your number is lesser than 10”

7. Define some of the rules to be followed on Pseudocode.


Rules to follow:
££ Only one statement per line
££ Capitalized initial keyword
££ Indent to show hierarchy.
££ End multi-line structures.
££ Keep statement language independent.
8. Define flowchart.
A flowchart is a graphical representation of an algorithm. A flowchart is a
diagram made up of boxes, diamonds and other shapes, connected by arrows
each shape represents a step in the process, and the arrows show the order in
which they occur.
Algorithmic Problem Solving 1.51

9. What are the different types of flowcharts?


££ Document flowcharts ££ System flowcharts
££ Data flowcharts ££ Program flowchart
10. What are the symbols used in flowcharting type?
££ Process / Operation Symbols
££ Branching and Control of Flow Symbols
££ Input and Output Symbols
££ File and Information Storage Symbols
££ Data Processing Symbols
11. List some guidelines for drawing flowchart.
££ The flowchart should be clear, neat and easy to follow.
££ The usual direction of the flow of a process is from left to right or top to
bottom.
££ Only one flow line should come out from a process symbol
££ All necessary requirements should be listed out in logical order for
drawing a proper flowchart.
12. Explain some of the qualities of Programming Language?
££ Languages are not designed to provide a means for having a two-way
dialog with a computer.
££ It is a set of instructions specified by the human on what the computer
should do.
££ Provides a way for humans to communicate to computers.
££ It always follows grammar; hence there is no ambiguity.
££ A system will be able to infer the computer language.
13. What is the difference between the algorithm and the program?
A program is the implementation of an algorithm to be run on a specific
computer and operating system. An algorithm is more abstract.
14. Give the Pseudocode to check the biggest of 2 numbers.
if (A>B)
Print “A is greater”
else
Print “B is greater”
1. 52 Problem Solving and Python Programming

15. State the differences between Iteration and Recursion.


Iteration Recursion
Iteration explicitly uses a repetition Recursion achieves repetition
Recursion achieves repetition through repeated function calls.
through structure.
Iteration keeps modifying the Recursion keeps producing simple
counter until the loop condition fails. versions of the original problem until
the base case is attained.
It reduces the processor’s operating It increases the processor’s operating
time. time
Iteration normally occurs within the Recursion causes another copy of
loop, hence no need of extra memory. the function; hence considerable
memory space is occupied

Review Questions
1. Define an algorithm.
2. List the advantages of using an algorithm.
3. Write an algorithm to compute the factorial of a given number.
4. What are the characteristics of an algorithm?
5. Define pseudocode.
6. Write two characteristics of pseudocode.
7. List out the advantages and disadvantages of pseudocode.
8. Write the rules for writing a pseudocode.
9. Describe (i) Qualities of a good algorithm. (ii) Representation of an algorithm
10. Define flowchart.
11. What are the various symbols used in flowcharting? Give their pictor
representation.
12. Draw a flowchart to find the biggest among two numbers.
13. Draw a flowchart to find the sum of first N Natural numbers. 14. Draw a
flowchart to find the maximum of three integer numbers.
14. What are the basic logic structures used in writing structured programs?
Algorithmic Problem Solving 1.53

15. Write an algorithm to compute the factorial of a number.


16. Write a pseudocode to add two matrices. 18. Draw a flowchart to find the
highest marks in a set of n marks.
17. Explain the symbols used in flowchart and the basic design structures flowchart.
18. Explain the need for an algorithm and highlight its advantages

You might also like