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

Python - Unit 1-New-Final

An algorithm is a step-by-step procedure to solve a problem using well-defined instructions. It must have inputs, outputs, definiteness, effectiveness, and terminate after a finite number of steps. Algorithms are built using statements, sequences, selections, iterations, and functions. Common building blocks include input/output, assignment, and control statements that allow conditional branching and loops.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views

Python - Unit 1-New-Final

An algorithm is a step-by-step procedure to solve a problem using well-defined instructions. It must have inputs, outputs, definiteness, effectiveness, and terminate after a finite number of steps. Algorithms are built using statements, sequences, selections, iterations, and functions. Common building blocks include input/output, assignment, and control statements that allow conditional branching and loops.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 45

UNIT - 1

ALGORITHMIC PROBLEM SOLVING

1.1. ALGORITHM
An algorithm is defined as a step by step procedure for solving a problem. It is a ordered
set of rules to solve a problem. An algorithm is a representation of a solution to a problem. It 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.

Algorithm
Input A step by step method Output
for solving a problem

1.1.1. Properties of Algorithms


Every algorithm must have five essential properties:
(1) Inputs specified: An algorithm must have zero or more inputs, We must specify the
type of the data, the amount of data, and the form that the data will take.
(2) Outputs specified: An algorithm has one or more outputs, which have a specified
relation to the inputs.
(3) Definiteness: Every detail of each step must be clearly specified.
(4) Effectiveness: All operations to be performed must be sufficiently basic that they can
be done exactly and in finite length.
(5) Finiteness: An algorithm must always terminate after a finite number of steps.

1.1.2. Characteristics of Algorithm Finiteness


Algorithm must terminate after a finite number of steps and further each steps must be
executable in finite amount of time.

Definiteness
Instruction must be clear, user defined & Precise. There should not be any ambiguity.

Input
An algorithm has zero or more, but only finite number of inputs, zero inputs. Eg: ASCII
character of 0-225.
1.2 Problem Solving and Python Programming

Output
An algorithm has one or more output.

Effectiveness
An algorithm should be effective that means each of the operation to be preformed in
algorithm should be computer programming language independent.

Uniqueness
Result or each steps are uniquely defined and only depend on the input and result of the
preceding steps.

Generality
Algorithm should apply to set of input, rather than single input.

Feasibility
It must be possible to perform each instructions.

1.1.3. Method for Developing an Algorithm


(1) Define the problem: State the problem to be solved in clear and concise manner.
(2) List the inputs and outputs
(3) Describe the steps needed to convert input to output
(4) Test the algorithm: Choose input data and verify that the algorithm works.

1.2 .BUILDING BLOCKS OF ALGORITHM


1.2.1. Statements/Instructions
The statements/instructions enable us to manipulate the data items. The instructions in
Python or indeed in any high-level language are designed as components for algorithmic problem
solving rather than as one-to-one translations of the underlying machine language instruction set
of the computer. Thus, they allow the programmer to work at a higher level of abstraction.

Input/output statements make up one type of statement. An input statement collects a


specific value from the user for a variable within the program. An output statement writes a
message or the value of a program variable to the user’s screen. Assignment statement, which
assigns a value to a program variable. This is similar to what an input statement does, except that
the value is not collected directly from the user, but is computed by the program. Control
statements, the third type of statement, affect the order in which instructions are executed. A
program executes one instruction or program statement at a time. Without directions to the
contrary, instructions are executed sequentially from first to last in the program. Control
statements direct the flow of control.

1.2.2. State
Stored data are regarded as part of the internal state of the entity performing the algorithm.
The state is stored in one or more data structures. For such computational process, the algorithm
must
Algorithmic Problem Solving 1.3

be rigorously defined and it must be specified in the way that it applies in all possible
circumstances. Data Structure specify the arrangement of data in a particular format.

1.2.3. Control Flow


Control flow (or flow of control) is the order in which individual statements, instructions
or function calls of a program are executed or evaluated. At the level of machine language or
assembly language, control flow instructions usually work by altering the program counter. For
some central processing units (CPUs), control flow instructions available are conditional or
unconditional branch instructions, also termed jumps.

Kinds of control flow statements


• conditional branch
• loop - the same as conditional branch
• subroutines, co-routines, and continuations
• unconditional halt

1.2.4. Function
A function is a sequence of instructions that perform a task, bundled as a unit. Functions
can accept input arguments and produce output values. A function in Python is defined by using
the keyword def, after which the name of the function follows, terminated by a pair of braces
(which may or may not contain input parameters) and, finally, a colon (:) signals the end of the
function definition line. Immediately afterwards, indented by four spaces, we find the body of the
function, which is the set of instructions that the function will execute when called.

Reason for using Function


• Hide the implementation details from their users.
• Reduce code duplication in a program.
• Help in splitting a complex task into smaller blocks, each of which becomes a function.
• Improve traceability.
• Improve readability.

1.2.5. Basic building blocks of Algorithm


An algorithm is a sequence of simple steps that can be followed to solve a problem. These
steps must be organized in a logical and clear manner.
Algorithm can be designed using the below basic building blocks.

Building Block Common name Description


