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

Class 11 Cs Ch5_introduction to Python and Debugging_notes

The document provides an overview of Python programming, covering topics such as its features, execution modes, and the importance of algorithms in problem-solving. It explains the process of writing and executing Python code, including the use of an interpreter and the structure of algorithms. Additionally, it discusses the representation of algorithms through flowcharts and pseudocode, as well as the characteristics of good algorithms.

Uploaded by

kgyyd
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
6 views40 pages

Class 11 Cs Ch5_introduction to Python and Debugging_notes

The document provides an overview of Python programming, covering topics such as its features, execution modes, and the importance of algorithms in problem-solving. It explains the process of writing and executing Python code, including the use of an interpreter and the structure of algorithms. Additionally, it discusses the representation of algorithms through flowcharts and pseudocode, as well as the characteristics of good algorithms.

Uploaded by

kgyyd
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 40

GETTING STARTED WITH PYTHON

CONTENT – REVIEW

S.NO TOPICS
1. Introduction to Python

2. Python Keywords

3. Identifiers

4. Variables

5. Comments

6. Everything is an Object

7. Data Types

8. Operators

9. Expressions

10. Statement

11. Input and Output

12. Type Conversion

13. Debugging
5.1 INTRODUCTION TO PYTHON

A program written in a high-level language is called source code. Python uses an


interpreter to convert its instructions into machine language, so that it can be
understood by the computer. An interpreter processes the program statements one by
one, first translating and then executing. This process is continued until an error is
encountered or the whole program is executed successfully

5.1.1 Features of Python

 Python is a high level language. It is a free and open source language.


 It is an interpreted language, as Python programs are executed by an
interpreter.
 Python programs are easy to understand as they have a clearly defined
syntax and relatively simple structure.
 Python is case-sensitive. For example, NUMBER and number are not
same in Python.
 Python is portable and platform independent, means it can run on various
operating systems and hardware platforms.
 Python has a rich library of predefined functions.
 Python is also helpful in web development. Many popular web services
and applications are built using python.
 Python uses indentation for blocks and nested blocks.

5.1.2 Working with Python

To write and run (execute) a Python program, we need to have a Python interpreter
installed on our computer or we can use any online Python interpreter.
5.1.3 Execution Modes

There are two ways to use the Python interpreter:

a) Interactive mode

b) Script mode

Interactive Mode:

Without passing python script file to the interpreter, directly execute code to Python
(Command line).
Example:
>>>6+3
Output: 91. INTRODUCTION

Computers are used for solving various day-to-day problems.

It is pertinent to mention that computers themselves cannot solve a problem.

Precise step-by-step instructions should be given by us to solve the problem.

Thus, the success of a computer in solving a problem depends on how correctly and
precisely we define the problem, design a solution (algorithm) and implement the
solution (program) using a programming language.

Thus, problem solving is the process of identifying a problem, developing an


algorithm for the identified problem and finally implementing the algorithm to
develop a computer program.

2. Steps for Problem Solving

There are four steps in problem solving


Analysing the problem

Developing an Algorithm

Coding

Testing and Debugging

2.1 Analysing the problem

It is important to clearly understand a problem before we begin to find the solution for
it.

If we are not clear as to what is to be solved, we may end up developing a program


which may not solve our purpose.

By analysing a problem, we would be able to figure out what are the inputs that our
program should accept and the outputs that it should produce.

2.2 Developing an Algorithm

The solution for a problem is represented in step by step procedure called an algorithm.

For a given problem, more than one algorithm is possible and we have to select the
most suitable solution.

2.3 Coding

After finalising the algorithm, we need to convert the algorithm into the format which
can be understood by the computer to generate the desired solution.

2.4 Testing and Debugging

The program created should be tested on various parameters.

The program should meet the requirements of the user.

In the presence of syntactical errors, no output will be obtained.

In case the output generated is incorrect, then the program should be checked for logical
errors, if any.
3. Algorithm

Algorithm is the step by step procedure for solving the problem. Suppose following
are the steps required for an activity ‘riding a bicycle’:

remove the bicycle from the stand,

sit on the seat of the bicycle,

start peddling,

