0% found this document useful (0 votes)
11 views40 pages

Unit - 1

The document provides an introduction to algorithmic problem solving using Python, covering its features, problem-solving techniques, and the importance of algorithms, flowcharts, and pseudocode. It outlines the characteristics of good algorithms, steps for developing them, and the advantages and disadvantages of using algorithms, pseudocode, and flowcharts. Additionally, it discusses the building blocks of algorithms, including statements, control flow, and functions, as well as the basics of programming languages.

Uploaded by

kurinji
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views40 pages

Unit - 1

The document provides an introduction to algorithmic problem solving using Python, covering its features, problem-solving techniques, and the importance of algorithms, flowcharts, and pseudocode. It outlines the characteristics of good algorithms, steps for developing them, and the advantages and disadvantages of using algorithms, pseudocode, and flowcharts. Additionally, it discusses the building blocks of algorithms, including statements, control flow, and functions, as well as the basics of programming languages.

Uploaded by

kurinji
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

AlgorithmicProblemSolving

UNIT – 1 ALGORITHMICPROBLEMSOLVING

Introduction to Python Language

Python is a widely used general-purpose, high level programming language. It


is an interpreter, object-oriented, high-level programming language with dynamic
semantics. Its high-level built in data structures, combined with dynamic typing and
dynamic binding, makes it very attractive for the development of different
applications, as well as for the usage as a scripting or glue language to connect
existing components together.
It was created by Guido van Rossum in 1991 and further developed by the
Python Software Foundation. It was designed with an emphasis on code readability,
and its syntax allows programmers to express their concepts in fewer lines of
code.Python is a programming language that lets you work quickly and integrate
systems more efficiently.There are two major Python versions: Python 2 and Python
3. Both are quite different.Beginning with Python programming it is must to finding
an Interpreter: Before we start Python programming, we need to have an interpreter to
interpret and run our programs. For windows: There aremany interpreters available
freely to run Python scripts like IDLE (Integrated Development Environment) that
comes bundled with the Python software and for macOS: Generally, Python 2.7 comes
bundled with macOS. Python3 or above versions of Python cab be manually install
from http://python.org/
Problem Solving Techniques
Problem solving technique is a set of methods which helps us to provide a logic
for solving a problem or a given task. These problem-solving techniques can be
defined by the following three components
1. Algorithm
2. Flowchart
3. Pseudocode
These three components can be expressed in the form of any programming
languages to give a proper solution of a particular task or a problem. Let us discuss
these in detail.
1.1 Algorithm
“Algorithm is a step- by-step procedure for solving a task or a problem. It is
an ordered sequence of finite, well defined, unambiguous instructions for completing
a task.”
It is English like representation of the logic used to solve the problem.

1. 1
AlgorithmicProblemSolving

Example1.1: Algorithm to display a message


Step 1: Start
Step 2:Get/Read the message
Step 3: Print the message
Step 4: Stop

Simple python code to display a message

# Script Begins
A=input(“Enter a message”)
print(A)
# Scripts Ends
Output:
Welcome to python

1.1.1 Need of an Algorithm?


An algorithm serves variety purposes and it is used to
 To understand the basic idea of the problem.
 To find an approach to solve the problem.
 To improve the efficiency of existing techniques.
 To give a clear description of requirements and goal of the problem
to the designer.
 To understand the flow of the problem.

1.1.2 Characteristics of Good Algorithm


There are five different characteristics which deal with various aspects of
algorithm. They are as follows:
1. Definiteness:Each step of an algorithm must be precisely defined; the actions to be
carried out must be rigorously and unambiguously specified for each case.
2. Effectiveness: An algorithm is also generally expected to be effective. This means
that each step of an algorithm must be feasible and it should not contain any
unnecessary or redundant steps which could make an algorithm ineffective.
3. Finiteness: An algorithm must always terminate after a finite number of steps.
4. Independent:An algorithm should have step-by-step directions, which should be
independent of any programming language.

1. 2
AlgorithmicProblemSolving

5. Input specified: The input is the data to be transformed during the computation to
produce the output. An algorithm should have 0 or more well-defined inputs.
6. Output specified: The output is the data resulting from the computation (your
intended result). An algorithm should have 1 or more well-defined outputs, and should
match the desired output.
7. Correctness: Finite steps in an algorithm must return a correct output for any given
input.

1.1.3Steps for Developing Algorithm


An algorithm is a plan for solving a problem. The development of an algorithm
is a key step in solving a problem. Once we have an algorithm, we can translate it into
a computer program in some programming language. 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.