Statements Declaration An effective procedure for solving a problem in a
finite number of steps.
Sequence Action Instructions are executed in sequential order (from
first to last).
Selection Decision or A Decision is making a choice among several
Branching actions (condition checking).
Iteration Repetition or Loop A Loop is one or more instructions that the
computer performs repeatedly.
Functions Methods To divide the task into smaller and simpler tasks.
1.4 Problem Solving and Python Programming

Statements
 The algorithm consists of finite number of statements.

 The Statements must be in an ordered form.

 The time taken to execute all the statements of the algorithm should be finite and within a
reasonable limit.

Sequence Structure
This is the most common form of control structure. Each statement in the program is
executed one after another in the given order. The flow of sequence structure is shown in
Figure.1.1.

Statement 1

Statement 2

Statement n

Figure 1.1. Sequence structure.

An algorithm to add two numbers entered by user


Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop

Selection Structure
The selection control structure is the presentation of a condition and the choice between
two (or sometimes more) actions. The choice made depends on whether the condition is true or
false. It is also called a decision, one of the three basic logic structures in computer. This structure
is sometimes referred to as an if-then-else because it directs the program to perform in this way: If
Condition A is True then perform Action X else perform Action Y. The flow of sequence structure
is shown in Figure.1.2.

True False
Algorithmic Problem Solving 1.5
Figure 1.2. Selection structure.
1.6 Problem Solving and Python Programming

Algorithm to find the largest among three different numbers entered by user.
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: 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.
Step 5: Stop

Algorithm to find all roots of a quadratic equation ax2+bx+c=0.


Step 1: Start
Step 2: Declare variables a, b, c, D, x1, x2, rp and ip;
Step 3: Calculate discriminant
D←b2-4ac
Step 4: 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
Step 5: Stop

Iteration Structure
The iterative process is also called as repetition or looping. It carries out a particular action
over and over again until some condition is met. A loop is created to return the program to where
the repetition has started for as long as it takes until the condition is met.
Algorithmic Problem Solving 1.7

There are two ways of testing to see if the condition is met: pre-test loops, and post-test
loops. In pre-test loops, the condition is tested at the beginning of the loop. If the condition fails,
the looping process will never carried out. Here the loop is operated only when condition is met.
Pre-test loop ends when the condition fails.

Post-test loops test the condition at the end of the loop. The looping process is executed
first whether the condition is true or false and will keep repeating until the condition is met. This
loop ends when the condition is true. The structures of pre-tested and post-tested loops are shown
in Figure.1.3.

True False

False

True

Figure 1.3. Iteration structure.

Algorithm to find the factorial of a number entered by user


Step 1: Start
Step 2: Declare variables n, factorial and i.
Step 3: Initialize variables
factorial←1
i←1
Step 4: Read value of n
Step 5: Repeat the steps until i=n
5.1: factorial←factorial*i
5.2: i←i+1
Step 6: Display factorial
Step 7: Stop

An algorithm to find the Fibonacci series till term≤1000


Step 1: Start
Step 2: Declare variables first_term, second_term and temp.
Step 3: Initialize variables first_term←0 second_term←1
Step 4: Display first_term and second_term
1.8 Problem Solving and Python Programming

Step 5: Repeat the steps until second_term≤1000


5.1: temp←second_term
5.2: second_term←second_term+first term
5.3: first_term←temp
5.4: Display second_term
Step 6: Stop
Functions
Any complex problem will become simpler if the problem is broken smaller and the smaller
problems are solved. The functions are solutions to smaller problems. These can be used to solve
bigger, complex problems. Algorithm for man online shopping system can be broken down into
smaller functional aspects called modules. Few modules can be used in several other modules.
Hence writing functions would increase the readability and efficiency of the algorithm.
Considering the online shopping system, the products and its details can be segregated as the
following:
Product Basket

Listing Change

Product Check

Figure 1.2.5.1. Functions of Online Shopping System

Algorithm to find the prime numbers in a range of numbers.


Step 1: Start
Step 2: Get the start and end of range
Step 3: Let N=Start

Step 4: Check if number N is prime using Isprime (N)


Step 5: Print number if True is returned

Step 6: Increment N by 1

Step 7: Repeat steps 3 and 5 until end is reached

Step 8: Stop
Algorithmic Problem Solving 1.9

1.3. ALGORITHM NOTATIONS (EXPRESSING ALGORITHMS)


An algorithm is a sequence of finite instructions, often used for calculation and data
processing. Algorithms can be expressed in many kinds of notation, including

Fig 1.3.1 Notations

1.2.1 PSEUDOCODE
Pseudocode (pronounced SOO-doh-kohd) is a kind of structured English for representing
algorithms and is a “text-based” detail design tool for human understanding rather than machine
understanding. It allows the designer to concentrate on the logic of the algorithm without
worrying about the details of language syntax.

Once the pseudo code is prepared, it is rewritten using the syntax and semantic rules of a
programming language.

Rules of Pseudo code


• Start with an algorithm and phrase it using words that are easily transcribed into
computer instructions.
• Indent when you are enclosing instructions within a loop or a conditional clause.
• Avoid words associated with a certain kind of computer language.
• Do not include data declarations in pseudo code.
1.10 Problem Solving and Python Programming

Three basic constructs for flow of control


1. Sequence
◦ Default mode.
◦ Used for the sequential execution of statements, one line after another.
2. Selection
◦ Used for decisions to choose between two or more alternative paths.
3. Repetition
◦ Used for looping to repeat a piece of code several times.