use breaks whenever needed and

stop on reaching the destination.

Example:

Algorithm to find square of a number.

Step 1: Input a number and store it to num

Step 2: Compute num * num and store it in square

Step 3: Print square

3.1 Why do we need an Algorithm

Writing an algorithm is mostly considered as a first step to programming.

Once we have an algorithm to solve a problem, we can write the computer program for
giving instructions to the computer in high level language.

If the algorithm is correct, computer will run the program correctly, every time.

So, the purpose of using an algorithm is to increase the reliability, accuracy and
efficiency of obtaining solutions.

Characteristics of a good algorithm


• Precision — the steps are precisely stated or 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 always stops after a finite number of steps.

• Input — the algorithm receives some input.

• Output — the algorithm produces some output.

While writing an algorithm, it is required to clearly identify the following:

• The input to be taken from the user

• Processing or computation to be performed to get the desired result

• The output desired by the user

4. Representation of Algorithms

There are two common methods of representing an algorithm —flowchart and


pseudocode. Either of the methods can be used to represent an algorithm while
keeping in mind the following:

• it showcases the logic of the problem solution, excluding any implementational details

• it clearly reveals the flow of control during execution of the program

4.1 Flowchart — Visual Representation of

Algorithms A flowchart is a visual representation of

an algorithm.

A flowchart is a diagram made up of boxes, diamonds and other shapes, connected by


arrows.

Symbols / Functions / Descriptions / Start/End .


Also called “Terminator” symbol. It indicates where the flow starts and ends.
Process

Also called “Action Symbol,” it represents a process, action, or a single step.


Decision

A decision or branching point, usually a yes/no or true/ false question is asked, and
based on the answer, the path gets split into two branches.

Input/Output

Also called data symbol, this parallelogram shape is used to input or output data

Arrow

Connector to show order of flow between shapes.

Flowchart to calculate square of a number

4.2 Pseudocode

A pseudocode (pronounced Soo-doh-kohd) is another way of representing an


algorithm. It is considered as a non-formal language that helps programmers to write
algorithm. The word “pseudo” means “not real,” so “pseudocode” means “not real
code”. Following are some of the frequently used keywords while writing

pseudocode:

• INPUT

• COMPUTE

• PRINT

• INCREMENT

• DECREMENT

• IF/ELSE

• WHILE
• TRUE/FALSE

Example:

Pseudocode for the sum of two numbers will be:

input num1

input num2

COMPUTE Result = num1 + num2

PRINT Result

4.5 Flow of Control

The flow of control depicts the flow of events as represented in the flow chart.

4.5.1 Sequence

Sometimes the algorithm to either does some routine tasks in a repeated manner or
behave differently depending on the outcomes of previous steps.

The statements are executed one after another is known as sequence.

4.5.2 Selection

Let us look at some other examples where decision making is dependent on certain
conditions. For example,

(i) Checking eligibility for voting.

Depending on their age, a person will either be allowed to vote or not allowed to vote:

• If age is greater than or equal to 18, the person is eligible to vote

• If age is less than 18, the person is not eligible to vote

(ii) Let us consider another example


If a student is 8 years old and the student likes Maths put the student in Group A

Otherwise

Put the student in Group B

Actions depending on true or false of a condition

Conditionals are written in the algorithm as follows:

If <condition> then

steps to be taken when the

condition is true/fulfilled

There are situations where we also need to take action when the condition is not
fulfilled (In above Figure). To represent that, we can write:

If <condition> is true then

steps to be taken when the condition is

true/fulfilled

otherwise

steps to be taken when the condition is

false/not fulfilled

4.6 Verifying Algorithms

The software designer should make sure that the functioning of all the components are
defined correctly, checked and verified in every possible way.

When we were told that the formula for the sum of first N natural numbers is N(N+1)
/ 2 , how did we verify it?
Well, we can check this for small numbers, for which we can manually calculate the
sum.

Let N = 6, then the sum is 1 + 2 + 3 + 4 + 5 + 6 = 21 Using formula we get sum =


6x(6+1) / 2

The method of taking an input and running through the steps of the algorithm is
sometimes called dry run. Such a dry run will help us to:

1. Identify any incorrect steps in the algorithm

2. Figure out missing details or specifics in the algorithm

Write an algorithm to calculate the time taken to go from place A to C (T_total) via B
where time taken to go from A to B (T1) and B to C (T2) are given. That is, we want
the algorithm to add time given in hours and minutes. One way to write the algorithm
is:

PRINT value for T1

INPUT hh1

INPUT mm1

PRINT value for T2

INPUT hh2

INPUT mm2

hh_total = hh1 + hh2 (Add hours)

mm_total = mm1 + mm2 (Add mins)

Print T_total as hh_total, mm_total

Now let us verify. Suppose the first example we take is T1 = 5 hrs 20 mins and T2 = 7
hrs 30 mins. On dry run, we get the result 12 hrs and 50 mins. This looks fine.

4.7 Comparison of Algorithm


There can be four different ways to write algorithms to check whether a given number
is prime or not as shown below:

(i) Starting with divisor 2, divide the given number (dividend) and check if there are
any factors. Increase the divisor in each iteration and repeat the previous steps as long
as divisor < dividend. If there is a factor, then the given number is not prime

(ii) In (i), instead of testing all the numbers till the dividend, only test up to half of the
given value (dividend) because the divisor can not be more than half of the dividend

(iii) In method (i), only test up to the square root of the dividend (numbers)

(iv) Given a prior list of prime number till 100, divide the given number by each
number in the list. If not divisible by any number, then the number is a prime else it is
not prime

All these four methods can check if a given number is prime or not. Now the question
is which of these methods is better or efficient?

Algorithm (i) requires large number of calculations (means more processing time) as
it checks for all the numbers as long as the divisor is less than the number. If the
given number is large, this method will take more

time to give the output.

Algorithm (ii) is more efficient than (i) as it checks for divisibility till half the
number, and thus it reduces the time for computation of the prime number.

Algorithm (iii) is even more efficient as it checks for divisibility till square root of the
number, thereby further reducing the time taken.

As algorithm (iv) uses only the prime numbers smaller than the given number for
divisibility, it further reduces the calculations. But in this method we require to store
the list of prime numbers first. Thus it takes additional

memory even though it requires lesser calculations.

Hence, algorithms can be compared and analysed on the basis of the amount of
processing time they need to run and the amount of memory that is needed to execute
the algorithm. These are termed as time complexity and space complexity,
respectively. The choice of an algorithm over another is done depending on how
efficient they are in terms of processing time required (time complexity) and the
memory they utilize (space complexity).
4.8 Coding

Once an algorithm is finalised, it should be coded in a high-level programming


language as selected by the programmer.

The ordered set of instructions are written in that programming language by following
its syntax.

Syntax is the set of rules or grammar that governs the formulation of the statements in
the language, such as spellings, order of words, punctuation, etc.

4.9 Decomposition

The basic idea of solving a complex problem by decomposition is to 'decompose' or


break down a complex problem into smaller sub problems

Answer the Following Questions (Very Short Annswers)

Define Algorithm

What is decomposition?

Why do we need Algorithm?

What is meant by Debugging?

Answer the Following Questions (Short Answers)

Write an algorithm to find the greatest among two different numbers

Write a pseudocode to calculate the factorial of a number

Write an algorithm to fing greates among three numbers

Answer the Following Questions (LongAnswers)

Write pseudocode and draw flowchart to accept numbers till the user enters 0 and
then find their average.
Write a pseudocode and draw a flowchart where multiple conditions are checked to
categorize a person as either child (<13), teenager (>=13 but <20) or adult
(>=20),based on age specified:

Write an algorithm that accepts four numbers as input and find the largest and
smallest of them.

REVISION NOTES

CLASS XI

GETTING STARTED WITH PYTHON

5.1 INTRODUCTION TO PYTHON

A program written in a high-level language is called source code. Python uses an


interpreter to convert its instructions into machine language, so that it can be
understood by the computer. An interpreter processes the program statements one by
one, first translating and then executing. This process is continued until an error is
encountered or the whole program is executed successfully

5.1.1 Features of Python