1.1.4 Advantages and Disadvantages


Advantages:
 Easy to understand
 Provides definite solution
 Independent of programming languages
 Easy to debug
Disadvantages:
 Hard to design a logical problem
 Need more knowledge to create a program
 Difficult to represent branching and looping statements
 Take more time to convert as a program

1.2 Building Blocks of Algorithm


Algorithms can be constructed from basic building blocks namely statement,
state, control flow and functions.
1.2.1 Statement: Statement represents single action in a computer. The algorithm
consists of finite number of statements. Statements must be in an ordered form and
1. 3
AlgorithmicProblemSolving

should complete in finite amount of time. Computer statements might include


following actions
1. Input statements-Information is fed tothe program through input
statement.
2. Processing statement-Process the data given as input.
3. Output statement-Display the output to the end user.
1.2.2 State:In computer science, a system is described as state-full if it is designed to
remember preceding events or user interactions. The remembered information is
called the state of the system.
1.2.3 Control flow: Control flow is the order in which the individual statements are
executed. Different types of control flows are
1. Sequence
2. Selection
3. Iteration
Building Block Common Name
Sequence Step by Step Execution
Selection Decision
Iteration Repetition or Loop

1. Sequence:
Sequencing is the application of each step of an algorithm in the order in which
the statements are given.In a sequence control flow, the instructions are executed in a
linear order one after the other. The sequence can contain any number of actions, but
no actions can be skipped in the sequence. The program, when run, must perform each
action in order with no possibility of skipping an action or branching off to another
action.
Example1.2: Algorithm to find the sum of two numbers
Step 1: Start
Step 2: Get two numbers from user and store it in variables Aand B.
Step 3: Add A and B and assign the result to sum.
sum= A + B
Step 4: Display sum
Step 5: Stop
2. Selection:

1. 4
AlgorithmicProblemSolving

Selection uses a Boolean condition to determine which of two parts of an


algorithm is used. In a selection structure, a question is asked, and depending on the
answer, the program takes one of two courses of action, after which the program
moves on to the next event.
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.
Example1.3: Algorithm to find the greater of two numbers
Step 1: Start
Step2: Read A, B,
Step3: If A > B is True, then print A is greater otherwise print B is
greater.
Step3:Stop