Sequence
It is indicated by writing one statement after another, each statement on a line by itself,
and all statements aligned with the same indent. The actions are performed in the order in which
they are written, from top to bottom.

Common Keywords
Input: READ, INPUT, OBTAIN, GET
Output: PRINT, OUTPUT, DISPLAY, SHOW
Compute: COMPUTE, CALCULATE, DETERMINE
Initialize: SET, INIT
Add one: INCREMENT, BUMP

Examples
(i) Pseudo code for computing the area of a rectangle.
READ height of rectangle
READ width of rectangle
COMPUTE area as height times width
PRINT area

(ii) Pseudo code for computing the average of five numbers.


PRINT “Enter 5 numbers”
READ n1, n2, n3, n4, n5
PRINT “The average is”
SET avg to (n1+n2+n3+n4+n5)/5
PRINT avg
Algorithmic Problem Solving 1.1

Selection
It is a decision (selection) in which a choice is made between two alternative courses of
action and it comprises of the following constructs:
• IF-THEN-ELSE
• CASE...ENDCASE

IF-THEN-ELSE
Binary choice on a given Boolean condition is indicated by the use of four keywords:
◦ IF, THEN, ELSE, and ENDIF.

The general form is:


IF condition THEN
sequence 1
ELSE
sequence 2
ENDIF

The ELSE keyword and “sequence 2” are optional. If the condition is true, sequence 1 is
performed, otherwise sequence 2 is performed.

Examples
(i) Pseudo code to check whether the number is odd or even.
READ number
IF number MOD 2 = 0 THEN
DISPLAY “Number is Even”
ELSE
DISPLAY “Number is Odd”
ENDIF

(ii) Pseudo code to check whether the given non-zero number is positive or negative.
READ number
IF num is less than 0 THEN
PRINT num is negative
ELSE
PRINT num is positive
ENDIF
1.12 Problem Solving and Python Programming

CASE

CASE is a multiway branch (decision) based on the value of an expression. CASE is a


Algorithmic Problem Solving 1.1
generalization of IF-THEN-ELSE. Four keywords, CASE, OF, OTHERS, and ENDCASE, and
conditions are used to indicate the various alternatives.

The general form is:

CASE expression OF
condition 1 : sequence 1
condition 2 : sequence 2
...
condition n : sequence n
OTHERS:
default sequence
ENDCASE

The OTHERS clause with its default sequence is optional. Conditions are normally
numbers or characters indicating the value of “expression”, but they can be English statements or
some other notation that specifies the condition under which the given sequence is to be
performed. A certain sequence may be associated with more than one condition.

Examples
(i) Pseudo code for simple calculator
READ n1, n2
READ choice
CASE choice OF
+ : PRINT n1+n2
– : PRINT n1-n2
* : PRINT n1*n2
/ : PRINT n1/n2
ENDCASE

(ii) Pseudo code for determining gradepoints from grades.


READ grade
CASE grade OF
S : gradepoint = 10
A : gradepoint = 9
Algorithmic Problem Solving 1.11

B : gradepoint = 8
C : gradepoint = 7
D : gradepoint = 6
E : gradepoint = 5
U : gradepoint = 0
ENDCASE
DISPLAY gradepoint

Repetition
It is a loop (iteration) based on the satisfaction of some condition(s). It comprises of the
following constructs:
• WHILE...ENDWHILE
• REPEAT...UNTIL
• FOR...ENDFOR

WHILE...ENDWHILE
It is a loop (repetition) with a simple condition at its beginning. The beginning and ending
of the loop are indicated by two keywords WHILE and ENDWHILE.

The general form is:


WHILE condition
sequence
ENDWHILE

The loop is entered only if the condition is true. The “sequence” is performed for each
iteration. At the conclusion of each iteration, the condition is evaluated and the loop continues as
long as the condition is true.

Examples
(i) Pseudo code to print the numbers from 1 to 100.
n=1
WHILE n is less than or equal to 100
DISPLAY n
INCREMENT n by 1
ENDWHILE
1.12 Problem Solving and Python Programming

(ii) Pseudo code to print the sum of the digits of a given number
INPUT a Number
INITIALIZE Sum to zero
WHILE Number is not zero
COMPUTE Remainder by Number Mod 10
ADD Remainder to Sum
DIVIDE Number by 10
ENDWHILE
PRINT Sum

REPEAT...UNTIL
It is a loop with a simple condition at the bottom. This loop is similar to the WHILE loop
except that the test is performed at the bottom of the loop instead of at the top. Two keywords,
REPEAT and UNTIL are used.

The general form is:


REPEAT
sequence
UNTIL condition

The “sequence” in this type of loop is always performed at least once, because the test
is peformed after the sequence is executed. At the conclusion of each iteration, the condition is
evaluated, and the loop repeats if the condition is false. The loop terminates when the condition
becomes true.

Examples
(i) Pseudo code to print the numbers from 1 to 100.
n=1
REPEAT
DISPLAY n
INCREMENT n by 1
UNTIL n is greater than 100

(ii) Pseudo code to print the sum of the digits of a given number
INPUT a Number
INITIALIZE Sum to zero
Algorithmic Problem Solving 1.13

REPEAT
COMPUTE Remainder by Number Mod 10
ADD Remainder to Sum
DIVIDE Number by 10
UNTIL Number is zero
PRINT Sum