Python is a high level language. It is a free and open source language.

 It is an interpreted language, as Python programs are executed by an interpreter.

 Python programs are easy to understand as they have a clearly defined syntax
and relatively simple structure.

 Python is case-sensitive. For example, NUMBER and number are not same in
Python.
 Python is portable and platform independent, means it can run on various
operating systems and hardware platforms.

 Python has a rich library of predefined functions.

 Python is also helpful in web development. Many popular web services and
applications are built using python.

 Python uses indentation for blocks and nested blocks.

5.1.2 Working with Python

To write and run (execute) a Python program, we need to have a Python interpreter
installed on our computer or we can use any online Python interpreter.

Script Mode:
In this mode source code is stored in a file with the .py extension and use the
interpreter to execute the contents of the file. To execute the script by the interpreter,
you have to tell the interpreter the name of the file.
Example:
If you have a file name Demo.py , to run the script you have to follow the
following steps:

Step-1: Open the text editor i.e. Notepad


Step-2: Write the python code and save the file with .py file extension.
(Default directory is C:\Python33/Demo.py)
Step-3: Open IDLE ( Python GUI) python shell
Step-4: Click on file menu and select the open option
Step-5: Select the existing python file
Step-6: Now a window of python file will be opened
Step-7: Click on Run menu and the option Run Module.
Step-8: Output will be displayed on python shell window

5.2 PYTHONKEYWORDS

Reserved words in the library of a language. There are 33 keywords in python.

All the keywords are in lowercase except 03 keywords (True, False, None)

5.3 IDENTIFIERS
Identifier: The name given by the user to the entities like variable name, class-name,
function-name etc.

Rules for identifiers:

 It can be a combination of letters in lowercase (a to z) or uppercase (A to Z)


or digits (0 to 9) or an underscore.
 It cannot start with a digit.
 Keywords cannot be used as an identifier.
 We cannot use special symbols like !, @, #, $, %, + etc. in identifier.
 _ (underscore) can be used in identifier.
 Commas or blank spaces are not allowed within an identifier.

5.4 VARIABLES
 A variable in a program is uniquely identified by a name (identifier).
 Variable in Python refers to an object — an item or element that is stored in the
memory.
 Value of a variable can be a string (e.g., ‘b’, ‘Global Citizen’), numeric (e.g.,
345) or any combination of alphanumeric characters (CD67).
 In Python we can use an assignment statement to create new variables and
assign specific values to them.
gender = 'M'
message = "Keep Smiling"
price = 987.9
Program Write a program to display values of variables in Python.
#To display values of variables
message = "Keep Smiling"
print(message)
userNo = 101
print('User Number is', userNo)
Output:
Keep Smiling
User Number is 101
5.5 COMMENTS
 Comments are not executed.
 Comments explain a program and make a program understandable and
readable.
 All characters after the # and up to the end of the physical line are part of the
comment and the Python interpreter ignores them.
Example
#Variable amount is the total spending on grocery
amount = 3400
#totalMarks is sum of marks in all the tests of Mathematics
totalMarks = test1 + test2 + finalTest

5.6 EVERYTHING IS ANOBJECT


Python treats every value or data item whether numeric, string, or other type
(discussed in the next section) as an object in the sense that it can be assigned to some
variable or can be passed to a function as an argument.
Example
>>> num1 = 20
>>> id(num1)
1433920576 #identity of num1
>>> num2 = 30 - 10
>>> id(num2)
1433920576 #identity of num2 and num1
#are same as both
refers to #object 20

5.7 DATATYPES
5.7.1 Number

Number data type stores numerical values only. It is further classified into three
different types: int, float and complex.

Table Numeric data types

Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting of
two constants, True and False.

Example
>>> num1 = 10
>>> type(num1)
<class 'int'>

>>> float1 = -1921.9


>>> type(float1)
<class 'float'>
>>> float2 = -9.8*10**2
>>> print(float2, type(float2))
-980.0000000000001 <class 'float'>

>>> var2 = -3+7.2j


>>> print(var2, type(var2))
(-3+7.2j) <class 'complex