3. Iteration
Iteration is the repetition of a part of an algorithm until a condition is met or for
a specified number of times. One or more instructions are executed repeatedly.
For example, a program written to compute a company`s weekly payroll for
each individual employee will begin by computing the wages of one employee and
continue performing that action in a loop until there are no more employee wages to
be computed, and then the program can move on to its next action.
Each pass through the loop is called iteration. Loops constitute one of the most basic
and powerful programming concepts.
Example 1.4: Algorithm to find sum of 1st 100 integers
Step 1: Start
Step 2: Assign sum = 0, i=1
Step 3: Calculatesum = sum + i and i=i+1
Step 4: Check whether i>100, if no repeat step 3 or go to next step
Step5: Print the value of sum
Step 6: Stop
All logical problems in programming can be solved by forming algorithms
using only the three logic structures, and they can be combined in an infinite number
of ways. The more complex of the computing need is the more complex the
combination of structures.

1. 5
AlgorithmicProblemSolving

1.2.4 Functions
A function is a named block of sequence of reusable code (statement) that is
used to perform a single, related computation. Functions provide better modularity for
your application. Python provides many built-in functions like print(), input(), etc, and
we can also create our own functions.
Some of the advantages of using functions in python are:
 Decomposing complex problems into simpler pieces.
 Easy to debug and test.
 Enables the reuse of code.
 Improves clarity and readability of the code.
 Improves maintainability.
 Enables information hiding.
 Reduces duplication of code.
Two types of python functions are:
1. Build-in Function
2. User defined Function

1.3 Notation
1.3.1 Pseudo Code
Pseudocode is a way of expressing an algorithm without conforming to specific
syntactic rules and a simple way of writing programming code in English.It is an
informal high-level description of a computer program or algorithm. Pseudocode is
not actual programming language. It uses short phrases to write code for programs
before you actually create it in a specific language.
Using pseudocode, beginners can more easily communicate ideas and concepts
to other programmers, even though they may be using completely different languages.
There is no such thing as correct pseudocode, although there are a few generally
accepted notations that are widely understood by programmers (e.g. A =5 to create a
variable called A with a value of 5), no matter which language they use.
Why is this so important?
When we are first building a program, we don't really care about the actual
LANGUAGE or SYNTAX we will use. Rather, we care about the logic. Pseudocode
helps us by forcing to think logically rather than about syntax.
Common Keywords: The Keywords often used to indicate common input,
output, and processing operations are
Input: READ, OBTAIN, GET
Output: PRINT, DISPLAY, SHOW
Compute: COMPUTE, CALCULATE, DETERMINE
1. 6
AlgorithmicProblemSolving

Initialize: SET, INIT


Add one: INCREMENT, BUMP
Subtract one: DECREMENT

Example 1.5: Find the sum of any two numbers

READ the values of X and Y


COMPUTE C by Adding X and Y
PRINT the result in C
STOP

Advantages of Pseudocode
 It can be easily modified
 It can be easily converted into program
 Easy to read and understand the concepts
 Independent of programming languages.
Disadvantages of Pseudocode
 No fixed rules for writing pseudocode.
 It cannot be compiled and executed.
 For beginners, it will be difficult to follow the logics.
 It does not provide visual representation.

1.3.2 Flow Chart


Flowchart is a graphical (Pictorial) representation of an algorithm.
Programmers often use it as a program-planning tool to solve a problem. It makes use
of symbols which are connected among them to indicate the flow of information and
processing. The process of drawing a flowchart for an algorithm is known as
“flowcharting”.

Flowchart Symbols
Different flowchart shapes have different conventional meanings. The
meanings of some of the more common shapes are as follows:

Table 1.1: Flowchart symbols, name and description

1. 7
AlgorithmicProblemSolving

Symbol Symbol Name Description

Terminator It represents the starting or ending


(Start/End) of the process.

It represents operation or action


Process
step.

It represents information entering


or leaving the system. An input
Data might be an order from a
customer. Output can be a product
to be delivered.
A diamond represents a decision
or branching point. Lines coming
Decision out from the diamond indicate
different possible situations,
leading to different -processes.

This represents a printout, such as


Document
a document or a report.

Lines represent the flow of the


Flow sequence and direction of a
process.

This symbol would contain a letter


inside. It indicates that the flow
On-Page Reference continues on a matching symbol
containing the same letter
somewhere else on the same page.

1. 8
AlgorithmicProblemSolving

Example 1.6: Flowchart to find the sum of first N natural numbers using
iteration structure

When to Draw Flowchart?


Using a flowchart has a variety of benefits:
 It helps to clarify complex processes.
 It identifies steps that do not add value to the internal or external customer,
including delays; needless storage and transportation; unnecessary work,
duplication, and added expense; breakdowns in communication.
 It helps team members gain a shared understanding of the process and use this
knowledge to collect data, identify problems, focus discussions, and identify
resources.
 It serves as a basis for designing new processes. Let us discuss with some
examples.

1. 9
AlgorithmicProblemSolving

Example 1.7: Flowchart to find Sum and Average of two numbers using
sequential structure

Start

Input a, b

Sum = a+b

Avg = (Sum/2)

Display
Sum, Avg

End

Example 1.8: Flowchart to find given number is odd or even

Start

Read num

num %
2==0
False
True
Print it is an Print it is an
odd number even number

End

1. 10
AlgorithmicProblemSolving

Guidelines for Drawing a Flowchart


 The flowchart should be clear, neat and easy to follow.
 The flowchart must have logical start and end.
 Only one flow-line should enter a process symbol and input symbol.
 Only one flow-line should come-out from a process symbol and input symbol.
 Only one flow-line should enter a decision symbol. However, two or three lines
may leave the decision symbol.
 Only one flow-line is used with terminal symbol.
 Intersection of flow-lines should be avoided
Advantages of Flowchart
 It provides a better way for communicating the logic to solve the problem.
 It provides an effective way to analyse the problem.
 It serves as a good program document.
 It acts as blueprint for coding.
 It makes debugging easier.
Disadvantages of Flowchart
 Flowchart representation of complex logic becomes complex and clumsy
 Alterations in flowchart may require redrawing completely
 Programs are updated regularly, whereas regular updation is not possible in
flowchart.

1.3.3 Programming Language


A programming language is a set of symbols and rules for instructing a
computer to perform specific tasks. The programmers have to follow all the specified
rules before writing program using programming language. The user has to
communicate with the computer using language which it can understand.
Types of programming language
1. Machine language
2. Assembly language
3. High level language
1. Machine language:
The computer can understand only machine language which uses 0’s and 1’s. In
machine language the different instructions are formed by taking different
combinations of 0’s and 1’s.
Advantages:

1. 11
AlgorithmicProblemSolving

 Translation free: Machine language is the only language which the


computer understands. For executing any program written in any programming
language, the conversion to machine language is necessary. The program
written in machine language can be executed directly on computer. In this case
any conversion process is not required.

 High speed: The machine language program is translation free. Since


the conversion time is saved, the execution of machine language program is
extremely fast.
Disadvantage:
 It is hard to find errors in a program written in the machine language.
 Writing program in machine language is a time consuming process.
 Machine dependent: According to architecture used, the computer differs from
each other. So machine language differs from computer to computer. So a
program developed for a particular type of computer may not run on other type
of computer.
2. Assembly language
To overcome the issues in programming language and make the programming
process easier, an assembly language is developed which is logically equivalent to
machine language but it is easier for people to read, write and understand.Assembly
language is symbolic representation of machine language. Assembly languages are
symbolic programming language that uses symbolic notation to represent machine
language instructions. They are called low level language because they are so closely
related to the machines.
Ex: ADD a, b
Assembler: Assembler is the program which translates assembly language
instruction in to a machine language.
Advantage:
 Easy to understand and use.
 It is easy to locate and correct errors.
Disadvantage
 Machine dependent:Assembly language program which can be
executed on the machine depends on the architecture of computer.
 Hard to learn: It is machine dependent, so the programmer should have
the hardware knowledge to create applications using assembly language.
 Less efficient: Takes more time to execute, because it needs to converts
from machine to assembly language.
3. High level language

1. 12
AlgorithmicProblemSolving

High level language contains English words and symbols. The specified rules
are to be followed while writing program in high level language. The interpreter or
compilers are used for converting these programs in to machine readable form. The
programs that translate high level language in to machine language are called
interpreter or compiler.
 Compiler:
A compiler is a program which translates the source code written in a high
level language in to object code which is in machine language. Compiler reads the
whole program written in high level language and translates it to machine language. If
error is found it displays error message on the screen.
 Interpreter:
Interpreter translates the high level language program in line by line manner.
The interpreter translates a high level language statement in a source program to a
machine code and executes it immediately before translating the next statement. When
an error is found the execution of the program is halted and error message is displayed
on the screen.
Advantages
1. Readability.
2. High level language is closer to natural language so they are easier to
learn and understand.
3. Machine independent.
4. High level language program have the advantage of being portable
between machines.
5. Easy debugging.
6. Easy to find and correct error in high level language.
Disadvantages
Less efficient: The translation process increases the execution time of
the program. Programs in high level language require more memory and take
more execution time to execute.
They are divided into following categories:
1. Interpreted programming languages
2. Functional programming languages
3. Compiled programming languages
4. Procedural programming languages
5. Scripting programming language
6. Mark-up programming language
7. Concurrent programming language
8. Object oriented programming language
 Interpreted programming languages:

1. 13
AlgorithmicProblemSolving

An interpreted language is a programming language for which most of its


implementation executes instructions directly, without previously compiling a
program into machine language instructions. The interpreter executes the program
directly translating each statement into a sequence of one or more subroutines already
compiled into machine code.
Examples: Pascal, Python
 Functional programming language:
Functional programming language defines every computation as a
mathematical evaluation. They focus on the programming languages that bound to
mathematical calculations.
Examples: Clean, Haskell
 Compiled Programming language:
A compiled language is a programming language which is generally compiled
and not interpreted. It is one where the program, once compiled, is converted in to
machine language.
Examples: C, C++, C#, JAVA
 Procedural programming language:
Procedural (imperative) programming implies specifying the steps that the
programs should take to reach to an intended state. A procedure is a group of
statements that can be referred through a procedure call. Procedures help in the reuse
of code. Procedural programming makes the programs structured and easily traceable
for program flow.
Examples: Hyper talk, MATLAB
 Scripting language:
Scripting language are programming languages that control an application.
Scripts can be executed independent of any other application. They are mostly
embedded in the application that they control and are used to automate frequently
executed tasks like communicating with external program.
Examples: Apple script, VB script
 Mark-up languages:
Mark-up languages are languages used by a computer to annotate a document.
It define the style and structure of a document so that a computer knows how you
want that document to appear.
Examples: HTML, XML

 Concurrent programming language:

1. 14
AlgorithmicProblemSolving

Concurrent programming is a computer programming technique that is use for the


execution of operation concurrently, either with in a single computer or across a
number of systems.
Examples: Joule, Limbo
 Object oriented programming language:
Object-oriented programming is a programming paradigm based on the concept
of "objects", which can contain data and code: data in the form of fields (often known
as attributes or properties), and code, in the form of procedures (often known
as methods).

1.4 Algorithmic Problem Solving


Problem solving is the systematic approach to define the problem and creating
number of solutions. The problem-solving process starts with a plan and that plan is
called an algorithm.The algorithmic problem solving process consists of five major
steps, they are

1. Understanding the Problem


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.

2. Deciding on computational means, exact vs approximate solving and data


structure:
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 and solving it approximately.
 Based on this, the algorithms are classified as exact algorithm and
approximation algorithm.

Deciding on Data Structure

1. 15
AlgorithmicProblemSolving

Data structure plays a vital role in designing and analysing the


algorithms.Some of the algorithm design techniques also depend on the structuring
data specifying a problem’s instance.
Algorithm+ Data structure=programs.

Understand the problem

Decide on computational means, exact vs


Approximate solving, data structure, Algorithmic
design Techniques

Design an Algorithm

Prove Correctness

Analyse the Algorithm

Code the Algorithm

Fig. 1.1 Process of Algorithm Design and Analysis

3. Algorithm Design Techniques


An algorithm design technique (or “strategy” or “paradigm”) is a general
approach for solving problems algorithmically which 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

1. 16
AlgorithmicProblemSolving

4. 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.

5. Analysing an Algorithm
Efficiency:
 Time efficiency, indicating how fast the algorithm runs,
 Space efficiency indicating how much extra memory it uses.
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.

6. Coding an Algorithm
 Most algorithms are destined to be 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.

1.5 Simple Strategies for Developing Algorithms


Developing an algorithm is a very important step in problem-solving. There are
different strategies that could be used to develop an algorithm to solve a problem.
Two of the most frequently used strategies are:

 Iteration
 Recursion

1.5.1 Iteration

1. 17
AlgorithmicProblemSolving

Iteration is a process wherein a set of instructions or statements are sequentially


repeated 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 iteration where it could run
multiple times to achieve a specific outcome.
Example 1.9: An algorithm for finding the factorial of a number using
Iteration:

Step 1: Start

Step 2: Get a number from the user and store it in variable num.

Step 3: Initialize variables start and fact with 1.

Step 4: Repeat step 5 and step 6 until start is less than or equal to the num.

Step 5: Multiply start with fact and store the result in variable fact.

Step 6:Increment the value of start and go to step 4.

Step 7: Display the value of fact as the factorial of the given number.

1.5.2 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.

Example 1.10: An algorithm for finding the factorial of a number using


Recursion

Step 1: Start

Step 2: Get a number from the user and store it in variable num.

Step 3: Call the subroutine Finding_Factorial by passing num as the argument


and store the result in fact.

Step 4: Display the value of fact.

Step 5: Stop

1. 18
AlgorithmicProblemSolving

Finding_Factorial(n)

Step 1: Start

Step 2:Check whether n is equal to one, if true return 1 else go to step 3

Step 3:Perform f=n*Finding_Factorial(n)

Step 4:Return f

Step 5: Stop

1.6 Illustrative problems

1.6.1 Find Minimum in a List


Here we have to write an algorithm that helps in finding the smallest number
from the given list of numbers.
Algorithm
Step 1:Start.
Step 2:Read the elements of list.
Step 3:Assign the first element in a list as minimum and i=1
Step 4: Check whether (i<n) if true go to step 6 else goto step8
Step 5: Check whether ith element is less than minimum if true set
minimum=ith element
Step 6: Increment i by 1 and go to step5
Step 7:Display minimum& stop.

1. 19
AlgorithmicProblemSolving

Flowchart

Start

Read List
Elements

minimum = L[0]

Is False
i<n

True

Is False
L[i]<minimum

True
minimum = L[i]

Increment i

Print minimum

Stop

Pseudocode
BEGIN
SET numlist=[ ]
GET n
FOR i=1 to n
GET numlist elements
ENDFOR

1. 20
AlgorithmicProblemSolving

SET minimum = numlist[0]


FOR i in numlist
IF (n < minimum)
minimum = n
ENDIF
ENDFOR
PRINT minimum
END

1.6.2 Insert a Card in a List of Sorted Cards

Algorithm
Step 1: Start.
Step 2: Read n (card to be inserted).
Step 3:set i=0.
Step 4:Check whether n>ith card and i<length(list) if true go to step 5
else go to step 6
Step 5:Increment i and go to step 4
Step 6:Shift the cards from ith position to len(list) by 1 position right.
Step 7:Insert the card at ith position.
Step 8: Stop.

Pseudocode
BEGIN
READ n
SET i=0
WHILE (n>ith card& i<length(list)):
INCREMENT i
END WHILE
SHIFT cards in ith position to len(list) by 1 position right.

1. 21
AlgorithmicProblemSolving

INSERT the card at ith position.


END

Flowchart

Start

Read n

i=0

Is False
n>ith card & i<
length (list))

True

i=i+1

Shift the cards from ith position to


len(list) by one position right

Insert the card at ith position

Stop

1.6.3 Guess an Integer Number in a Range

1. 22
AlgorithmicProblemSolving

Algorithm
Step1: 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
Else
Print Guess not hit
Print hidden
Step 6: Stop

Pseudocode
BEGIN
COMPUTE hidden=random value in a range
READ guess
IF guess=hidden, then
PRINT Guess is hit
ELSE
PRINT Guess not hit
PRINT hidden
END IF-ELSE
END

Flowchart

1. 23
AlgorithmicProblemSolving

Start

Compute hidden= random value in a range

Read Guess

False Is True
Guess==hidden

Print “Guess is Print “Guess is


not hit” hit”

Stop

1. 24
AlgorithmicProblemSolving

1.6.4 Towers of Hanoi


Tower of Hanoi, is a mathematical puzzle which consists of three towers(pegs)
and more than one rings is as depicted −

Towers

Disks

3 Smallest

1 Largest

These rings are of different sizes and stacked upon in an ascending order, i.e.
the smaller one sits over the larger one. There are other variations of the puzzle where
the number of disks increase, but the tower count remains the same.
Rules
The mission is to move all the disks to some another tower withoutviolating the
sequence of arrangement. A few rules to be followed for Tower of Hanoi are −
 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.
Following is an animated representation of solving a Tower of Hanoi puzzle with
three disks.
Tower of Hanoi puzzle with n disks can be solved in minimum 2n−1 steps. This
presentation shows that a puzzle with 3 disks has taken 23 - 1 = 7 steps. 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).
The goal of the puzzle is to move all the disks from leftmost peg to rightmost
peg.Move only one disk at a time.A larger disk may not be p1aced on top of a smaller
disk. For example, consider n=3 disks

1. 25
AlgorithmicProblemSolving

Step: 1

Beg Aux End

Step: 2

1 3

Beg Aux End

Step: 3

1 2 3

Beg Aux End

1. 26
AlgorithmicProblemSolving

Step: 4

1 2

Beg Aux End

Step: 5

2 1

Beg Aux End

Step: 6

3 2 1

Beg Aux End

1. 27
AlgorithmicProblemSolving

Step: 7

3 1

Beg Aux End

Output:

Beg Aux End

Algorithm
Procedure Hanoi(disk, Beg,End,Aux)
If disk==1. THEN
move disk from Beg to End
ELSE
Hanoi (disk -1, Beg, Aux, End)
move disk from Beg to End
Hanoi (disk -1, Aux, End, Beg)
END If
END Procedure

1. 28
AlgorithmicProblemSolving

1.7 Additional Examples


Example 1.11: Algorithm to find greatest among three numbers.
Step 1: Start
Step 2: Get 3 numbers A,B,C from the user
Step 3: Check whether (A>B) if true then go to step 4 otherwise go
to step 5
Step 4: Check whether (A>C) if true then print “A is greater”
otherwise print “C is greater”

Step 5: Check whether (B>C) if true then print “B is greater”


otherwise print “C is greater”
Step 6: Stop

Example 1.12: Algorithm to calculate area and circumference of a


circle
Step 1: Start
Step 2: Read r
Step 3: Compute area=3.14*r*r and circumference=2*3.14*r
Step 4: Print area and circumference
Step 5: Stop

Example 1.13: Algorithm to findwhether a given number is even or odd


Step 1: Start
Step 2: Read n
Step 3:Check whether (n%2 == 0) if true thenprint “even number"
otherwiseprint “odd number"
Step 4: Stop

Example 1.14: Algorithm to find Fibonacci Series

1. 29
AlgorithmicProblemSolving

Step 1: Start
Step 2: Readi, a,b, show
Step 3: Initialize a=0, b=1, i=2 and show =0
Step 4: Read number of terms of Fibonacci series to be printed (n)
Step 5: Print a and b
Step 6: Repeat following stepsuntil i<n
 show=a+b
 a=b
 b=show
 Increase value of i each time by 1
 print the value of show
Step 7: End

Example 1.15: Algorithm to find GCD of the two numbers


Step1: Start
Step 2: Get 2 integer inputs from the user
Step 3: Next, use decision-making statements or use recursion to check
if both the given numbers are divisible by any number (i) without
leaving any remainder.
Step 4: If true, then GCD = i
Step 5: Print the GCD of the two numbers
Step 6: Stop

Example 1.16: Algorithm to display first n odd number


Step 1: Start
Step 2: Read n
Step 3: Set i=1, j=0
Step 4: Check whether (j<=n), if true go to step 5 else go to step 7
Step 5: Check whether (i%2!=0), if true print(i) and Increment j
Step 6: Increment i and go to step 4
Step 7: Stop

1. 30
AlgorithmicProblemSolving

Example 1.16: Pseudocode to find greatest among three numbers.


BEGIN
READ a,b,c
IF(a>b)
IF(a>c)
PRINT “a is greater”
ELSE
PRINT “c is greater”
END IF
ELSE IF(b>c)
PRINT “b is greater”
ELSE
PRINT “c is greater”
END IF
END

Example 1.17: Pseudocode to find factorial of a number.


BEGIN
READ n
Fact=CALL Fact(n)
Print Fact
END
Fact(n)
BEGIN
IF n == 0 or 1 then
Return 1;
ELSE

1. 31
AlgorithmicProblemSolving

Return n*Call Fact(n-1);


ENDIF
END

Example 1.18: Pseudocodefor sum of even numbers between 0 and 50


SET sum = 0, i=2
WHILE i <=50
IF (i%2==0) then
sum=sum+i
End IF
INCREMENT i
END WHILE
PRINT sum

Example 1.19: Flowchart to find largest of three numbers

1. 32
AlgorithmicProblemSolving

Start

Read a, b, c

False True
Is a>b

False True
Is b>c
False True
Is a>c

Print c is Print b is Print a is


Greater Print c is Greater
Greater
Greater

Stop

Example 1.20: Flowchart to whether the given year is leap year or not

1. 33
AlgorithmicProblemSolving

Start

year = INPUT (“input a


year e.g. 2020”)

IF
False
(year MOD 400 == 0)
or ((year mod 100!=0)
and(year mod 4==0))

True

Print “Not a Leap year”


Print “Leap year”

Stop

2 Marks Questions with Answers

1. 34
AlgorithmicProblemSolving

1. What is an algorithm?
“Algorithm is a step- by-step procedure for solving a task or a problem. It is an
ordered sequence of finite, well defined, unambiguous instructions for
completing a task.”
It is English like representation of the logic used to solve the problem.
2. What are the steps for developing algorithms?
 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.
3. Write an algorithm to find minimum of 3 numbers in a list.
Step 1: Start
Step 2: Get 3 numbers A,B,C from the user
Step 3: Check whether (A>B) if true then go to step 4 otherwise go
to step 5
Step 4: Check whether (A>C) if true then print “A is greater”
otherwise print “C is greater”

Step 5: Check whether (B>C) if true then print “B is greater”


otherwise print “C is greater”
Step 6: Stop
4. List the building blocks of an algorithm.
 Statement
 State
 Control flow
 Functions
5. Define statement. List its types.
Statement represents single action in a computer. Computer statements might
include following actions
1. Input statements-Information is fed tothe program through input
statement.
2. Processing statement-Process the data given as input.
3. Output statement-Display the output to the end user.

1. 35
AlgorithmicProblemSolving

6. Write the pseudo code to calculate the sum and product of two numbers and
display it.
READ number1, number2
COMPUTE sum = number1 + number2
PRINT “The sum is “, sum
COMPUTE product = number1 * number2
PRINT “The Product is “, product
END program
7. How does flow of control work?
Control flow is the order in which the individual statements are executed. Different
types of control flows are
1. Sequence
2. Selection
3. Iteration
8. What is a function?
A function is a named block of sequence of reusable code (statement) that is
used to perform a single, related computation. Functions provide better modularity for
your application. Python provides many built-in functions like print(), input(), etc, and
we can also create our own functions.
9. Define state.
In computer science, a system is described as stateful if it is designed to
remember preceding events or user interactions. The remembered information is
called the state of the system.
10. List the advantagesflowchart.
 It provides a better way for communicating the logic to solve the problem.
 It provides an effective way to analyse the problem.
 It serves as a good program document.
 It acts as blueprint for coding.
 It makes debugging easier.
11. Compare flowchart and pseudo code.
Flowchart and Pseudo code are used to document and represent the algorithm.
In other words, an algorithm can be represented using a flowchart or a pseudo code.
Flowchart is a graphical representation of the algorithm. Pseudo code is a readable,
formally styled English like language representation of the algorithm.
12. Define a flowchart.

1. 36
AlgorithmicProblemSolving

A flowchart is a diagrammatic representation of the logic for solving a task. A


flowchart is drawn using boxes of different shapes with lines connecting them to show
the flow of control. The purpose of drawing a flowchart is to make the logic of the
program clearer in a visual form.
13. Give an example of iteration.
a=0
fori from 1 to 3 // loop
{
a=a+i // add the current value of i to a
}
print a // the number 6 is printed (0 + 1; 1 + 2; 3 + 3)
14. Write down the rules for preparing a flowchart.
 The flowchart should be clear, neat and easy to follow.
 The flowchart must have logical start and end.
 Only one flow-line should enter a process symbol and input symbol.
 Only one flow-line should come-out from a process symbol and input symbol.
 Only one flow-line should enter a decision symbol. However, two or three lines
may leave the decision symbol.
 Only one flow-line is used with terminal symbol.
 Intersection of flow-lines should be avoided
15. Define programming language.
A programming language is a vocabulary and set of grammatical rules for
instructing a computer or computing device to perform specific tasks. The term
programming language usually refers to high-level languages, such as BASIC, C,
C++, COBOL, Java, FORTRAN, Ada, and Pascal.
16. Mention the characteristics of an algorithm.
 Algorithm should be precise and unambiguous.
 Instruction in an algorithm should not be repeated infinitely.
 Ensure that the algorithm will ultimately terminate.
 Algorithm should be written in sequence.
 Algorithm should be written in normal English.
 Desired result should be obtained only after the algorithm terminates.

17. What is the difference between algorithm and pseudo code?


An algorithm is a systematic logical approach used to solve problems in a
computer while pseudo code is the statement in plain English that may be translated

1. 37
AlgorithmicProblemSolving

later to a programming language. Pseudo code is the intermediary between algorithm


and program.
18. Give the differences between recursion and iteration.
Recursion Iteration
Function calls itself until the base Repetition of process until the
condition is reached. condition fails.
Only base condition (terminating It involves four steps: initialization,
condition) is specified. condition, execution and updation.
Iterative approach makes our code
It keeps our code short and simple.
longer.
It is slower than iteration due to overhead
Iteration is faster.
of maintaining stack.
It takes more memory than iteration due to
Iteration takes less memory.
overhead of maintaining stack.

19. What are advantages and disadvantages of recursion?


Advantages Disadvantages
Recursive functions make the code look Sometimes the logic behind recursion is
clean and elegant. hard to follow through.
A complex task can be broken down into Recursive calls are expensive
simpler sub-problems using recursion. (inefficient) as they take up a lot of
memory and time.
Sequence generation is easier with Recursive functions are hard to debug.
recursion than using some nested
iteration.

20. Give an example for recursion function.


#to find the factorial of a number
defcalc_factorial(x):
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
num = 4

1. 38
AlgorithmicProblemSolving

print("The factorial of", num, "is", calc_factorial(num))


Output: The factorial of 4 is 24
23. Differentiate predefined function and user defined function.

Predefined function User defined function

A user-defined function is a function


Predefined functions are part of the
which the programmer creates and uses
programming language.
in a program.
For eg.built-in C functions, like printf(
For eg.def Add()
) and scanf( ).

16 Marks Questions
1. 39
AlgorithmicProblemSolving

1. What are the building blocks of an algorithm? Explain in detail.


2. Briefly describe iteration and recursion. Illustrate with an example.
3. Explain in detail Algorithmic problem solving.
4. Write an algorithm and draw a flowchart to calculate 24.
5. Describe the guidelines to write pseudo code with an example.
6. Write the pseudo code for Towers of Hanoi.
7. Discuss how to draw a flowchart? Draw a flowchart to count and print from
number1 to 10.
8. Write an algorithm and give the flowchart to find the net salary of an
employee.
9. Write an algorithm and give the pseudo code to guess an integer number in a
range.
10. Write an algorithm to insert a card in a list of sorted cards.
11. Write an algorithm to find the minimum number in a list.

1. 40

You might also like