FOR...ENDFOR
FOR is a “counting” loop. This loop is a specialized construct for iterating a specific
number of times, often called a “counting” loop. Two keywords, FOR and ENDFOR are used.

The general form is:


FOR iteration bounds
sequence
ENDFOR

Examples
(i) Pseudo code to print the numbers from 1 to 100.
FOR n=1 to 100
DISPLAY n
ENDFOR

(ii) Pseudo code to input ten numbers and print the sum.
INITIALIZE sum to 0
FOR n=1 to 10
INPUT number
COMPUTE sum as sum+number
ENDFOR
DISPLAY sum

Nested Constructs
The constructs can be embedded within each other, and this is made clear by use of
indenting.
Nested constructs should be clearly indented from their surrounding constructs.

Examples
(i) Pseudo code to find the smallest among three numbers using nested IF construct.
READ the three numbers a, b, c.
1.14 Problem Solving and Python Programming

IF a is less than b THEN


IF a is less than c THEN
PRINT a,
Algorithmic Problem Solving 1.15
ELSE
PRINT c
ENDIF
ELSE IF b is less than a THEN
IF b is less than c THEN
PRINT b
ELSE
PRINT c
ENDIF
ENDIF
(ii) Pseudo construct using IF construct nested within REPEAT construct.
SET total to zero
REPEAT
READ Temperature
IF Temperature > Freezing THEN
INCREMENT total
ENDIF
UNTIL Temperature < zero
PRINT total

Invoking Subprocedures
To call subprocedures (functions), CALL keyword is used with the following structure:

CALL subprocedurename [WITH argumentslist] [RETURNING returnvalue]

Here, “WITH argumentslist” and “RETURNING returnvalue” are optional. “WITH


argumentslist” is used to call a function with arguments. “RETURNING returnvalue” is used
when a called function returns a value.

Examples:
CALL SumAndAvg WITH NumberList
◦ Calls a function SumAndAvg with NumberList as an argument. This function does
not return any value.
CALL SwapItems WITH CurrentItem and TargetItem
◦ Calls a function SwapItems with CurrentItem and TargetItem as arguments. This
function does not return any value.
CALL getBalance RETURNING BalanceAmt
◦ Calls a function getBalance which returns BalanceAmt as its return value. This
function does not take any argument.

Advantages of Pseudo code


(1) Can be read and understood easily.
(2) Can be done easily on a word processor.
(3) Can be modified easily.
(4) Implements structured concepts well.
(5) Clarifies algorithms in many cases.
(6) Imposes increased discipline on the process of documenting detailed design.
(7) Provides additional level at which inspection can be performed.
(8) Helps to trap defects before they become code.
(9) Increases product reliability.
(10) Converting a pseudocode to a program is simple.

Disadvantages of Pseudo code


(1) Creates an additional level of documentation to maintain.
(2) Introduces error possibilities in translating to code.
(3) May require tool to extract pseudocode and facilitate drawing flowcharts.
(4) There is no standardized format, so one pseudocode may be different from another.
(5) For a beginner, it is more difficult to follow the logic and write pseudocode as
compared to flowchart.
(6) We do not get a picture of the design.

1.2.2 Flowchart
Flowchart is a diagrammatic representation of an algorithm or a stepwise process, showing
the steps as boxes of various kinds, and their order by connecting these with arrows. Flowcharts
are used in designing or documenting a process or program. In other words, a flow chart, or flow
diagram, is a graphical representation of a process or system that details the sequencing of steps
required to create output. A flowchart is a picture of the separate steps of a process in sequential
order.
Flowchart is very helpful in writing program and explaining program to others. Flowchart
makes us to understand the problem unambiguously. It is often used by programmer as a program
planning tool for organizing a sequence of step necessary to solve a problem by a computer.

Symbol Purpose Description

Terminal(Stop/Start) Represents start and end of flowchart.

Input/output Represents input and output operation.

Represents arithmetic operations and


Processing
data-manipulations.

Represents the decision making


Decision operation in which there are two
alternatives, true and false.

On-page Connector Used to join different flow line

Used to connect flowchart portion on


Off-page Connector
different page.

Predefined Process/ Represent a group of statements


Function performing one processing task and for
function call.

Used for iterative statements(Looping


Looping statements
structure).

Declare Used for declaration statements

Indicates the flow of logic by


Flow line
connecting symbols.

GUIDELINES
The following are some guidelines in flowcharting:
(a) In drawing a proper flowchart, all necessary requirements should be listed out in
logical order.
(b) The flowchart should be clear, neat and easy to follow. There should not be any room
for ambiguity in understanding the flowchart.
(c) The usual direction of the flow of a procedure or system is from left to right or top to
bottom.
(d) Only one flow line should come out from a process symbol.

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

<0 >0 <0 >0

=0 =0
(f) Only one flow line is used in conjunction with terminal symbol.

(g) Write within standard symbols briefly. As necessary, you can use the annotation
symbol to describe data or computational steps more clearly.

This is top secret data

(h) If the flowchart becomes complex, it is better to use connector symbols to reduce the
number of flow lines. Avoid the intersection of flow lines if you want to make it more
effective and better way of communication.
(i) Ensure that the flowchart has a logical start and finish.
(j) It is useful to test the validity of the flowchart by passing through it with a simple test
data.