5.7.2 Sequence
String
String is a group of characters. These characters may be alphabets, digits or special
characters including spaces.
>>> str1 = 'Hello Friend'
>>> str2 = "452"
We cannot perform numerical operations on strings, even when the string contains a
numeric value, as in str2.
List
List is a sequence of items separated by commas and the items are enclosed in square
brackets [ ].
Example
#To create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> print(list1)
[5, 3.4, 'New Delhi', '20C', 45]
Tuple
Tuple is a sequence of items separated by commas and items are enclosed in
parenthesis ( ). This is unlike list,
where values are enclosed in brackets [ ]. Once created, we cannot change the tuple.
Example
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')
Set
Set is an unordered collection of items separated by commas and the items are
enclosed in curly brackets { }. A set is similar to list, except that it cannot have
duplicate entries. Once created, elements of a set cannot be changed.

Example
#create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(type(set1))
<class 'set'>
>>> print(set1)
{10, 20, 3.14, "New Delhi"}
#duplicate elements are not included in set
>>> set2 = {1,2,1,3}
>>> print(set2)
{1, 2, 3}
5.7.4 None
None is a special data type with a single value.
Example
>>> myVar = None
>>> print(type(myVar))
<class 'NoneType'>
>>> print(myVar)
None
5.7.5 Mapping
Mapping is an unordered data type in Python. Currently, there is only one standard
mapping data type in Python
called dictionary.
Dictionary
Dictionary in Python holds data items in key-value pairs.Items in a dictionary are
enclosed in curly brackets { }.
Example
#create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
>>> print(dict1['Price(kg)'])
120
5.7.6 Mutable and Immutable Data Types
Mutable Immutable
The objects can be modified after the Objects can not be modified after the
creation as well. creation of the objects.
Classes that are mutable are not considered Classes that are immutable are
final. considered final.
Thread unsafe. Thread-safe.
Classes are not made final for the mutable Classes are made final for the
objects. immutable objects.
Example: Lists, Dicts, Sets, User-Defined Example: int, float, bool, string,
Classes, Dictionaries, etc. Unicode, tuple, Numbers, etc.

5.8 OPERATORS
5.8.1 Arithmetic Operators
5.8.2 Relational Operators
5.8.3 Assignment Operators
5.8.4 Logical Operators

5.8.5 Identity Operators


5.8.6 Membership Operators

5.9 EXPRESSIONS

An expression is defined as a combination of constants, variables, and operators.

An expression always evaluates to a value.

1. 100
2. 3.0 + 3.14
3. num
4. 23/3 -5 * 7(14 -2)
5. num – 20.4
6. "Global" + "Citizen"
5.9.1 Precedence of Operators
Example
How will Python evaluate the following expression?
(20 + 30) * 40
Solution:
= (20 + 30) * 40 # Step 1
#using parenthesis(), we have forced precedence of + to be more than that of *
= 50 * 40 # Step 2
= 2000 # Step 3
Example
How will the following expression be evaluated in Python?
15.0 / 4 + (8 + 3.0)
Solution:
= 15.0 / 4 + (8.0 + 3.0) #Step 1
= 15.0 / 4.0 + 11.0 #Step 2
= 3.75 + 11.0 #Step 3
= 14.75 #Step 4

5.10 STATEMENT
In Python, a statement is a unit of code that the Python interpreter can execute.
Example
>>> x = 4 #assignment statement
>>> cube = x ** 3 #assignment statement
>>> print (x, cube) #print statement
4 64

5.11 INPUT AND OUTPUT


The input() function prompts the user to enter data. It accepts all user input as string.
The user may enter a number or a string but the input() function treats them as strings
only.
The syntax for input() is:
input ([Prompt])
Example 5.14
>>> fname = input("Enter your first name: ")
Enter your first name: Arnab
>>> age = input("Enter your age: ")
Enter your age: 19
>>> type(age)
Example

5.12 TYPE CONVERSION