Advantages of flow charts


• It is easy to understand
• A problem can be analysed easily with flowchart
• It gives clear idea of a program
• It acts as a guide during the program development
• It helps to clear the errors in coding
• It helps in maintenance of code
Disadvantages of flow charts
• It cannot be prepared for difficult programs
• Alterations and modifications cannot be done easily
• It is not typed, so its preparation is little difficult

Rules for drawing a flow chart is given below


• The standard symbols should only be used.
• The arrowheads in the flowchart represent the direction of flow of control in the
problem.
• The usual direction of the flow of procedure is from top to bottom or left to right.
• The flow lines should not cross each other.
• Be consistent in using names and variables in the flowchart.
• Keep the flowchart as simple as possible.
• Words in the flowchart symbols should be common statements and easy to understand.
• Chart main line of logic, and then incorporate all the details of logic.
• If a new page is needed for flowcharting, then use connectors for better representation.
• Don’t chart every details or the flowchart will only be graphical represented

Flowchart representation to add two numbers


Start

Declare variables num1, num2 and sum

Read num1and num2

sum ← a+b

Display sum

stop
Flowchart representation to find all 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←b-4ac

True is
False
D ≥ 0?
r1←(-b+ 𝐷)/2𝑎 ip←-b+/2𝑎
r2←(-b+ 𝐷)/2𝑎 rp← 𝐷)/2𝑎

x1←rp+j ip
x1← rp-j ip

Display r1 and r2

Stop

Flowchart representation to find the Fibonacci series till term≤1000


Start

Declare variables fterm, sterm and


temp

fterm←0, sterm←1

is False
sterm ≤
1000?
True
Display sterm

temp←sterm

sterm←sterm+fterm

Stop
fterm←temp
1.2.3 Programming Language
Representation of Algorithm using Programming Language
Algorithms describe the solution to a problem in terms of the data needed to represent
the problem instance and the set of steps necessary to produce the intended result. Programming
languages must provide a notational way to represent both the process and the data. It also provide
control constructs and data types.

Programming is the process of taking an algorithm and encoding it into a notation, a


programming language, so that it can be executed by a computer. Although many programming
languages and many different types of computers exist, the important first step is the need to have
the solution. Without an algorithm there can be no program. Control constructs allow algorithmic
steps to be represented in a convenient yet unambiguous way. At a minimum, algorithms require
constructs that perform sequential processing, selection for decision-making, and iteration for
repetitive control. As long as the language provides these basic statements, it can be used for
algorithm representation.

Programming is implementing the already solved problem (algorithm) in a specific


computer language where syntax and other relevant parameters are different, based on different
programming languages.

Fig Programming

Low level Language(Machine level Language)


A low-level language is a programming language that deals with a computer's hardware
components and constraints. In simple we can say that ,low level language can only be understand
by computer processor and components. Binary and assembly languages are examples for low
level language.

Middle level Language (Intermediate Language)


Medium-level language serves as the bridge between the raw hardware and programming
layer of a computer system.Medium-level language is also known as intermediate programming
language and pseudo language. C intermediate language and Java byte code are some examples of
medium-level language.
High level Language (Human understandable Language)
A high-level language is any programming language that enables development of a
program in a much more user-friendly programming context.High-level languages are designed to
be used by the human operator or the programmer.They are referred to as "closer to humans." In
other words, their programming style and context is easier to learn and implement than low- level
languages. BASIC, C/C++ and Java are popular examples of high-level languages.

Fig 1.3.8 Programming

1.3 ALGORITHMIC PROBLEM SOLVING


Definition
“Algorithmic-problem solving”; this means solving problems that require the formulation
of an algorithm for their solution. The formulation of algorithms has always been an important
element of problem-solving.

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.

Step 1: Obtain a description of the problem.


This step is much more difficult than it appears. In the following discussion, the word client
refers to someone who wants to find a solution to a problem, The word developer refers to someone
who finds a way to solve the problem. The developer must create an algorithm that will solve the
client's problem.

Step 2: Analyze the problem.


The purpose of this step is to determine both the starting and ending points for solving the
problem. This process is analogous to a mathematician determining what is given and what must
be proven. A good problem description makes it easier to perform this step.

Step 3: Develop a high-level algorithm.


An algorithm is a plan for solving a problem, but plans come in several levels of detail.
It's usually better to start with a high-level algorithm that includes the major part of a solution, but
leaves the details until later. We can use an everyday example to demonstrate a high-level
algorithm.
Problem: I need to send a birthday card to my brother, Mark.
Analysis: I don't have a card. I prefer to buy a card rather than make one myself.
Example: Go to a store that sells greeting cards Select a card Purchase a card & mail the
card.

Step 4: Refine the algorithm by adding more detail.


A high-level algorithm shows the major steps that need to be followed to solve a problem.
The technique of gradually working from a high-level to a detailed algorithm is often called
stepwise refinement. Stepwise refinement is a process for developing a detailed algorithm by
gradually adding detail to a high-level algorithm.

Step 5: Review the algorithm.


The final step is to review the algorithm. First, we need to work through the algorithm step
by step to determine whether or not it will solve the original problem.

1.4 . STRATEGIES SIMPLE FOR DEVELOPING ALGORITHMS


There are various kinds of algorithm development techniques formulated and used for
different types of problems.
1.5.1. Iteration
The iteration technique repeats the execution of a block of instructions. I f a statement has to
be executed more than once then, the technique of repetition is applied. It saves the trouble of
writing the same statements again and again.
Example: Consider a program segment designed to find the sum of first 100 integers.
i=1;
sum=0;
while(i=100)
sum=sum+i;
i=i+1;
When the while structure finishes executing, the sum will contain the desired answer.
The flowchart in figure illustrates the flow of control in the while structure that corresponds
to the proceeding while structure.

Yes sum=sum+i
i<=100 i=i+1

No

The flowchart clearly shows the repetition. The flow-line emerging from the rectangle
wraps back to the decision that is tested each time through the loop until the decision becomes false.
Then the while structure exits and control passes to the next statement in the program.

Algorithm: To find the sum of first 100 integers.


Step 1: Start
Step 2: Assign sum=0,i=0
Step 3: Calculate i=i+1 and sum=sum+i
Step 4: Check whether i>=100, if no repeat step 3. Otherwise go to next step.
Step 5: Print the value of sum
Step 6: Stop
1.5.1. RECURSION
In recursive technique a function or procedure is called by itself again and again until a
given condition is satisfied.
Recursion is defining a large and complex problem in terms of smaller and more easily solvable
problems. In recursive function, a complex problem is defined in terms of simpler and simpler
problem.
Since the function is repeatedly by a call by itself, there is no overhead of changing control
from one block into another and that gives considerably a cost effective tool for a long and lengthy
pattern of search problem.
Example: Recursive algorithm for finding the factorial of a number.
Step 1: Start
Step 2: Read number n
Step 3: Call factorial (n)
Step 4: Print factorial f
Step 5: Stop
Factorial (n)
Step 1: if n==1 then return 1
Step 2: Else
f=n x factorial (n-1)
Step 3: Return f

1.6. ILLUSTRATIVE PROBLEMS


1.6.1. Finding a minimum list
Algorithm:
1. Start
2. Get positive numbers from user and add it in to the List L
3. Set min to L[0].
4. For each number x in the list L, compare it to min. If x is smaller, set min to x.
5. Min is now set to the minimum number in the list.
6. Stop
Flow chart for finding minimum number in a list.
Start

Read the list


numbers, i and min

min= numbers[0]

False For i in numbers

True
No
if i<min

Yes
min= i

print ‘The minimum


value in the list is min’

Stop

Pseudo code to find minimum in a list


READ the list of numbers
INITIALIZE min with the first element of the list
FOR each element in the list of numbers
IF element is less than min
COPY element to min
ENDIF
ENDFOR
PRINT min as the minimum value

1.6.2.Pseudo code to insert a card in a list of sorted cards


Playing cards is one of the techniques of sorting and the steps are shown as follows:

• Start with an empty left hand and cards face down on the table.
• Then remove one card at a time from the table and Insert it into the correct position in
the left hand.
• To find a correct position for a card, we compare it with each of the cards already in
the hand from left to right.
Once the position is found, the cards from that position are moved to the next higher
indexed position and in that order.

New card is inserted at the current position.

Algorithm
1. Start
2. Ask for value to insert
3. Find the correct position to insert, If position cannot be found ,then insert at the end.
4. Move each element from the backup to one position, until you get position to insert.
5. Insert a value into the required position
6. Increase array counter
7. Stop

Pseudo Code
READ the list of sorted cards
READ newcard
SET pos to 0
WHILE (pos < numberOfCards) and (CARDS [pos] <= newcard)
INCREMENT pos
ENDWHILE
IF pos < numberOfCards then
INCREMENT numberOfCards by 1
FOR counter = last position used to pos by -1
SET CARDS [counter + 1] to array CARDS [counter]
ENDFOR
ENDIF
SET CARDS [pos] to newcard
Flowchart for inserting a card in a list of sorted cards
Start

position=1

No
position<length

Yes
location = position

No location > 0
position=position+1 && cards [location]
< cards [location-1]

Yes
Swap cards [location] < cards[location-1]

location= location-1

Stop

1.6.3.Guessing Game
Problem: Guessing Game – guessing a number within a range of numbers.

Algorithm:
Step 1. Generate a random number in between 1 and 100.
Step 2. Prompt the user for a guess number.
Step 3. Determine if the guessing number is
Step 3. (a). Equal to the random number: If it is, output a message that says the guessing is
correct and go to step 4.
Step 3. (b). Less than the random number: If it is,
(i) Output a message “Too low,”
(ii) Ask if the user wants to continue the game. If yes, ask for another guess
number; otherwise go to step 4.
Step 3. (c). Greater than the random number: If it is,
(i) Output a message “Too high,”
(ii) Ask if the user wants to continue the game. If yes, ask for another guess
number; otherwise go to step 4.
Step 4. Stop.
Pseudo code to guess an integer number in a range
This task allows a player to guess a number that lies between 1 and 100. The code should
keep repeating until the player guesses the correct number. The number guessed by the system in
the following pseudo code is 45.
Pseudo Code
READ number from player
WHILE number is not equal to 45
IF number is less than 45 THEN
PRINT Your guess is too small.
ELSE IN number is greater than 45
PRINT Your guess is too high.
ENDIF
IF number does not fall between 1 and 100 THEN
PRINT Guess a number between 1 and 100
ENDIF
READ number
ENDWHILE
PRINT Your guess is correct
Flowchart:
Start