Consider the following program
num1 = input("Enter a number and I'll double it: ")
num1 = num1 * 2
print(num1)
The program was expected to display double the value of the number received and
store in variable num1.
So if a user enters 2 and expects the program to display 4 as the output, the program
displays the following result:
Enter a number and I'll double it: 2
22
5.12.1 Explicit Conversion
Program
Program of explicit type conversion from int to float.
#Explicit type conversion from int to float
num1 = 10
num2 = 20
num3 = num1 + num2
print(num3)
print(type(num3))
num4 = float(num1 + num2)
print(num4)
print(type(num4))
Output: 30 30.0
Program
Program to show explicit type conversion.
#Explicit type conversion
icecream = '25'
brownie = '45' #String concatenation
price = icecream + brownie
print("Total Price Rs." + price) #Explicit type conversion - string to integer
price = int(icecream)+int(brownie)
print("Total Price Rs." +
str(price)) Output: Total Price
Rs.2545
Total Price Rs.70

5.12.2 Implicit Conversion


Implicit conversion, also known as coercion, happens when data type conversion is
done automatically by
Python and is not instructed by the programmer. Program 5-10 Program to show
implicit conversion from int to
float.
#Program
#Implicit type conversion from int to float
num1 = 10 #num1 is an integer
num2 = 20.0 #num2 is a float
sum1 = num1 + num2 #sum1 is sum of a float and an integer
print(sum1)
print(type(sum1))
Output: 30.0

5.13 DEBUGGING
A programmer can make mistakes while writing a program, and hence, the program
may not execute or may generate wrong output. The process of identifying and
removing such mistakes, also known as bugs or errors, from a program is called
debugging. Errors occurring in programs can be categorised as:
i) Syntax errors.
ii) Logical errors
iii) Runtime errors

5.13.1 Syntax Errors