num=input random
number

guess=input user
guess

Yes No Yes
Does Is
guess=num guess>num?

No

Print “Well done that’s’ Print “Too


right” low”

Print “Too
Yes Do you high”
want
to

Do you No
No give
up?
Yes

End
1.6.4.Towers of Hanoi
Problem:
Tower of Hanoi is a mathematical puzzle with three rods and ‘n’ numbers of discs. These
rings are of different sizes and stacked upon in an ascending order, i.e. the smaller one sits over
the larger one. The objective is to move all the disks to some another tower without violating the
sequence of arrangement.

Rules to be followed:
• 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.

2 DISKS

A B C

(1) (2) (3)

A B C A B C A B C

Recursive Algorithm of Towers of Hanoi:


Main program
#fr-source rod; ar-auxillary rod; tr-target rod
Step 1: Start
Step 2: Define function
Step 3: Declare variable n
Step 4: Enter the number of disc n
Step 5: Initialize the fr=a, ar=c, tr = b
Step 4: Call the function towerfun (n, a , c, b)
Step 5: Stop

Algorithm for Function Definition


Step 1: if n=1
Step 1.a: Print Move disc 1 from fr to tr
Step 2: Call the function with n-1, fr, ar, tr
Step 3: Move disc n from fr to tr
Step 4: Call function with n-1, ar, tr, fr
Step 5: Return

Pseudo code for Towers of Hanoi


SUBPROCEDURE Hanoi(disk, source, destination, auxiliary)
IF disk == 0, THEN
move disk from source to destination
ELSE
MoveTower(disk - 1, source, auxiliary, destination)
Move disk from source to destination
MoveTower(disk - 1, auxiliary, destination, source)
ENDIF
END PROCEDURE

The above subprocedure “Hanoi” can be called by the following statement:


CALL Hanoi WITH 5, A, B, C

Flowchart: Main program


Start

Define function tower fun

Declare n

Enter the number of Discs

Call the function towerfun M


with n, A, C, B

End
Flowchart: Function towerfun()
M

n=1
?

Print Move disc 1 from fr to tr

Call the function towerfun


with n-1, fr, ar, tr

Print Move disc n from fr to tr

Call the function towerfun


with n-1, ar, tr, fr

Return

Additional algorithms and programs


Algorithm to check whether a number entered by user is prime or not.
Step 1: Start
Step 2: Declare variables n,i,flag
Step 3: Initialize variables
flag←1
i←2
Step 4: Read n from user
Step 5: Repeat the steps until i<(n/2)
5.1 If remainder of n÷i equals 0
flag←0
Go to step 6
5.2 i←i+1
Step 6: If flag=0
Display n is not prime
else
Display n is prime
Step 7: Stop
Algorithm to find minimum and maximum elements in the list.
Problem: Given a list of positive numbers, return the largest number on the list.
Inputs: A list L of positive numbers.
Outputs: A number n, which will be the largest number of the list.

Algorithm:
Step 1: Set max to 0 and min to 0.
Step 2: For each number x in the list L, compare it to max.
Step 2.a: If x is larger, set max to x. Else set min to x
Step 3: Display max and min
Step 4: Stop

Algorithm to print numbers from 1 to 20.


Algorithm:
Step 1: Initialize X as 0,
Step 2: Increment X by 1,
Step 3: Print X,
Step 4: If X is less than 20 then go back to step 2. Else go to step 5.
Step 5: Stop

Algorithm to convert Temperature from Fahrenheit to Celsius


Algorithm:
Step 1: Read temperature in Fahrenheit,
Step 2: Calculate temperature with formula C=5/9*(F-32),
Step 3: Print C
Step 4: Stop

Algorithm to determine and output whether number N is Even or Odd


Algorithm:
Step 1: Read number N
Step 2: Set remainder as N modulo 2
Step 3: If remainder is equal to 0 then number N is even, else number N is odd
Step 4: Print output.
Step 5: Stop
Algorithm to determine whether a student passed the Exam or Not
Algorithm:
Step 1: Input grades of 4 courses M1, M2, M3 and M4,
Step 2: Calculate the average grade with formula “Grade=(M1+M2+M3+M4)/4”
Step 3: If the average grade is less than 60, print “FAIL”, else print “PASS”.
Step 4: Stop

Flowchart to print numbers from 1 to 20


Start

Initialize X< 0

Increment X by 1

Print X

Yes

X < 20

No

End

Flowchart to convert Temperature from Fahrenheit to Celsius


Start

Read F

C = 5/9*(F-32)

Print C

End
Flowchart to determine and output whether number N is Even or Odd
Start

Input N

Remainder = N
Modulo 2

Yes No
Remainder = 0?

Answer = EVEN Answer = ODD

Output
Answer

End

Flowchart to determine whether a student passed the Exam or Not


Start

Input M1,
M2m M3, M4

Grade =
(M1+M2+M3+M4)/4

Yes No
If Grade < 60

Print “FAIL” Print “PASS”

End
Algorithmic Problem Solving 1.35

TWO MARKS QUESTION & ANSWER


1. What is an algorithm?
An algorithm is defined as a step by step procedure for solving a problem. It is a set of rules
to solve a problem.

2. What are the characteristics of an algorithm?


• In algorithms each and every instruction should be precise.
• In algorithms each and every instruction should be unambiguous.
• The instructions in an algorithm should not be repeated infinitely.
• Ensure that the algorithm will ultimately terminate.
• The algorithm should be written in sequence.
• It looks like normal English.
• The desired result should be obtained only after the algorithm terminates.

3. What is a pseudo code?


“Pseudo” means imitation of false and “code” refers to the instruction written in the
programming language. Pseudo code is programming analysis tool that is used for planning
program logic.
• Pseudo = copy (or) Duplicate, Code = instructions
• It cannot be compiled or executed
• It is written in natural language such as English, etc
• It is used to concentrate on algorithm

4. What is a flow chart?


A Flowchart is a pictorial representation of an algorithm. It is often used by programmer as
a program planning tool for organizing a sequence of step necessary to solve a problem by a
computer. It contains different symbols.
Input/Output

Terminal

5. List the ways to represent an algorithm.


• Normal English
• Flowchart
• Pseudo code
• Decision table
• Program
1.36 Problem Solving and Python Programming

6. Write some rules for drawing a flowchart.


• The standard symbols must be used.
• The arrowheads in the flowchart represent the direction of flow of control in the
problem.
• The usual direction of the flow of procedure is from top to bottom or left to right.
• The flow lines should not cross each other.
• Be consistent in using names and variables in the flowchart.
• Keep the flowchart as simple as possible.

7. List few advantages and disadvantages of flowchart.


Advantages:
• Makes logic clear
• Communication
• Effective Analysis
• Useful in Coding
• Proper Testing and Debugging
• Appropriate Documentation

Disadvantages:
• It cannot be prepared for difficult programs
• Alterations and modifications cannot be done easily

8. List the limitations of flowcharts.


• Complex
• Costly
• Difficult to Modify
• No Update

9. List few advantages and disadvantages of pseudo code.


Advantages:
• It can be done easily in any word processor.
• It can be written easily.
• It can be easily modified as compared to flowchart.

Disadvantages:
• It is not visual.
Algorithmic Problem Solving 1.37

• There are no accepted standards for writing pseudo codes.


• It cannot be compiles nor executed.

10. What is the use of decision box in flowcharts?


The decision symbol is used in a flowchart to indicate the point where a decision is to be
made and branching done upon the result of the decision to one or more alternative paths.
The criteria for decision making are written in the decision box.

11. What do flowlines show?


Flowlines are solid lines with arrowheads which indicate the flow of operation. They show
the exact sequence in which the instructions are to be executed. The normal flow of the
flowchart is depicted from top to bottom and left to right.

12. List any two steps involved in problem solving.


The problem solving involves :
• Detailed study of the problem
• Problem redefinition
• Identification of input data, output requirements and conditions and limitations
• Alternative methods of solution
• Selection of the most suitable method
• Preparation of a list of procedures and steps to obtain the solution
• Generating the output

13. Develop an algorithm and draw the flowchart to get marks for 3 subjects and declare
the result. If the marks >= 35 in all the subjects the student passes else fails.
Algorithm:
1. Start.
2. Declare three variables m1, m2, m3.
3. Read marks of three subjects m1, m2, m3.
4. If m1 >= 35 goto step 5 else goto step 7
5. If m2 >= 35 goto step 6 else goto step 7
6. If m3 >= 35 print Pass. Goto step 8
7. Print fail
8. Stop
1.38 Problem Solving and Python Programming

Flowchart:
Start

m1 = m2 = m3 =0

Read m1, m2, m3

No
M1>=35

Yes
No
M2>=35

Yes
No
M3>=35

Yes

Print PASS Print FAIL

Stop

14. Develop an algorithm and draw the flowchart to compute average of three numbers.
Algorithm:
1. Start
2. Read numbers a,b,c
3. Compute the average as (a+b+c)
4. Print average
5. Stop

Flowchart:
Start

Read a, b, c

avg =(a+b+c)/3

Print avg

Stop
Algorithmic Problem Solving 1.39

15. Draw the flowchart for following: read age of a person. If age less than 60 then print
“Not a senior citizen” otherwise print “Senior Citizen”.
Start

Read Age

Yes

Print
Age < 20 Not a
senior
citizen
No
Pr
int
senior
citizen
Stop

16. Write pseudo code to compute area of rectangle.


READ length, breadth
COMPUTE area = length * breadth
DISPLAY area

17. Write pseudo code to evaluate student result.


READ student’s grade
IF student’s grade is greater than or equal to 60
PRINT “passed”
ELSE
PRINT “failed”

18. Mention the different symbols used in flowchart.


Start Stop
1.40 Problem Solving and Python Programming
Terminal Processing
Symbols

Input/Output Connectors
Decision Flow Lines
Box
19. What keywords are commonly used in Pseudocode?
Input: READ, INPUT, OBTAIN, GET
Output: PRINT, OUTPUT, DISPLAY, SHOW
Compute: COMPUTE, CALCULATE, DETERMINE
Initialize: SET, INIT
Add one: INCREMENT, BUMP

20. List out the rules in writing the pseudocode.


• Start with an algorithm and phrase it using words that are easily transcribed into
computer instructions.
• Indent when you are enclosing instructions within a loop or a conditional clause.
• Avoid words associated with a certain kind of computer language.
• Do not include data declarations in pseudo code.

You might also like