Like other programming languages, Python has its own rules that determine its
syntax. The interpreter interprets the statements only if it is syntactically (as per the
rules of Python) correct. If any syntax error is present, the interpreter shows error
message(s) and stops the execution there. For example, parentheses must be in pairs,
so the expression (10 + 12) is syntactically correct, whereas (7 + 11 is not due to
absence of right parenthesis. Such errors need to be removed before the execution of
the program
5.13.2 Logical Errors
Logical errors are also called semantic errors as they occur when the meaning of the
program (its semantics) is not correct.
For example, if we wish to find the average of two numbers 10 and 12 and we write
the code as 10 + 12/2, it would run successfully and produce the result 16. Surely, 16
is not the average of 10 and 12. The correct code to find the average should have been
(10 + 12)/2 to give the correct output as 11.
5.13.3 Runtime Error
A runtime error causes abnormal termination of program while it is executing.
Runtime error is when the statement is correct syntactically, but the interpreter cannot
execute it. Runtime errors do not appear until after the program starts running or
executing.
Program
Example of a program which generates runtime error.
#Runtime Errors Example
num1 = 10.0 S.NO
TOPIC

Introduction , Steps for Problem Solving , Algorithm , , Representation of Algorithms

Flow of Control , Verifying Algorithms , Comparison of Algorithm , Coding ,


Decomposition
1. INTRODUCTION
Computers are used for solving various day-to-day problems.
It is pertinent to mention that computers themselves cannot solve a problem.
Precise step-by-step instructions should be given by us to solve the problem.
Thus, the success of a computer in solving a problem depends on how correctly and
precisely we define the problem, design a solution (algorithm) and implement the
solution (program) using a programming language.
Thus, problem solving is the process of identifying a problem, developing an
algorithm for the identified problem and finally implementing the algorithm to
develop a computer program.
2. Steps for Problem Solving
There are four steps in problem solving
Analysing the problem
Developing an Algorithm
Coding
Testing and Debugging

2.1 Analysing the problem


It is important to clearly understand a problem before we begin to find the solution for
it.
If we are not clear as to what is to be solved, we may end up developing a program
which may not solve our purpose.
By analysing a problem, we would be able to figure out what are the inputs that our
program should accept and the outputs that it should produce.

2.2 Developing an Algorithm


The solution for a problem is represented in step by step procedure called an
algorithm. For a given problem, more than one algorithm is possible and we have to
select the most suitable solution.

2.3 Coding
After finalising the algorithm, we need to convert the algorithm into the format which
can be understood by the computer to generate the desired solution.

2.4 Testing and Debugging


The program created should be tested on various parameters.
The program should meet the requirements of the user.
In the presence of syntactical errors, no output will be obtained.
In case the output generated is incorrect, then the program should be checked for logical
errors, if any.
3. Algorithm
Algorithm is the step by step procedure for solving the problem. Suppose following
are the steps required for an activity ‘riding a bicycle’:
remove the bicycle from the stand,
sit on the seat of the bicycle,
start peddling,
use breaks whenever needed and
stop on reaching the destination.

Example:
Algorithm to find square of a number.

Step 1: Input a number and store it to num


Step 2: Compute num * num and store it in square
Step 3: Print square

3.1 Why do we need an Algorithm


Writing an algorithm is mostly considered as a first step to programming.
Once we have an algorithm to solve a problem, we can write the computer program for
giving instructions to the computer in high level language.
If the algorithm is correct, computer will run the program correctly, every time.
So, the purpose of using an algorithm is to increase the reliability, accuracy and
efficiency of obtaining solutions.

Characteristics of a good algorithm


• Precision — the steps are precisely stated or 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 always stops after a finite number of steps.
• Input — the algorithm receives some input.
• Output — the algorithm produces some output.
While writing an algorithm, it is required to clearly identify the following:
• The input to be taken from the user
• Processing or computation to be performed to get the desired result
• The output desired by the user

4. Representation of Algorithms

There are two common methods of representing an algorithm —flowchart and


pseudocode. Either of the methods can be used to represent an algorithm while
keeping in mind the following:
• it showcases the logic of the problem solution, excluding any implementational details
• it clearly reveals the flow of control during execution of the program
4.1 Flowchart — Visual Representation of Algorithms
A flowchart is a visual representation of an algorithm.
A flowchart is a diagram made up of boxes, diamonds and other shapes, connected by
arrows.
Symbols
Functions
Descriptions

Start/End
Also called “Terminator” symbol. It indicates where the flow starts and ends.

Process
Also called “Action Symbol,” it represents a process, action, or a single step.
Decision
A decision or branching point, usually a yes/no or true/ false question is asked, and
based on the answer, the path gets split into two branches.

Input/Output
Also called data symbol, this parallelogram shape is used to input or output data

Arrow
Connector to show order of flow between shapes.

Flowchart to calculate square of a number

4.2 Pseudocode
A pseudocode (pronounced Soo-doh-kohd) is another way of representing an
algorithm. It is considered as a non-formal language that helps programmers to write
algorithm. The word “pseudo” means “not real,” so “pseudocode” means “not real
code”. Following are some of the frequently used keywords while writing
pseudocode:
• INPUT / • COMPUTE / • PRINT / • INCREMENT / • DECREMENT / • IF/ELSE /•
WHILE
• TRUE/FALSE

Example:
Pseudocode for the sum of two numbers will be:
input num1
input num2
COMPUTE Result = num1 + num2
PRINT Result

4.5 Flow of Control


The flow of control depicts the flow of events as represented in the flow chart.

4.5.1 Sequence
Sometimes the algorithm to either does some routine tasks in a repeated manner or
behave differently depending on the outcomes of previous steps.
The statements are executed one after another is known as sequence.

4.5.2 Selection
Let us look at some other examples where decision making is dependent on certain
conditions. For example,
(i) Checking eligibility for voting.
Depending on their age, a person will either be allowed to vote or not allowed to vote:
• If age is greater than or equal to 18, the person is eligible to vote
• If age is less than 18, the person is not eligible to vote
(ii) Let us consider another example
If a student is 8 years old and the student likes Maths put the student in Group A
Otherwise
Put the student in Group B

Actions depending on true or false of a condition

Conditionals are written in the algorithm as follows:

If <condition> then
steps to be taken when the
condition is true/fulfilled
There are situations where we also need to take action when the condition is not
fulfilled (In above Figure). To represent that, we can write:
If <condition> is true then
steps to be taken when the condition is
true/fulfilled
otherwise
steps to be taken when the condition is
false/not fulfilled

4.6 Verifying Algorithms

The software designer should make sure that the functioning of all the components are
defined correctly, checked and verified in every possible way.
When we were told that the formula for the sum of first N natural numbers is N(N+1)
/ 2 , how did we verify it?
Well, we can check this for small numbers, for which we can manually calculate the
sum.
Let N = 6, then the sum is 1 + 2 + 3 + 4 + 5 + 6 = 21 Using formula we get sum =
6x(6+1) / 2
The method of taking an input and running through the steps of the algorithm is
sometimes called dry run. Such a dry run will help us to:
1. Identify any incorrect steps in the algorithm
2. Figure out missing details or specifics in the algorithm
Write an algorithm to calculate the time taken to go from place A to C (T_total) via B
where time taken to go from A to B (T1) and B to C (T2) are given. That is, we want
the algorithm to add time given in hours and minutes. One way to write the algorithm
is:
PRINT value for
T1 INPUT hh1
INPUT mm1
PRINT value for
T2 INPUT hh2
INPUT mm2
hh_total = hh1 + hh2 (Add hours)
mm_total = mm1 + mm2 (Add mins)
Print T_total as hh_total, mm_total
Now let us verify. Suppose the first example we take is T1 = 5 hrs 20 mins and T2 = 7
hrs 30 mins. On dry run, we get the result 12 hrs and 50 mins. This looks fine.

4.7 Comparison of Algorithm

There can be four different ways to write algorithms to check whether a given number
is prime or not as shown below:
(i) Starting with divisor 2, divide the given number (dividend) and check if there are
any factors. Increase the divisor in each iteration and repeat the previous steps as long
as divisor < dividend. If there is a factor, then the given number is not prime
(ii) In (i), instead of testing all the numbers till the dividend, only test up to half of the
given value (dividend) because the divisor can not be more than half of the dividend
(iii) In method (i), only test up to the square root of the dividend (numbers)
(iv) Given a prior list of prime number till 100, divide the given number by each
number in the list. If not divisible by any number, then the number is a prime else it is
not prime All these four methods can check if a given number is prime or not. Now
the question is which of these methods is better or efficient?

Algorithm (i) requires large number of calculations (means more processing time) as
it checks for all the numbers as long as the divisor is less than the number. If the
given number is large, this method will take more
time to give the output.
Algorithm (ii) is more efficient than (i) as it checks for divisibility till half the
number, and thus it reduces the time for computation of the prime number.
Algorithm (iii) is even more efficient as it checks for divisibility till square root of the
number, thereby further reducing the time taken.
As algorithm (iv) uses only the prime numbers smaller than the given number for
divisibility, it further reduces the calculations. But in this method we require to store
the list of prime numbers first. Thus it takes additional
memory even though it requires lesser calculations.

Hence, algorithms can be compared and analysed on the basis of the amount of
processing time they need to run and the amount of memory that is needed to execute
the algorithm. These are termed as time complexity and space complexity,
respectively. The choice of an algorithm over another is done depending on how
efficient they are in terms of processing time required (time complexity) and the
memory they utilize (space complexity).

4.8 Coding
Once an algorithm is finalised, it should be coded in a high-level programming
language as selected by the programmer.
The ordered set of instructions are written in that programming language by following
its syntax.
Syntax is the set of rules or grammar that governs the formulation of the statements in
the language, such as spellings, order of words, punctuation, etc.

4.9 Decomposition
The basic idea of solving a complex problem by decomposition is to 'decompose' or
break down a complex problem into smaller sub problems

Answer the Following Questions (Very Short


Annswers) Define Algorithm
What
is
decom
positio
n?
Why
do we
need
Algori
thm?
What is meant by Debugging?

Answer the Following Questions (Short Answers)

Write an algorithm to find the greatest among two


different numbers Write a pseudocode to calculate
the factorial of a number
Write an algorithm to fing greates

among three numbers Answer the

Following Questions

Write pseudocode and draw flowchart to accept numbers till


the user enters 0 and then find their average.
Write a pseudocode and draw a flowchart where multiple
conditions are checked to categorize a person as either child
(<13), teenager (>=13 but <20) or adult (>=20),based on age
specified:
Write an algorithm that accepts four numbers as input and find
the largest and smallest of them.

You might also like