Class 12th Textbook
Class 12th Textbook
2024-
25
12130 – COMPUTER SCIENCE
Textbook for Class XII ISBN 978-93-5292-338-0
First Edition
September 2020 Bhadrapada 1942 ALL RIGHTS RESERVED
No part of this publication may be reproduced, stored in a
retrieval system or transmitted, in any form or by any
Reprinted means, electronic, mechanical, photocopying,
recording or otherwise without the prior permission of
September 2021 Bhadrapada 1943 the publisher.
December 2021 Agrahayana 1943 This book is sold subject to the condition that it shall
not, by way of trade, be lent, re-sold, hired out or
October 2022 Kartika 1944 otherwise disposed off without the publisher’s consent,
March 2024 Chaitra 1946 in any form of binding or cover other than that in which
it is published.
The correct price of this publication is the price printed on
this page. Any revised price indicated by a rubber
stamp or by a sticker or by any other means is
incorrect and should be unacceptable.
PD 25T SU
OFFICES OF THE PUBLICATION
DIVISION, NCERT
© National Council of Educational NCERT Campus
Research and Training, 2020 Sri Aurobindo
Marg
New Delhi 110 016 Phone : 011-26562708
108, 100 Feet Road
Hosdakere Halli
Extension
Banashankari III Stage
Bengaluru 560 085 Phone : 080-26725740
Navjivan Trust Building
P.O.Navjivan
Ahmedabad 380 014 Phone : 079-27541446
CWC Campus
Opp. Dhankal Bus Stop
Panihati
250.00 Kolkata 700 114 Phone : 033-25530454
CWC Complex
Maligaon
Guwahati 781 021 Phone : 0361-2674869
Publication Team
Head, Publication : Anup Kumar Rajput
Division
Printed on 80 GSM paper with NCERT
watermark Chief Editor : Shveta Uppal
2024-
25
FOReWORD
Computer science as a discipline has evolved over the years and has
emerged as a driving force of our socio-economic activities. It has made
continuous inroads into diverse areas — be it business, commerce, science,
technology, sports, health, transportation or education. With the advent
of computer and communication technologies, there has been a paradigm
shift in teaching-learning at the school level. The role and relevance of this
discipline is in focus because the expectations from the school pass-outs
have grown to be able to meet the challenges of the 21st century. Today, we
are living in an interconnected world where computer-based applications
influence the way we learn, communicate, commute or even socialise!
There is a demand for software engineers in various fields like
manufacturing, services, etc. Today, there are a large number of
successful startups delivering different services through software
applications. All these have resulted in generating interest for this subject
among students as well as parents.
Development of logical thinking, reasoning and problem-solving skills
are fundamental building blocks for knowledge acquisition at the higher
level. Computer plays a key role in problem solving with focus on logical
representation or reasoning and analysis.
This textbook focuses on the fundamental concepts and
problem-solving skills while opening a window to the emerging and
advanced areas of computer science. The newly developed syllabus
has dealt with the dual challenge of reducing curricular load as well as
introducing this ever evolving discipline. This textbook also provides space
to Computational Thinking and Artificial Intelligence, which envisaged in
National Education Policy, 2020.
As an organisation committed to systemic reforms and continuous
improvement in the quality of its products, NCERT welcomes comments and
suggestions which will enable us to revise the content of the textbook.
HRUSHIKESH SENAPATY
Director
New Delhi National Council of Educational
August 2020 Research and Training
2024-
25
2024-
25
PRefACe
chapters are required to be solved in a computer and verify with the given
outputs.
Box items are pinned inside the chapters either to explain related
concepts or to describe additional information related to the topic covered
in that section. However, these box-items are not to be assessed through
examinations.
Project Based Learning given as the end includes exemplar projects
related to real-world problems. Teachers are supposed to assign these or
similar projects to be developed in groups. Working in such projects may
promote peer-learning, team spirit and responsiveness.
The chapters have been written by involving practicing teachers
as well as subject experts. Several iterations have resulted into this
book. Thanks are due to the authors and reviewers for their valuable
contribution. I would like to place on record appreciation for Professor
Om Vikas for leading the review activities of the book as well as for his
guidance and motivation to the development team throughout. Comments
and suggestions are welcome.
2024-
25
TexTBOOk DevelOPMenT COMMITTee
CHIEF ADVISOR
Om Vikas, Professor (Retd.), Former Director, ABV-IIITM, Gwalior, M.P.
MEMBERS
Anju Gupta, Freelance Educationist, Delhi
Anuradha Khattar, Assistant Professor, Miranda House, University of Delhi
Chetna Khanna, Freelance Educationist, Delhi
Faheem Masoodi, Assistant Professor, Department of Computer Science,
University of Kashmir
Harita Ahuja, Assistant Professor, Acharya Narendra Dev College, University
of Delhi
Mohini Arora, HOD, Computer Science, Air Force Golden Jubilee Institute,
Subroto Park, Delhi
Mudasir Wani, Assistant Professor, Govt. College for Women Nawakadal,
Sri Nagar, Jammu and Kashmir
Naeem Ahmad, Assistant Professor, Madanapalle Institute of Technology
and Science, Madanapalle, Andhra Pradesh
Purvi Kumar, Co-ordinator, Computer Science Department, Ganga
International School, Rohtak Road, Delhi
Priti Rai Jain, Assistant Professor, Miranda House, University of Delhi
Sangita Chadha, HOD, Computer Science, Ambience Public School,
Safdarjung Enclave, Delhi
Sharanjit Kaur, Associate Professor, Acharya Narendra Dev College,
University of Delhi
MEMBER-COORDINATOR
Rejaul Karim Barbhuiya, Assistant Professor, CIET, NCERT, Delhi
2024-
25
AcknOWLeDGemenTs
2024-
25
COnTenTs
FOREWORD iii
PREFACE v
CHAPTER 1 EXCEPTION HANDLING IN PYTHON 1
1.1 Introduction 1
1.2 Syntax Errors 1
1.3 Exceptions 3
1.4 Built-in Exceptions 3
1.5 Raising Exceptions 4
1.6 Handling Exceptions 7
1.7 Finally Clause 13
CHAPTER 3 STACK 39
3.1 Introduction 39
3.2 Stack 40
3.3 Operations on Stack 42
3.4 Implementation of Stack in Python 43
3.5 Notations for Arithmetic Expressions 46
3.6 Conversion from Infix to Postfix Notation 47
3.7 Evaluation of Postfix Expression 49
CHAPTER 4 QUEUE 53
4.1 Introduction to Queue 53
4.2 Operations on Queue 55
2024-
25
4.3 Implementation of Queue using Python 56
4.4 Introduction to Deque 59
4.5 Implementation of Deque Using Python 61
CHAPTER 5 SORTING 67
5.1 Introduction 67
5.2 Bubble Sort 68
5.3 Selection Sort 71
5.4 Insertion Sort 74
5.5 Time Complexity of Algorithms 77
CHAPTER 6 SEARCHING 81
6.1 Introduction 81
6.2 Linear Search 82
6.3 Binary Search 85
6.4 Search by Hashing 90
2024-
25
xi
2024-
25
13.4 Project Descriptions 245
2024-
25
2024-
25
h a pter
C
Exception
1 Handling in
Python
In this Chapter
» Introduction
» Syntax Errors
» Exceptions 1.1 INTRODUCTION
» Built-in Exceptions Sometimes while executing a Python program, the
» Raising Exceptions program does not execute at all or the program
» Handling Exceptions executes but generates unexpected output or
» Finally Clause
behaves abnormally. These occur when there are
syntax errors, runtime errors or logical errors in
the code. In Python, exceptions are errors that
get triggered automatically. However, exceptions
can be forcefully triggered and handled through
program code. In this chapter, we will learn
about exception handling in Python programs.
2024-
25
rerun the program. When a syntax error is encountered
while working in shell mode, Python displays the name
of the error and a small description about the error as
shown in Figure 1.1.
except ValueError:
print ("Only INTEGERS should be entered")
else:
print ("The result of division operation is ", quotient)
Output:
SUMMARY
• Syntax errors or parsing errors are detected when
we have not followed the rules of the particular
programming language while writing a program.
EXERCISE
1.
“Every syntax error is an exception but every exception
cannot be a syntax error.” Justify the statement.
2. When are the following built-in exceptions raised? Give
examples to support your answers.
a) ImportError
b) IOError
c) NameError
d) ZeroDivisionError
3. What is the use of a raise statement? Write a code to
accept two numbers and display the quotient.
Appropriate exception should be raised if the user enters
the second number (denominator) as zero (0).
4. Use assert statement in Question No. 3 to test the
division expression in the program.
5. Define the following:
a) Exception Handling
b) Throwing an exception
c) Catching an exception
6. Explain catching exceptions using try and except block.
7. Consider the code given below and fill in the blanks.
print (" Learning Exceptions...")
try:
num1= int(input ("Enter the first
number")) num2=int(input("Enter the second
number")) quotient=(num1/num2)
print ("Both the numbers entered were correct")
except : # to enter only integers
print (" Please enter only numbers")
except : # Denominator should not be zero
print(" Number 2 should not be zero")
else:
print(" Great .. you are a good programmer")
: # to be executed at the end
print(" JOB OVER... GO GET SOME REST")
In this Chapter
» Introduction to Files
» Types of Files
» Opening and Closing a 2.1 INTRODUCTION TO FILES
Text File
We have so far created programs in Python that
» Writing to a Text File accept the input, manipulate it and display the
» Reading from a Text File output. But that output is available only during
» Setting Offsets in a File execution of the program and input is to be
» Creating and Traversing a entered through the keyboard. This is because
Text File the variables used in a program have a lifetime
that lasts till the time the program is under
» The Pickle Module
execution. What if we want to store the data that
were input as well as the generated output
permanently so that we can reuse it later?
Usually, organisations would want to
permanently store information about
employees, inventory, sales, etc. to avoid
repetitive tasks of entering the same data.
Hence, data are stored permanently on secondary
storage devices for reusability. We store Python
programs written in script mode with a .py
extension. Each program is stored on the
secondary device as a file. Likewise, the data
entered, and the output can be stored
2024-
25
permanently into a file.
2024-
25
So, what is a file? A file is a named location on a
secondary storage media where data are permanently
Text files contain stored for later access.
only the ASCII
equivalent of the
contents of the 2.2. TYPES OF FILES
file whereas a
Computers store every file as a collection of 0s and 1s
.docx file contains
many additional i.e., in binary form. Therefore, every file is basically
information like just a series of bytes stored one after the other. There
the author's name, are mainly two types of data files — text file and
page settings, font binary file. A text file consists of human readable
type and size, date characters, which can be opened by any text editor. On
of creation and
the other hand, binary files are made up of non-human
modification, etc.
readable characters and symbols, which require specific
programs to access its contents.
2.2.1 Text file
A text file can be understood as a sequence of characters
consisting of alphabets, numbers and other special
symbols. Files with extensions like .txt, .py, .csv, etc.
are some examples of text files. When we open a text file
using a text editor (e.g., Notepad), we see several lines
of text. However, the file contents are not stored in such
a way internally. Rather, they are stored in sequence
of bytes consisting of 0s and 1s. In ASCII, UNICODE or
Activity 2.1
any other encoding scheme, the value of each character
Create a text file using of the text file is stored as bytes. So, while opening a
notepad and write text file, the text editor translates each ASCII value
your name and save it.
Now, create a .docx file and shows us the equivalent character that is readable
using Microsoft Word by the human being. For example, the ASCII value 65
and write your name (binary equivalent 1000001) will be displayed by a text
and save it as well. editor as the letter ‘A’ since the number 65 in ASCII
Check and compare character set represents ‘A’.
the file size of both the
files. You will find that Each line of a text file is terminated by a special
the size of .txt file is character, called the End of Line (EOL). For example,
in bytes whereas the default EOL character in Python is the newline (\
that of .docx is in
KBs. n). However, other characters can be used to indicate
EOL. When a text editor or a program interpreter
encounters the ASCII equivalent of the EOL character,
it displays the remaining file contents starting from a
new line. Contents in a text file are usually separated
by whitespace, but comma (,) and tab (\t) are also
commonly used to separate values in a text file.
<a> Opens the file in append mode. If the file doesn’t exist, then End of the file
a new file will be created.
<a+> or <+a> Opens the file in append and read mode. If the file doesn’t End of the file
exist, then it will create a new file.
['Hello', 'everyone']
['Writing', 'multiline', 'strings']
['This', 'is', 'the', 'third', 'line']
In the output, each string is returned as elements
of a list. However, if splitlines() is used instead of split(),
then each line is returned as element of a list, as shown
in the output below:
>>> for line in d:
words=line.splitlines()
print(words)
['Hello everyone']
['Writing multiline strings']
['This is the third line']
Let us now write a program that accepts a string
from the user and writes it to a text file. Thereafter,
the same program reads the text file and displays it on
the screen.
Program 2-1 Writing and reading to a text file
fileobject=open("report.txt", "w+")
print ("WRITING DATA IN THE FILE")
print() # to display a blank line
while True:
line= input("Enter a sentence ")
fileobject.write(line) fileobject.write('\
n')
choice=input("Do you wish to enter more data? (y/n): ")
if choice in ('n','N'): break
print("The byte position of file object is ",fileobject.tell())
fileobject.seek(0) #places file object at beginning of file
print()
print("READING DATA FROM THE FILE")
str=fileobject.read()
print(str)
fileobject.close()
In Program 2-5, the file will be read till the time end
of file is not reached and the output as shown in below
is displayed.
Output of Program 2-5:
>>>
RESTART: Path_to_file\Program2-5.py
WRITING DATA IN THE FILE
import pickle
listvalues=[1,"Geetika",'F', 26]
fileobject=open("mybinary.dat", "wb")
pickle.dump(listvalues,fileobject)
fileobject.close()
import pickle
print("The data that were stored in file are:
") fileobject=open("mybinary.dat","rb")
objectvar=pickle.load(fileobject)
fileobject.close()
print(objectvar)
Program 2-8 To perform basic operations on a binary file using pickle module
RECORD No. 1
Employee number : 11
Employee Name : D N Ravi
Basic Salary : 32600
Allowances : 4400
TOTAL SALARY : 37000
Do you wish to enter more records (y/n)? y
RECORD No. 2
Employee number : 12
Employee Name : Farida Ahmed
Basic Salary : 38250
Allowances : 5300
TOTAL SALARY : 43550
Do you wish to enter more records (y/n)? n
Record entry OVER
Record Number : 1
[11, 'D N Ravi', 32600, 4400, 37000]
Record Number : 2
[12, 'Farida Ahmed', 38250, 5300, 43550]
>>>
As each employee record is stored as a list in the
file empfile.dat, hence while reading the file, a list is
displayed showing record of each employee. Notice that
in Program 2-8, we have also used try.. except block to
handle the end-of-file exception.
SUMMARY
• A file is a named location on a secondary storage
media where data are permanently stored for
later access.
• A text file contains only textual information
consisting of alphabets, numbers and other
EXERCISE
1. Differentiate between:
a) text file and binary file
b) readline() and readlines()
c) write() and writelines()
3. Write the file mode that will be used for opening the
following files. Also, write the Python statements to open
the following files:
a) a text file “example.txt” in both read and write mode
b) a binary file “bfile.dat” in write mode
c) a text file “try.txt” in append and read mode
d) a binary file “btry.dat” in read only mode.
In this Chapter
» Introduction
» Stack
» Operations on Stack 3.1 INTRODUCTION
» Implementation of Stack We have learnt about different data types in
in Python Python for handling values in Class XI. Recall
» Notations for Arithmetic that String, List, Set, Tuple, etc. are the sequence
Expressions data types that can be used to represent
» Conversion From Infix To collection of elements either of the same type or
Postfix Notation different types. Multiple data elements are
» Evaluation of Postfix grouped in a particular way for faster
Expression accessibility and efficient storage of data. That is
why we have used different data types in python
for storing data values. Such grouping is referred
as a data structure.
A data structure defines a mechanism to
store, organise and access data along with
operations (processing) that can be efficiently
performed on the data. For example, string is a
data structure containing a sequence of elements
where each element is a character. On the other
hand, list is a sequence data structure in which
each element may be of different types. We can
2024-
25
apply different
operations like
reversal, slicing,
counting of
2024-
25
elements, etc. on list and string. Hence, a data structure
organises multiple elements in a way so that certain
operations on each element as well as the collective
data unit could be performed easily.
Other important
data structures Stack and Queue are two other popular data
in Computer structures used in programming. Although not directly
Science include available in Python, it is important to learn these
Array, Linked concepts as they are extensively used in a number of
List, Binary Trees, programming languages. In this chapter, we will study
Heaps, Graph,
Sparse Matrix, about stack, its implementation using Python as well as
etc. its applications.
3.2 STACK
We have seen piles of books in the library or stack of
plates at home (Figure 3.1). To put another book or
another plate in such a pile, we always place (add to
the pile) the object at the top only. Likewise, to remove
a book or a plate from such a pile, we always remove
(delete from the pile) the object from the top only. This
is because in a large pile, it is inconvenient to add or
remove an object from in between or bottom. Such an
arrangement of elements in a linear order is called a
A data structure stack. We add new elements or remove existing elements
in which elements
are organised from the same end, commonly referred to as the top of
in a sequence is the stack. It thus follows the Last-In-First-out (LIFO)
called linear data principle. That is, the element which was inserted last
structure. (the most recent element) will be the first one to be taken
out from the stack.
STACK 41
2024-
25
mismatched, the compiler needs to throw an error. To
handle matching of parentheses, stack is used.
STACK 43
2024-
25
NOTES shall use the built-in method append() of list to
add an element to the stack that always adds at the
end of the list. As there is no limit on the size of list
in Python, the implemented stack will never be full
unless there is no more space available in memory.
Hence, we will never face ‘overflow’ (no space for
new element) condition for stack.
def opPush(glassStack,element):
glassStack.append(element)
• A function named size to read the number of
elements in the glassStack. We will use the len()
function of list in Python to find the number of
elements in the glassStack.
def size(glassStack):
return len(glassStack)
• A function named top to read the most recent element
(TOP) in the glassStack.
def top(glassStack):
if isEmpty(glassStack):
print('Stack is empty')
return None
else:
x =len(glassStack)
element=glassStack[x-1]
return element
• A function named opPop to delete the topmost
element from the stack. It takes one parameter - the
name of the stack (glassStack) from which element
is to be deleted and returns the value of the deleted
element. The function first checks whether the stack
is empty or not. If it is not empty, it removes the
topmost element from it. We shall use the built-
in method pop() of Python list that removes the
element from the end of the list.
def opPop(glassStack):
if isEmpty(glassStack):
print('underflow')
return None
else:
return(glassStack.pop())
STACK 45
2024-
25
NOTES #delete all elements from stack
while True:
item=opPop(glassStack)
if item == None:
print("Stack is empty now")
break
else:
print("Popped element is",item)
STACK 47
2024-
25
Step 4: IF character is a left parenthesis THEN PUSH on the Stack
ELSE IF character is a right parenthesis
THEN POP the elements from the Stack and append to string
postExp until the corresponding left parenthesis is popped
while discarding both left and right parentheses
ELSE IF character is an operator
THEN IF its precedence is lower than that of operator at the top of Stack
THEN POP elements from the Stack till an
operator with precedence less than the current
operator is encountered and append to string
postExp before pushing this operator on the
postStack
ELSE PUSH operator on the Stack
ELSE Append the character to postExp
Step 5: Pop elements from the Stack and append to postExp until Stack is empty
Step 6: OUTPUT postExp
Example 3.1
Let us now use this algorithm to convert a given infix
expression (x + y)/(z*8) into equivalent postfix
expression using a stack. Figure 3.3 shows the steps to
be followed on encountering an operator or an
operand in the given infix expression. Note here that
stack is used to track the operators and parentheses,
and a string variable contains the equivalent postfix
expression. Initially both are empty. Each character in
the given infix expression is processed from left to
right and the appropriate action is taken as detailed in
the algorithm. When each character in the given infix
expression has been processed, the string will contain
the equivalent postfix expression.
SYMBOL : ( x + y
Initial
Stack
+ +
(Empty)
( ( ( (
POSTFIX
empty x x xy
STRING (postExp)
STACK 49
2024-
25
the popped elements and PUSH the computed value onto
the Stack
Step 4: IF Stack has a single element
THEN POP the element and OUTPUT as the net result
ELSE OUTPUT “Invaild Postfix expression”
Example 3.2
Figure 3.4 shows the step-by-step process of evaluation
of the postfix expression 7 8 2 * 4 / + using Algorithm
3.2 .
SYMBOL : 7 8 2
ACTION : PUSH PUSH PUSH
Initial
Stack 2
(Empty) 8 8
7 7 7
SYMBOL : * 4 /
4
16 16 4
7 7 7
SYMBOL : + End of
Input
Expression
Final
Stack Result = 11
(Empty)
11
EMPTY
STACK 51
2024-
25
NOTES
EXERCISE
1. State TRUE or FALSE for the following cases:
a) Stack is a linear data structure
b) Stack does not follow LIFO rule
c) PUSH operation may result into underflow condition
d) In POSTFIX notation for expression, operators are
placed after operands
2. Find the output of the following code:
a) result=0
numberList=[10,20,30]
numberList.append(40)
result=result+numberList.pop()
result=result+numberList.pop()
print(“Result=”,result)
b) answer=[]; output=''
answer.append('T')
answer.append('A')
answer.append('M')
ch=answer.pop()
output=output+ch
ch=answer.pop()
output=output+ch
ch=answer.pop()
output=output+ch
print(“Result=”,output)
3. Write a program to reverse a string using stack.
4. For the following arithmetic expression:
((2+3)*(4/2))+2
Show step-by-step process for matching parentheses
using stack data structure.
5. Evaluate following postfix expressions while showing
status of stack after each operation given A=3, B=5,
C=1, D=4
a) A B + C *
b) A B * C / D *
6. Convert the following infix notations to postfix notations,
showing stack and string contents at each step.
a) A + B - C * D
b) A * (( C + D)/E)
7. Write a program to create a Stack for storing only odd
numbers out of all the numbers entered by the user.
Display the content of the Stack along with the largest
odd number in the Stack. (Hint. Keep popping out the
elements from stack and maintain the largest element
retrieved so far in a variable. Repeat till Stack is empty)
In this Chapter
» Introduction to Queue
» Operations on Queue
» Implementation of Queue
4.1 INTRODUCTION TO QUEUE
using Python
» Introduction to Deque In the previous chapter we learned about a data
structure called Stack, which works on Last-In-
» Implementation of Deque
First-Out (LIFO) principle. In this chapter, we
using Python
will learn about another data structure called
Queue which works on First-In-First-Out (FIFO)
principle. Queue is an ordered linear list of
elements, having
different ends for adding
and removing elements
Cashier Next in it.
Examples of queue
in our everyday life
include students
standing in a queue
for morning assembly,
customers forming a
queue at the cash
counter in a bank
(Figure 4.1), vehicles
2024-
25
q ueued at fuel pumps
Figure 4.1: Queue of people at a bank (Figure 4.2), etc.
h a pter
C
4 Queu
e
2024-
25
NOTES
QUEUE 55
2024-
25
• PEEK : used to view elements at the front of the
queue, without removing it from the queue.
While using a
list to implement • IS FULL : used to check whether any more
queue, we can elements can be added to the queue or not, to avoid
designate either Overflow exceptions while performing enqueue
end of the list
operation.
as Front or Rear
of the queue. Figure 4.3 shows the various stages of a simple
But we have to
queue containing alphabets. In the figure, Front of the
fix either of the
ends index[0] queue is on the left and Rear on the right.
or index[n-1] as
Front and fix the Operation performed Status of queue after operation
opposite end as enqueue(z) F Z R
Rear. enqueue(x) F Z X R
enqueue(c) F Z X C R
dequeue() F X C R
enqueue(v) F X C V R
dequeue() F C V R
dequeue() F V R
QUEUE 57
2024-
25
Activity 4.1 Let us consider the example of a queue that people
How can you avoid form while waiting at a bank cash counter. Usually,
printing of None, following are the events that occur in queue:
when trying to • Two friends come together and go to the cash
print an empty
queue? counter, i.e. they form a queue - enqueue operation
is performed two times.
• As soon as the person at the front is serviced, he will
be removed from the queue - thus dequeue operation
is performed. Cashier calls Next to serve the next
Activity 4.2
person who is now at the front of the queue.
What if the content of
the complete queue • Cashier wants to know the length of the queue - size
is to be listed? of the queue is checked.
Write a function
for it. • Meanwhile, a few more people walk in the bank,
and three of them join the queue at the cash
counter, i.e. enqueue happens 3 times.
• Another person gets served and leaves the counter,
i.e. dequeue is performed. Cashier calls Next to serve
another person.
• The Next three people get served one after another,
i.e. dequeue is performed thrice.
• Cashier calls Next and realises that there are no more
people to be served - underflow situation happens
Now, let us write the code for the above scenario of
the bank.
Program 4-1
myQueue = list()
# each person to be assigned a code as P1, P2, P3,...
element = input("enter person’s code to enter in queue :”)
enqueue(myQueue,element)
element = input("enter person’s code for insertion in queue :")
enqueue(myQueue,element)
print("person removed from queue is:", dequeue(myQueue))
print(“Number of people in the queue is :”,size(myQueue))
element = input("enter person’s code to enter in queue :")
enqueue(myQueue,element)
element = input("enter person’s code to enter in queue :")
enqueue(myQueue,element)
element = input("enter person’s code to enter in queue :")
enqueue(myQueue,element)
(insertion) Push
Push (insertion)
(deletion) Pop
Pop (deletion)
Front Rear
Figure 4.4: Basic deque structure displaying head and tail to implement stack or queue.
m a d a insertrear
(m)
Front Rear
Figure 4.5: Status of Deque after 4th iteration
removefront a d a insertrear
(m)
(m)
Front Rear
Figure 4.6: Status of Deque after removing one character from both
the ends.
QUEUE 61
2024-
25
NOTES • A statement to create deque, with name myDeque.
myDeque = list()
def insertFront(myDeque,element):
myDeque.insert(0,element)
def getFront(myDeque):
if not (isEmpty(myDeque)):
return myDeque[0]
else:
print("Queue underflow")
def getRear(myDeque):
if not (isEmpty(myDeque)):
return myDeque[len(myDeque)-1]
else:
print ("Queue underflow")
def insertRear(myDeque,element):
myDeque.append(element)
def isEmpty(myDeque):
if len(myDeque) == 0:
return True
else:
return False
def deletionRear(myDeque):
if not isEmpty(myDeque):
return myDeque.pop()
else:
print("Queue underflow")
def deletionFront(myDeque):
if isEmpty(myDeque):
QUEUE 63
2024-
25
print("Queue underflow")
else:
return myDeque.pop(0)
def main():
dQu = list()
choice = int(input('enter 1 to use as normal queue 2 otherwise
: '))
if choice == 1:
element = input("data for insertion at rear ")
insertRear(dQu,element)
element = getFront(dQu)
print("data at the beginning of queue is ", element)
element = input("data for insertion at front ")
insertRear(dQu,element)
print('data removed from front of queue is ', deletionFront(dQu))
print('data removed from front of queue is ', deletionFront(dQu))
Output
enter 1 to use as normal queue 2 otherwise : 1
data for insertion at rear 23
data at the beginning of queue is 23
data for insertion at rear 45
data removed from front of queue is 23
data removed from front of queue is 45
Queue underflow
data removed from front of queue is None
SUMMARY
• Queue is an ordered linear data structure,
following FIFO strategy.
• Front and Rear are used to indicate beginning
and end of queue.
• In Python, the use of predefined methods takes
care of Front and Rear.
EXERCISE
1.
Fill in the blank
a) is a linear list of elements
in which insertion and deletion takes place from
different ends.
b) Operations on a queue are performed in
order.
c) Insertion operation in a queue is called
and deletion operation in a queue is called
.
d) Deletion of elements is performed from
end of the queue.
e) Elements ‘A’,’S’,’D’ and ‘F’ are present in the queue, and
they are deleted one at a time,
is the sequence of element received.
f) is a data structure where elements
can be added or removed at either end, but not in
the middle.
g) A deque contains ‘z’,’x’,’c’,’v’ and ‘b’ . Elements
received after deletion are ‘z’,’b’,’v’,’x’ and ‘c’.
is the sequence of deletion
operation performed on deque.
QUEUE 65
2024-
25
NOTES 4. Write a menu driven python program using queue, to
implement movement of shuttlecock in it’s box.
In this Chapter
» Introduction
» Bubble Sort
» Selection Sort
» Insertion Sort 5.1 INTRODUCTION
» Time Complexity of
Algorithms Sorting is the process of ordering or arranging a
given collection of elements in some particular
order. We can sort a collection of numbers in
ascending (increasing) or descending (decreasing)
order. If the collection is of strings, we can sort it
in an alphabetical order (a-z or z-a) or according
to the length of the string. For example, words in
a dictionary are sorted in alphabetical order;
seats in an examination hall are ordered
according to candidates’ roll number. We can
also sort a list of students based on their height
or weight.
Imagine finding the meaning of a word from
a dictionary that is not ordered. We will have to
search for the word on each page till we find the
word, which will be very tedious. That is why
dictionaries have the words in alphabetical order
2024-
25
and it ease
the process of
searching.
2024-
25
Sorting a large number of items can take a substantial
Can you identify amount of time. However, this extra time (called
other examples overhead) is worth when compared to the amount of
where sorting plays
an important role in
time needed to find an element from an unsorted list.
computers? Sorting is an important area of study in computer
science, and many sorting algorithms have been
developed and analysed from their performance point of
view. In this chapter, we will learn about three sorting
methods and implement them using Python. Bubble sort
is discussed in section 5.2, followed by discussion on
selection sort and insertion sort in section 5.3 and 5.4,
respectively
8 7 13 1 -9 4 7 8 1 -9 4 13
No Change Swap
7 8 13 1 -9 4 7 8 1 -9 4 13
Swap Swap
7 8 13 1 -9 4 7 1 8 -9 4 13
Swap Swap
7 8 1 13 -9 4 7 1 -9 8 4 13
Swap Swap
7 8 1 -9 13 4 7 1 -9 4 8 13
7 8 1 -9 4 13
7 1 -9 4 8 13 1 -9 4 7 8 13
Swap No Change
1 7 -9 4 8 13 -9 1 4 7 8 13
Swap
1 -9 7 4 8 13 -9 1 4 7 8 13
Swap
1 -9 4 7 8 13
SORTING 69
2024-
25
Comparison in Pass 5
Swap
-9 1 4 7 8 13
def bubble_Sort(list1):
n = len(list1)
for i in range(n): # Number of passes
for j in range(0, n-i-1):
# size -i-1 because last i elements are already sorted
#in previous passes
if list1[j] > list1[j+1] :
# Swap element at jth position with (j+1)th position
list1[j], list1[j+1] = list1[j+1], list1[j]
numList = [8, 7, 13, 1, -9, 4]
bubble_Sort(numList)
SORTING 71
2024-
25
numList 8 7 13 1 -9 4
Index
0 1 2 3 4 5
Comparison in Pass 1
Comparison in Pass 2
8 7 13 1 -9 4 -9 8 7 13 1 4
8 7 13 1 -9 4 -9 8 7 13 1 4
8 7 13 1 -9 4 -9 8 7 13 1 4
8 7 13 1 -9 4 -9 8 7 13 1 4
-9 8 7 13 1 4
8 7 13 1 -9 4
Swap
8 7 13 1 -9 4
-9 1 7 13 8 4
Swa
p
-9 8 7 13 1 4
-9 1 7 13 8 4 -9 1 4 13 8 7
-9 1 7 13 8 4 -9 1 4 13 8 7
-9 1 7 13 8 4 -9 1 4 13 8 7
Swap
-9 1 7 13 8 4 -9 1 4 7 8 13
Swap
-9 1 4 13 8 7
SORTING 73
2024-
25
Program 5-2 Implementation of selection sort using Python.
def selection_Sort(list2):
flag = 0 #to decide when to swap
n=len(list2)
for i in range(n): # Traverse through all list elements
min = i
for j in range(i + 1, len(list2)): #the left elements
#are already sorted in previous passes
if list2[j] < list2[min]: # element at j is smaller
#than the current min element
min = j
flag = 1
if flag == 1 : # next smallest element is found
list2[min], list2[i] = list2[i], list2[min]
Output:
The sorted list is :
-9 1 4 7 8 13
numList 8 7 13 1 -9 4
Index
0 1 2 3 4 5
8 7 13 1 -9 4 7 8 13 1 -9 4
Swap
8 7 13 1 -9 4 7 8 13 1 -9 4
7 8 13 1 -9 4
7 8 13 1 -9 4 1 7 8 13 -9 4
Swap Swap
7 8 1 13 -9 4 1 7 8 -9 13 4
Swap
Swap
7 1 8 13 -9 4 1 7 -9 8 13 4
Swap
1 7 8 13 -9 4 -9 1 7 8 13 4
-9 1 7 8 13 4
SORTING 75
2024-
25
Comparison in Pass 5
Swap
Indicates element(s) in sorted list
-9 1 7 8 13 4
Swap
-9 1 7 8 4 13
Swap
-9 1 7 4 8 13
No Change
-9 1 4 7 8 13
-9 1 4 7 8 13
Figure 5.3: Comparisons done in different passes of Insertion sort
Activity 5.4
Step 3: temp = numList[i]
Consider a list of 10 Step 4: SET j = i-1
elements:
Array = Step 5: WHILE j> = 0 and numList[j]>temp,REPEAT
[7,11,3,10,17,23,1,4,21,5] STEPS 6 to 7
Determine the partially
sorted list after Step 6: numList[j+1] = numList[j]
three complete
passes of Step 7: SET j=j-1
insertion sort.
Step 8: numList[j+1] = temp #insert
temp at position j
Step 9: set i=i+1
def insertion_Sort(list3):
n= len(list3)
for i in range(n): # Traverse through all elements
temp = list3[i]
j = i-1
while j >=0 and temp< list3[j] :
list3[j+1] = list3[j]
j = j-1
list3[j+1] = temp
Output:
The sorted list is :
-9 1 4 7 8 13
SUMMARY
• The process of placing or rearranging a collection
of elements into a particular order is known as
sorting.
• Bubble sort is the simplest sorting algorithm
that works by repeatedly swapping the adjacent
elements in case they are unordered in n-1 passes.
• In Selection Sort, the smallest element is selected
from the unsorted array and swapped with the
EXERCISE
1. Consider a list of 10 elements:
numList =[7,11,3,10,17,23,1,4,21,5].
Display the partially sorted list after three complete
passes of Bubble sort.
List 1 : 63 42 21 9
List 2: 11 7 5 3 2
SORTING 79
2024-
25
NOTES 5. All the branches of XYZ school conducted an aptitude
test for all the students in the age group 14 - 16. There
were a total of n students. The marks of n students are
stored in a list. Write a program using a user defined
function that accepts a list of marks as an argument
and calculates the ‘xth’ percentile (where x is any number
between 0 and 100).You are required to perform the
following steps to be able to calculate the ‘xth’ percentile.
Note: Percentile is a measure of relative performance i.e. It is
calculated based on a candidate’s performance with respect
to others. For example : If a candidate's score is in the 90th
percentile, that means she/he scored better than 90% of
people who took the test.
Index in numList 0 1 2 3 4 5 6
Value 8 -4 7 17 0 2 19
Index in numList 0 1 2 3 4 5 6
Value 17 8 -4 7 0 2 19
Table 6.4 Linear search for key 17 in numList given in Table 6.3
numList[index]=
index index < n index=index+1
key
0 0 < 7 ? Yes 17 = 17? Yes 1
SEARCHING 83
2024-
25
Let us now assume another case, where the key
being searched is not present in the list. For example,
we are searching for key = 10 in the numList.
In this case also, the algorithm has to compare each
element in the list till the end to display ‘Element is
not found in the list’. Thus, if the key is not present in
the list, the linear search algorithm will have to make
n comparisons. This again is a case where maximum
work is done. Let us now understand the program of
a Linear Search. It takes a list of elements and the key
to be searched as input and returns either the position
of the element in the list or display that the key is not
present in the list.
Program 6-1 Linear Search
Output
How many elements in your list? 4
Enter each element and press enter:
12
23
3
-45
The List contents are: [12, 23, 3, -45]
Enter the number to be searched:23
Number 23 is present at position 2
SEARCHING 85
2024-
25
If the middle element is greater than the key it
means that if the key is present in the list, it must
We are using the surely be in the first half. We can thus straight away
term iteration and
ignore the second half of the list and repeat the
not comparison
in binary search, searching process only in the first half.
because after If the middle element is less than the key, it means
every unsuccessful
if the key is present in the list, it must be in the second
comparison, we
change the search half. We can thus straight away ignore the first half of
area redefining the list and repeat the searching process only in the
the first, mid and second half. This splitting and reduction in list size
last position before continued till the key is either found or the remaining
making subsequent
list consists of only one item. If that item is not the
comparisons.
key, then the search is unsuccessful as the key is not
in the list.
Thus, it is evident that unlike linear search of
elements one-by-one, we can search more efficiently
using binary search provided the list from which we
want to search is arranged in some order. That is, the
list needs to be sorted.
Activity 6.3
If the list to be searched contains an even number
Consider the numList of elements, the mid value is calculated using the floor
[17, 8, -4, 7, 0, 2,
19]. Sort it using division (//) operator. If there are 10 elements in the list,
the sort() function of then the middle position (mid) = 10//2 = 5. Therefore,
Python’s Lists. Now the sixth element in the list is considered the middle
apply binary search element as we know that the first element in list has
to search for the index value 0. If required, the list is further divided into
key 7. Determine
the number two parts where the first half contains 5 elements and
of iterations the second half contains 4 elements.
required. It is interesting to note that the intermediate
comparisons which do not find the key still give us
information about the part of the list where the key
may be found! They reveal whether the key is before or
after the current middle position in the list, and we use
this information to narrow down or reduce our search
Activity 6.4 area. Thus, each unsuccessful comparison reduces the
Consider a list [-4, 0, number of elements remaining to be searched by half,
2, 7, 8, 17, 19]. Apply hence the name binary search. Let us now discuss the
binary search to find algorithm of binary search.
element -4. Determine
the number of key Given a list numList of n elements and key value K,
comparisons Algorithm 6.2 shows steps for finding position of the
required. key K in the numList using binary search algorithm.
Table 6.6 Working of binary search using steps given in Algorithm 6.2.
first <=
first last mid numList[mid] == K key < Lmid? last
0 14 (0+14)// Not known Not known 0 <= 14?
At Start
2=7 True
0 14 7 17 = 17? Key is
Iteration Yes found. The
1 search
terminates
SEARCHING 87
2024-
25
is the minimum amount of work binary search would
have to do to confirm that a key is present in the list.
Now, let us search for key 2 in the list.
numList = [2,3,5,7,10,11,12,17,19,23,29,3
Activity 6.5 1,37,41,43]
For L = [2,3,5,7,10,1 In the first iteration, we have the mid value as 17.
1,12,17,19,23,29,31, As 2 is smaller than the mid value (17), we have to
37,41,43]. Fill up the search for the first half of the list in the second
Table 6.8 for the given iteration. We now consider only 7 elements. As 2 is
key values 2, 43, 17
and 9. What do you
smaller than the new mid value (7), we have to search
infer from Table 6.8 for the first half of the remaining list in the third
regarding performance iteration. We now consider only 3 elements. Observe
of both the that the number of elements in the numList is halved
algorithms in each time. It reduces from 15 elements in iteration 1
different cases?
to 7 elements in iteration 2, and to 3 elements in
iteration 3. In the 3rd iteration, the algorithm finds
that key 2 is smaller than the new mid value (3), we
have to search in the first half of the remaining list.
The list now has only 1 element in the fourth iteration
and on comparison, it is found that the element is the
same as key. Hence, the search terminates successfully
and returns the position of key. Steps followed for
binary search are given in Table 6.7.
Table 6.7 Searching key = 2 in the numList using binary search
numList]
first last mid mid] == K K < numList[mid] first <= last
Output
Create a list by entering elements in ascending order
press enter after each element, press -999 to stop
1
3
4
5
-999
Enter the number to be searched: 4
4 is found at position 3
SEARCHING 89
2024-
25
6.3.1 Applications of Binary Search
• Binary search has numerous applications including
– searching a dictionary or a telephone directory,
finding the element with minimum value or maximum
value in a sorted list, etc.
• Modified binary search techniques have far
reaching applications such as indexing in databases,
implementing routing tables in routers, data
compression code, etc.
Element 34 16 2 93 80 77 51
index 0 1 2 3 4 5 6 7 8 9
SEARCHING 91
2024-
25
print("The hash table contents are: " )
for i in range(0,len(hashTable)):
print("hashindex=", i," , value =", hashTable[i])
position = hashFind(key,hashTable)
if position is None:
print("Number",key,"is not present in the hash table")
else:
print("Number ",key," present at ",position, " position")
Output:
We have created a hashTable of 10 positions:
[None, None, None, None, None, None, None, None, None, None]
The given list is [34, 16, 2, 93, 80, 77, 51]
The hash table contents are:
hashindex= 0 , value = 80
hashindex= 1 , value = 51
hashindex= 2 , value = 2
hashindex= 3 , value = 93
hashindex= 4 , value = 34
hashindex= 5 , value = None
hashindex= 6 , value = 16
hashindex= 7 , value = 77
hashindex= 8 , value = None
hashindex= 9 , value = None
Enter the number to be searched:16
Number 16 present at 7 position
6.4.1 COLLISION
The hashing technique works fine if each element of the
list maps to a unique location in the hash table. Consider
a list [34, 16, 2, 26, 80]. While applying the
hash function say, list [i]%10, two elements (16 and
26) would have a hash value 6. This is a problematic
situation, because according to our definition, two or
more elements cannot be in the same position in the
list. This situation is called collision in hashing.
We must have a mechanism for placing the other
items with the same hash value in the hash table. This
process is called collision resolution. Collision can be
resolved in many ways, but it is beyond the scope of
this book to discuss collision resolution methods.
SUMMARY
• Searching means trying to locate a particular
element called key in a collection of elements.
Search specifies whether that key is present in
the collection or not. Also, if the key is present, it
tells the position of that key in the given
collection.
• Linear search checks the elements of a list, one at
a time, without skipping any element. It is useful
when we need to search for an item in a small
unsorted list, but it is slow and time-consuming
when the list contains a large number of items.
The time taken to search the list increases as the
size of the list increases.
• Binary search takes a sorted/ordered list and
divides it in the middle. It then compares the
middle element with the key to be searched. If
the middle element matches the key, the search
is declared successful and the program ends. If
the middle element is greater than the key, the
search repeats only in the first half of the list.
If the middle element is lesser than the key, the
search repeats only in the second half of the list.
SEARCHING 93
2024-
25
NOTES This splitting and reduction in list size continue
till the key is found or the remaining list consists
of only one item.
• In binary search, comparisons that do not find
the key still give us idea about the location
where the key may probably be found! They
reveal whether the key is before or after the
current middle position in the list, and we can use
this information to narrow down or reduce our
searching efforts.
• Hash based searching requires only one key
comparison to discover the presence or absence
of a key, provided every element is present at its
designated position decided by a hash function.
It calculates the position of the key in the list
using a formula called the hash function and the
key itself.
• When two elements map to the same slot in the
hash table, it is called collision.
• The process of identifying a slot for the second
and further items in the hash table in the event
of collision, is called collision resolution.
• A perfect hash function maps every input key
to a unique index in the hash table. If the hash
function is perfect, collisions will never occur.
1. Using linear search determine the position of 8, 1, 99
and 44 in the list:
E XERCISE
[1, -2, 32, 8, 17, 19, 42, 13, 0, 44]
SEARCHING 95
2024-
25
NOTES 7. Estimate the number of key comparisons required in
binary search and linear search if we need to find the
details of a person in a sorted database having 230
(1,073,741,824) records when details of the person being
searched lies at the middle position in the database.
What do you interpret from your findings?
In this Chapter
» Introduction to Data
» Data Collection
» Data Storage 7.1 INTRODUCTION TO DATA
» Data Processing Many a time, people take decisions based on
» Statistical Techniques for certain data or information. For example, while
Data Processing choosing a college for getting admission, one looks
at placement data of previous years of that college,
educational qualification and experience of the
faculty members, laboratory and hostel facilities,
fees, etc. So we can say that identification of a
college is based on various data and their analysis.
Governments systematically collect and record
data about the population through a process
called census. Census data contains valuable
information which are helpful is planning and
formulating policies. Likewise, the coaching staff
of a sports team analyses previous performances
of opponent teams for making strategies. Banks
maintain data about the customers, their
account details and transactions. All these
examples highlight the need of data in various
fields. Data are indeed crucial for decision
making.
2024-
25
In the previous examples, one cannot make
decisions by looking at the data itself. In our example
of choosing a college, suppose the placement cell of the
college has maintained data of about 2000 students
placed with different companies at different salary
packages in the last 3 years. Looking at such data, one
cannot make any remark about the placement of
students of that college. The college processes and
analyses this data and the results are given in the
placement brochure of the college through
summarisation as well as visuals for easy
understanding. Hence, data need to be gathered,
processed and analysed for making decisions.
A knowledge base is In general, data is a collection of characters, numbers,
a store of information and other symbols that represents values of some
consisting of facts, situations or variables. Data is plural and singular of
assumptions and
rules which an AI the word data is “datum”. Using computers, data are
system can use for stored in electronic forms because data processing
decision making. becomes faster and easier as compared to manual data
processing done by people. The Information and
Communication Technology (ICT) revolution led by
computer, mobile and Internet has resulted in
generation of large volume of data and at a very fast
pace. The following list contains some examples of
data that we often come across.
• Name, age, gender, contact details, etc., of a person
• Transactions data generated through banking,
ticketing, shopping, etc. whether online or offline
• Images, graphics, animations, audio, video
• Documents and web pages
• Online posts, comments and messages
• Signals generated by sensors
• Satellite data including meteorological data,
communication data, earth observation data, etc.
2024-
25
Activity 7.1 data is usually stored in computer in a tabular (in rows
Observe Voter Identity and columns) format where each column represents
cards of your family different data for a particular parameter called attribute/
members and identify characteristic/variable and each row represents data
the data fields under of an observation for different attributes. Table 7.1
which data are shows structured data related to an inventory of
organised. Are
they same for kitchen items maintained by a shop.
all?
102
COMPUTER SCIENCE - CLASS XII
2024-
25
get results and after
analysing those results, RAW DATA INFORMATION
Data Processing
we make conclusions or (Numbers/ (In the form
decisions. Text/Image) of table/
chart/text)
We find automated
data processing in
situations like online bill Data Process Cycle
payment, registration Input Processing Output
of complaints, booking
tickets, etc. Figure 7.1 Data Collection Store Reports
illustrates basic steps Data Prepration Retrieve Results
used to process the data Data Entry Classify Processing System
to get the output. Update
Journey start and end stations, Verify login details and check
date of journey, number of tickets availability of berth in that class. If
required, class of travel payment done, issue tickets and Generate ticket with berth and
(Sleeper/AC/other), berth deduct that number from the total coach number, or issue ticket with
preference (if any), passenger available tickets on that coach. a waiting list number
name(s) and age(s), mobile and Allocate PNR number and berths or
email id, payment related details, generate a waiting number for that
etc. ticket.
n
Example 7.1
Assume that height (in cm) of students in a class are as
follows [90,102,110,115,85,90,100,110,110]. Mean or
average height of the class is
(C) Mode
Value that appears most number of times in the given
data of an attribute/variable is called Mode. It is
computed on the basis of frequency of occurrence of
distinct values in the given data. A data set has no mode
if each value occurs only once. There may be multiple
modes in the data if more than one values have same
highest frequency. Mode can be found for numeric as
well as non-numeric data.
Example 7.3
In the list of height of students, mode is 110 as its
frequency of occurrence in the list is 3, which is larger
than the frequency of rest of the values.
7.5.2 Measures of Variability
The measures of variability refer to the spread or
variation of the values around the mean. They are also
called measures of dispersion that indicate the degree of
diversity in a data set. They also indicate difference within
the group. Two different data sets can have the same
mean, median or mode but completely different levels of
dispersion, or vice versa. Common measures of
dispersion or variability are Range and Standard
Deviation.
(A) Range
It is the difference between maximum and minimum
values of the data (the largest value minus the
smallest value). Range can be calculated only for
numerical data. It is a measure of dispersion and
tells about coverage/spread of data values. For
Example 7.5
Let us compute the standard deviation of the height
of nine students that we used while calculating
Mean. The Mean (x) was calculated to be 101.33 cm.
Subtract each value from the mean and take square
of that value. Dividing the sum of square values by
total number of values and taking its square not
gives the standard deviation in data. See Table 7.3
for details.
Table 7.3 Standard deviation of attendance
_ of 9 students
(x _ )2
Height (x) in cm _
x_x x
90 -11.33 128.37 n
(Xi X)2
102 0.67 0.36
i1
Teacher wants to know about the average performance of the whole class in
a test.
Compare height of residents of two cities
Find the popular color for car after surveying the car owners of a small city.
SUMMARY
• Data refer to unorganised facts that can be
processed to generate meaningful result or
information.
• Data can be structured or unstructured.
• Hard Disk, SSD, CD/DVD, Pen Drive, Memory
Card, etc. are some of the commonly used
storage devices.
EXERCISE
1. Identify data required to be maintained to perform the
following services:
a) Declare exam results and print e-certificates
b) Register participants in an exhibition and issue
biometric ID cards
c) To search for an image by a search engine
d) To book an OPD appointment with a hospital in a
specific department
2. A school having 500 students wants to identify
beneficiaries of the merit-cum means scholarship,
achieving more than 75% for two consecutive years
and having family income less than 5 lakh per annum.
Briefly describe data processing steps to be taken by the
to beneficial prepare the list of school.
3. A bank ‘xyz’ wants to know about its popularity among
the residents of a city ‘ABC’ on the basis of number of
bank accounts each family has and the average monthly
account balance of each person. Briefly describe the
steps to be taken for collecting data and what results
can be checked through processing of the collected data.
2024-
25
there is no link or mapping between them. The school
NOTES
will have to write separate programs to access these two
files. This is because data mapping is not supported in
file system. In a more complex system where data files
are generated by different person at different times, files
being created in isolation may be of different formats.
In such case, it is difficult to write new application
programs to retrieve data from different files maintained
at multiple places, as one has to understand the
underlying structure of each file as well.
(E) Data Dependence
Data are stored in a specific format or structure in a file.
If the structure or format itself is changed, all the existing
application programs accessing that file also need to
be changed. Otherwise, the programs may not work
correctly. This is data dependency. Hence, updating the
structure of a data file requires modification in all the
application programs accessing that file.
(F) Controlled Data Sharing
There can be different category of users like teacher,
office staff and parents. Ideally, not every user should
be able to access all the data. As an example, guardians
and office staff can only see the student attendance data
but should not be able to modify/delete it. It means
these users should be given limited access (read only)
to the ATTENDANCE file. Only the teacher should be
able to update the attendance data. It is very difficult to
enforce this kind of access control in a file system while
accessing files through application programs.
Query Query
Query Result
Query Result
DBMS Software processes Query
DBMS Software access database and its definition
Student
Database
Guardian Catalog
Attendance
Table 8.7 Relation schemas along with its description of Student Attendance
database
Relation Scheme Description of attributes
STUDENT(RollNumber, RollNumber: unique id of the student
SName, SDateofBirth, SName: name of the student
GUID) SDateofBirth: date of birth of the student
GUID: unique id of the guardian of the student
ATTENDANCE AttendanceDate: date on which attendance is taken
(AttendanceDate, RollNumber: roll number of the student
RollNumber, AttendanceStatus: whether present (P) or absent(A)
AttendanceStatus) Note that combination of AttendanceDate and RollNumber will be unique
in each record of the table
GUARDIAN(GUID, GUID: unique id of the guardian
GName, GPhone, GName: name of the guardian
GAddress) GPhone: contact number of the guardian
GAddress: contact address of the guardian
Relation
State
101010101010 Himanshu Shah 4726309212 26/77, West Patel Nagar, Ahmedabad
333333333333 Danny Dsouza S -13, Ashok Village, Daman
466444444666 Sujata P. 3801923168 HNO-13, B- block, Preet Vihar, Madurai
Figure 8.5: STUDENTATTENDANCE database with the primary and foreign keys
SUMMARY
• A file in a file system is a container to store data in a computer.
• File system suffers from Data Redundancy, Data Inconsistency, Data
Isolation, Data Dependence and Controlled Data sharing.
• Database Management System (DBMS) is a software to create and
manage databases. A database is a collection of tables.
• Database schema is the design of a database.
• A database constraint is a restriction on the type of data that that can be
inserted into the table.
EXERCISE
1. Give the terms for each of the following:
a) Collection of logically related records.
b) DBMS creates a file that contains description about
the data stored in the database.
c) Attribute that can uniquely identify the tuples in
a relation.
d) Special value that is stored when actual data value is
unknown for an attribute.
e) An attribute which can uniquely identify tuples of the
table but is not defined as primary key of the table.
f) Software that is used to create, manipulate and
maintain a relational database.
2. Why foreign keys are allowed to have NULL values?
Explain with an example.
3. Differentiate between:
a) Database state and database schema
b) Primary key and foreign key
c) Degree and cardinality of a relation
In this Chapter
» Introduction
» Structured Query Language
(SQL)
9.1 INTRODUCTION
» Data Types and
Constraints in MySQL We have learnt about Relational Database
» SQL for Data Definition Management Systems (RDBMS) and its purpose
in the previous chapter. There are many
» SQL for Data
Manipulation
RDBMS such as MySQL, Microsoft SQL Server,
PostgreSQL, Oracle, etc. that allow us to create
» SQL for Data Query a database consisting of relations. These RDBMS
» Data Updation and also allow us to store, retrieve and manipulate
Deletion data on that database through queries. In this
» Functions in SQL chapter, we will learn how to create, populate
» GROUP BY Clause in SQL and query databases using MySQL.
» Operations on Relations
9.2 STRUCTURED QUERY LANGUAGE (SQL)
» Using Two Relations in a
Query One has to write application programs to access
data in case of a file system. However, for database
management systems there are special kinds of
languages called query language that can be used
to access and manipulate data from the database.
The Structured Query Language (SQL) is the
most popular query language used by major
2024-
25
relational
2024-
25
database management systems such as MySQL,
ORACLE, SQL Server, etc.
Activity 9.1 SQL is easy to learn as the statements comprise of
descriptive English words and are not case sensitive.
Find and list other
types of databases We can create and interact with a database using SQL
other than easily. Benefit of using SQL is that we do not have to
RDBMS. specify how to get the data from the database. Rather,
we simply specify what is to be retrieved, and SQL
does the rest. Although called a query language, SQL
can do much more, besides querying. SQL provides
statements for defining the structure of the data,
manipulating data in the database, declaring
constraints and retrieving data from the database in
various ways, depending on our requirements.
In this chapter, we will use the StudentAttendance
discussed in chapter 8 and create a database. We
will also learn how to populate databases with data,
manipulate data and retrieve data from a database
through SQL queries.
9.2.1 Installing MySQL
MySQL is an open source RDBMS software which can
be easily downloaded from the official website https://
dev.mysql.com/downloads. After installing MySQL,
start MySQL service. The appearance of mysql>
prompt (Figure 9.1) means that MySQL is ready to
accept SQL statements.
Table 9.4 Data types and constraints for the attributes of relation GUARDIAN
Attribute Name Data expected to be stored Data type Constraint
GUID Numeric value consisting of 12 digit Aadhaar CHAR (12) PRIMARY KEY
number
GName Variant length string of maximum 20 VARCHAR(20) NOT NULL
characters
GPhone Numeric value consisting of 10 digits CHAR(10) NULL UNIQUE
GAddress Variant length String of size 30 characters VARCHAR(30) NOT NULL
Table 9.5 Data types and constraints for the attributes of relation ATTENDANCE.
Attribute Name Data expected to be stored Data type Constraint
AttendanceDate Date value DATE PRIMARY KEY*
RollNumber Numeric value consisting of maximum 3 INT PRIMARY KEY*
digits FOREIGN KEY
AttendanceStatus ‘P’ for present and ‘A’ for absent CHAR(1) NOT NULL
*means part of composite primary key.
2024-
25
all such cases, we need to change or alter the structure
(schema) of the table by using the alter statement.
(A) Add primary key to a relation
Let us now alter the tables created in Activity 9.4. The
following MySQL statement adds a primary key to the
GUARDIAN relation:
mysql> ALTER TABLE GUARDIAN ADD PRIMARY KEY (GUID);
Query OK, 0 rows affected (1.14 sec)
Records: 0 Duplicates: 0 Warnings: 0
Now let us add the primary key to the
ATTENDANCE relation. The primary key of this
relation is a composite key made up of two attributes -
AttendanceDate and RollNumber.
mysql> ALTER TABLE ATTENDANCE
-> ADD PRIMARY KEY(AttendanceDate, RollNumber);
Query OK, 0 rows affected (0.52 sec)
Activity 9.5 Records: 0 Duplicates: 0 Warnings: 0
2024-
25
mysql> INSERT INTO STUDENT
-> VALUES(3, 'Taleem Shah','2002-02-28', NULL);
Query OK, 1 row affected (0.05 sec)
q
u
e
r
y
r
e
s
u
l
t
,
r
e
n
a
m
e
t
h
e
c
o
l
u
m
n
E
N
a
m
e
a
s
N
a
m
e
mysql>
SELECT
EName
as
Name,
Salary*
2024-
25
+----------+-----------------------+
| Name | Salary*12 | NOTES
+----------+-----------------------+
| Aaliya | 120000 |
| Kritika | 720000 |
| Shabbir | 540000 |
| Gurpreet | 228000 |
| Joseph | 408000 |
| Sanya | 576000 |
| Vergese | 180000 |
| Nachaobi | 348000 |
| Daribha | 504000 |
| Tanya | 600000 |
+----------+-----------------------+
10 rows in set (0.02 sec)
Observe that in the output, Salary*12 is displayed
as the column name for the Annual Income column. In
the output table, we can use alias to rename that
column as Annual Income as shown below:
mysql> SELECT Ename AS Name, Salary*12 AS 'Annual Income’
-> FROM EMPLOYEE;
+----------+------------------------------+
| Name | Annual Income|
+----------+------------------------------+
| Aaliya | 120000 |
| Kritika | 720000 |
| Shabbir | 540000 |
| Gurpreet | 228000 |
| Joseph | 408000 |
| Sanya | 576000 |
| Vergese | 180000 |
| Nachaobi | 348000 |
| Daribha | 504000 |
| Tanya | 600000 |
+----------+------------------------------+
10 rows in set (0.00 sec)
Note: Annual Income will not be added as a new column in the
database table. It is just for displaying the output of the query.
If an aliased column name has space as in the case of Annual
Income, it should be enclosed in quotes as 'Annual Income
(C) Distinct Clause
By default, SQL shows all the data retrieved through
query as output. However, there can be duplicate values.
The SELECT statement when combined with DISTINCT
clause, returns records without repetition (distinct
records). For example, while retrieving a department
number from employee relation, there can be duplicate
values as many employees are assigned to the same
department. To select unique department number for
all the employees, we use DISTINCT as shown below:
mysql> SELECT DISTINCT DeptId FROM EMPLOYEE;
2024-
25
NOTES mysql> SELECT *
-> FROM EMPLOYEE
-> WHERE DeptId = 'D01' OR DeptId = 'D02' OR
DeptId = 'D04';
+-------+----------+--------+-------+-------------------------------+
| EmpNo | Ename | Salary | Bonus | DeptId |
+-------+----------+--------+-------+-------------------------------+
| 101 | Aaliya | 10000 | 234 | D02 |
| 102 | Kritika | 60000 | 123 | D01 |
| 103 | Shabbir | 45000 | 566 | D01 |
| 104 | Gurpreet | 19000 | 565 | D04 |
| 106 | Sanya | 48000 | 695 | D02 |
| 107 | Vergese | 15000 | NULL | D01 |
| 109 | Daribha | 42000 | NULL | D04 |
+-------+----------+--------+-------+-------------------------------+
7 rows in set (0.00 sec)
(E) Membership operator IN
The IN operator compares a value with a set of values
and returns true if the value belongs to that set. The
above query can be rewritten using IN operator as
shown below:
mysql> SELECT * FROM EMPLOYEE
-> WHERE DeptId IN ('D01', 'D02' , 'D04');
+-------+----------+--------+-------+-------------------------------+
| EmpNo | Ename | Salary | Bonus | DeptId |
+-------+----------+--------+-------+-------------------------------+
| 101 | Aaliya | 10000 | 234 | D02 |
| 102 | Kritika | 60000 | 123 | D01 |
| 103 | Shabbir | 45000 | 566 | D01 |
| 104 | Gurpreet | 19000 | 565 | D04 |
| 106 | Sanya | 48000 | 695 | D02 |
| 107 | Vergese | 15000 | NULL | D01 |
| 109 | Daribha | 42000 | NULL | D04 |
+-------+----------+--------+-------+-------------------------------+
7 rows in set (0.00 sec)
w
e
n
e
e
d
t
o
c
o
m
b
i
n
e
N
O
T
w
i
t
h
I
N
a
s
w
e
w
a
n
t
t
o
r
e
t
r
i
e
2024-
25
(F) ORDER BY Clause
ORDER BY clause is used to display data in an ordered
form with respect to a specified column. By default,
ORDER BY displays records in ascending order of
the specified column’s values. To display the records
in descending order, the DESC (means descending)
keyword needs to be written with that column.
Example 9.9 The following query selects details of all the
employees in ascending order of their salaries.
mysql> SELECT * FROM EMPLOYEE
-> ORDER BY Salary;
+-------+----------+--------+-------+-------------------------------+
| EmpNo | Ename | Salary | Bonus | DeptId |
+-------+----------+--------+-------+-------------------------------+
| 101 | Aaliya | 10000 | 234 | D02 |
| 107 | Vergese | 15000 | NULL | D01 |
| 104 | Gurpreet | 19000 | 565 | D04 |
| 108 | Nachaobi | 29000 | NULL | D05 |
| 105 | Joseph | 34000 | 875 | D03 |
| 109 | Daribha | 42000 | NULL | D04 |
| 103 | Shabbir | 45000 | 566 | D01 |
| 106 | Sanya | 48000 | 695 | D02 | Activity 9.9
| 110 | Tanya | 50000 | 467 | D05 |
| 102 | Kritika | 60000 | 123 | D01 | Execute the following
2 queries and find out
+-------+----------+--------+-------+-------------------------------+
what will happen if we
10 rows in set (0.05 sec)
specify two columns in
the ORDER BY clause:
Example 9.10 Select details of all the employees in descending
order of their salaries. SELECT * FROM
mysql> SELECT * FROM EMPLOYEE EMPLOYEE
-> ORDER BY Salary DESC; ORDER BY Salary,
+-------+----------+--------+-------+-------------------------------+ Bonus;
| EmpNo | Ename | Salary | Bonus | DeptId |
+-------+----------+--------+-------+-------------------------------+ SELECT * FROM
| 102 | Kritika | 60000 | 123 | D01 | EMPLOYEE
| 110 | Tanya | 50000 | 467 | D05 | ORDER BY
| 106 | Sanya | 48000 | 695 | D02 | Salary,Bonus
| 103 | Shabbir | 45000 | 566 | D01 |
| 109 | Daribha | 42000 | NULL | D04 |
| 105 | Joseph | 34000 | 875 | D03 |
| 108 | Nachaobi | 29000 | NULL | D05 |
| 104 | Gurpreet | 19000 | 565 | D04 |
| 107 | Vergese | 15000 | NULL | D01 |
| 101 | Aaliya | 10000 | 234 | D02 |
+-------+----------+--------+-------+-------------------------------+
10 rows in set (0.00 sec)
(G) Handling NULL Values
SQL supports a special value called NULL to represent
a missing or unknown value. For example, the Gphone
column in the GUARDIAN table can have missing value
for certain
STRUCTURED records.
QUERY Hence,
LANGUAGE (SQL) NULL is used to represent 151
2024-
25
such unknown values. It is important to note that
NULL
2024-
25
NOTES is different from 0 (zero). Also, any arithmetic operation
performed with NULL value gives NULL. For example:
5 + NULL = NULL because NULL is unknown hence
the result is also unknown. In order to check for NULL
value in a column, we use IS NULL operator.
Example 9.11 The following query selects details of all those
employees who have not been given a bonus. This implies
that the bonus column will be blank.
mysql> SELECT * FROM EMPLOYEE
-> WHERE Bonus IS NULL;
+-------+----------+--------+-------+-------------------------------+
| EmpNo | Ename | Salary | Bonus | DeptId |
+-------+----------+--------+-------+-------------------------------+
| 107 | Vergese | 15000 | NULL | D01 |
| 108 | Nachaobi | 29000 | NULL | D05 |
| 109 | Daribha | 42000 | NULL | D04 |
+-------+----------+--------+-------+-------------------------------+
3 rows in set (0.00 sec)
2024-
25
NOTES Example 9.17 The following query selects names of all
employees containing 'a' as the second character.
mysql> SELECT EName FROM EMPLOYEE
-> WHERE Ename like '_a%';
+----------------+
| EName |
+----------------+
| Aaliya |
| Sanya |
| Nachaobi |
| Daribha |
| Tanya |
+----------------+
5 rows in set (0.00 sec)
2024-
25
9.8 FUNCTIONS IN SQL
In this section, we will understand how to use single
row functions, multiple row functions, group records
based on some criteria, and working on multiple tables
using SQL.
Customer
Inventory
CustID
CarID
CustName
CarName
CustAdd
Price
Phone
Model
Email
YearManufacture
FuelType Sale
InvoiceNo Employee
CarID
CustID EmpID
SaleDate EmpName
PaymentMode DOB
EmpID DOJ
SalePrice Designaiton
Salary
2024-
25
categorised as Single Row functions and Aggregate
functions.
9.8.1 Single Row Functions
These are also known as Scalar functions. Single row
functions are applied on a single value and return
a single value. Figure 9.3 lists different single row
functions under three categories — Numeric (Math),
String, Date and Time.
Math Functions
Single Row Functions
accept numeric value
as input and return
Numeric Functions String Functions Date Functions a numeric value
UCASE() NOW() as a result. String
POWER()
LCASE() DATE() Functions accept
ROUND()
MID() MONTH()
character value as
MOD()
input and return
LENGTH() MONTHNAME()
either character or
LEFT() YEAR()
numeric values as
RIGHT() DAY()
output. Date and
INSERT() DAYNAME() Time functions accept
LTRIM() date and time value
RTRIM() as input and return
TRIM() numeric or string
or Date and Time
Figure 9.3: Three categories of single-row functions in SQL
as output.
(A) Math Functions
Three commonly used numeric functions are POWER(),
ROUND() and MOD(). Their usage along with syntax is
given in Table 9.13.
2024-
25
d) After dividing the amount into EMIs, find out the
remaining amount to be paid immediately, by
performing modular division.
Following SQL query can be used to solve the
above mentioned (c) and (d) problem:
mysql> SELECT CarId, FinalPrice, ROUND(FinalPrice-
MOD(FinalPrice,1000)/10,0) "EMI",
MOD(FinalPrice,10000) "Remaining Amount" FROM INVENTORY;
+-------+--------------+---------+-----------------------------------------------+
| CarId | FinalPrice | EMI | Remaining Amount |
+-------+--------------+---------+-----------------------------------------------+
| D001 | 652526.6 6
| 52474 |2526.6 |
| D002 | 753885.4 7
| 53797 |3885.4 |
| B001 | 635074.7 6
| 35067 |5074.7 |
| B002 | 725601.0 7
| 25541 |5601.0 |
| E001 | 397829.6 3
| 97747 |7829.6 |
| E002 | 733503.7 7
| 33453 |3503.7 |
| S001 | 575680.0 5
| 75612 |5680.0 |
| S002 | 687680.0 6
| 87612 |7680.0 |
+-------+--------------+---------+-----------------------------------------------+
8 rows in set (0.00 sec)
Example 9.19
a) Let us now add a new column Commission to the
SALE table. The column Commission should have
a total length of 7 in which 2 decimal places to
be there.
mysql> ALTER TABLE SALE ADD(Commission
Numeric(7,2));
Query OK, 6 rows affected (0.34 sec)
Records: 6 Duplicates: 0 Warnings: 0
b) Let us now calculate commission for sales agents as
12% of the SalePrice, Insert the values to the newly
added column Commission and then display
records of the table SALE where commission >
73000.
mysql> UPDATE SALE SET
Commission=12/100*SalePrice;
Query OK, 6 rows affected (0.06 sec)
Rows matched: 6 Changed: 6 Warnings: 0
2024-
25
include displaying the current date, extracting each
element of a date (day, month and year), displaying day
of the week and so on. Table 9.15 explains various date
and time functions.
Table 9.15 Date Functions
Function Description Example with output
NOW() It returns the current system date mysql> SELECT NOW();
and time. Output:
2019-07-11 19:41:17
DATE() It returns the date part from the mysql> SELECT DATE(NOW());
given date/time expression. Output:
2019-07-11
MONTH(date) It returns the month in numeric mysql> SELECT MONTH(NOW());
form from the date. Output:
7
MONTHNAME(date) It returns the month name from mysql> SELECT
the specified date. MONTHNAME(“2003-11-28”);
Output:
Novembe
r
YEAR(date) It returns the year from the date. mysql> SELECT YEAR(“2003-10-
03”);
Output:
2003
DAY(date) It returns the day part from the mysql> SELECT DAY(“2003-03- 24”);
date. Output:
24
MIN(column) Returns the smallest value from mysql> SELECT MIN(Price) FROM
the specified column. INVENTORY;
Output: 355205.00
SUM(column) Returns the sum of the values mysql> SELECT SUM(Price) FROM
for the specified column. INVENTORY;
Output:
4608733.00
COUNT(*) Returns the number of records mysql> SELECT COUNT(*) from
in a table. MANAGER;
+---------------+
Note: In order to display the | count(*) |
number of records that matches +---------------+
a particular criteria in the table, | 4|
we have to use COUNT(*) with +---------------+
WHERE clause.
1 row in set (0.00 sec)
COUNT(column) Returns the number of values mysql> SELECT * from MANAGER;
in the specified column ignoring +------ +------------------+
the NULL values. | MNO | MEMNAME |
+------ +------------------+
Note: | 1 | AMIT |
In this example, let us consider | 2 | KAVREET |
Example 9.22
a MANAGER table having two | 3 | KAVITA |
attributesa)andDisplay
four records.
the total | number 4 | NULLof records| from table
INVENTORY having a model as VXI.
mysql> SELECT COUNT(*) FROM INVENTORY WHERE
Model=”VXI”;
+----------------+
| COUNT(*) |
+----------------+
|
available 2 | table INVENTORY.
from
mysql> SELECT COUNT(DISTINCT Model) FROM
INVENTORY;
2024-
25
9.10 OPERATIONS ON RELATIONS NOTES
We can perform certain operations on relations like
Union, Intersection and Set Difference to merge the
tuples of two tables. These three operations are binary
operations as they work upon two tables. Note here that
these operations can only be applied if both the relations
have the same number of attributes and corresponding
attributes in both tables have the same domain.
9.10.1 UNION ()
This operation is used to combine the selected rows of
two tables at a time. If some rows are same in both
the tables, then result of the Union operation will
show those rows only once. Figure 9.4 shows union of
two sets.
Music Dance
2024-
25
NOTES Example 9.25 List the UCode, UName, UColor, Size and
Price of related tuples of tables UNIFORM and COST.
The given query may be written in three different
ways as given below.
a) Using condition in where clause
mysql> SELECT * FROM UNIFORM U, COST C WHERE
U.UCode = C.UCode;
SUMMARY
• Database is a collection of related tables. MySQL
is a ‘relational’ DBMS.
• DDL (Data Definition Language) includes SQL
statements such as, Create table, Alter table and
Drop table.
• DML (Data Manipulation Language) includes SQL
statements such as, insert, select, update and
delete.
• A table is a collection of rows and columns, where
each row is a record and columns describe the
feature of records.
• ALTER TABLE statement is used to make changes
in the structure of a table like adding, removing
or changing datatype of column(s).
• UPDATE statement is used to modify existing
data in a table.
• WHERE clause in SQL query is used to enforce
condition(s).
• DISTINCT clause is used to eliminate repetition
and display the values only once.
EXERCISE
1. Answer the following questions:
a) Define RDBMS. Name any two RDBMS software.
b) What is the purpose of the following clauses in a
select statement?
i) ORDER BY
ii) GROUP BY
c) Site any two differences between Single Row Functions
and Aggregate Functions.
d) What do you understand by Cartesian Product?
e) Differentiate between the following statements:
— Stewart Kirkpatrick
In this Chapter
» Introduction to Computer
Networks
» Evolution of Networking
10.1 INTRODUCTION TO COMPUTER NETWORKS
» Types of Networks
» Network Devices We are living in a connected world. Information
is being produced, exchanged, and traced across
» Networking Topologies
the globe in real time. It's possible as almost
» Identifying Nodes everyone and everything in the digital world is
in a Networked interconnected through one way or the other.
Communication
» Internet, Web and the
Internet of Things
» Domain Name System
Networking
Device
1969
1983
1990
ARPANET became 1974 Domain Name System
functional by introduced
connecting UCLA and
SRI
The term Internet was The Berners-Lee at
coined, CERN developed HTML
and URL, thus giving
First commercial use of birth to World Wide Web
ARPANET, was started (www)
in the name of Telenet
LAN 1
Networking LAN 3
Device
LAN 2
Internet
Telephone Line
Modem Modem
10.4.3 RJ45
RJ 45 or Registered Jack-45 is an
eight-pin connector (Figure 10.10)
that is used exclusively with
Ethernet cables for networking.
It is a standard networking
interface that can be seen at
the end of all network cables.
Basically, it is a small plastic plug
that fits into RJ-45 jacks of the
Ethernet cards present in various
Figure 10.10: RJ 45
computing devices.
10.4.5 Switch
A switch is a networking device (Figure 10.12) that
plays a central role in a Local Area Network (LAN).
Like a hub, a network switch is used to connect
multiple computers or communicating devices. When
data arrives, the switch extracts the
destination address from the data
packet and looks it up in a table to
see where to send the packet.
Thus, it sends signals to only
selected devices instead of
sending to all. It can forward
multiple packets at the same time.
A switch does not forward the
signals which are noisy or
corrupted. It drops such signals
and asks the sender to resend it. Figure 10.12: Cables connected to a network switch
PC 4 PC 5 PC 4 PC 5
PC 1 PC 2 PC 3 PC 1 PC 2 PC 3
Activity 10.4
Explore how can you
find the MAC 10.6.2 IP Address
address of your
computer
IP address, also known as Internet Protocol address,
system. is also a unique address that can be used to uniquely
identify each node in a network. The IP addresses
http://www.ncert.nic.in/textbook/textbook.htm
URL
wikipedia.org 198.35.26.96
SUMMARY
• A computer network is an interconnection among
two or more computers or computing devices.
• A computer network allows computers to share
data and resources among each other.
• Networking devices are used to connect multiple
computers in different settings.
EXERCISE
1. Expand the following:
a) ARPANET
b) MAC
c) ISP
d) URI
2. What do you understand by the term network?
3. Mention any two main advantages of using a network of
computing devices.
4. Differentiate between LAN and WAN.
5. Write down the names of few commonly used networking
devices.
6. Two universities in different States want to transfer
information. Which type of network they need to use for
this?
7. Define the term topology. What are the popular network
topologies?
8. How is tree topology different from bus topology?
9. Identify the type of topology from the following:
a) Each node is connected with the help of a single cable.
b) Each node is connected with central switching
through independent cables.
In this Chapter
» Concept of Communication
» Components of Data
Communication 11.1 CONCEPT OF COMMUNICATION
» Measuring Capacity of
Communication Media
The term “Data Communication” comprises two
words: Data and Communication. Data can be
» Types of Data any text, image, audio, video, and multimedia
Communication
files. Communication is an act of sending or
» Switching Techniques receiving data. Thus, data communication refers
» Transmission Media to the exchange of data between two or more
» Mobile Telecommunication networked or connected devices. These devices
Technologies must be capable of sending and receiving data
» Protocol over a communication medium. Examples of
such devices include personal computers, mobile
phones, laptops, etc. As we can see in Figure
11.1, four different types of devices — computer,
printer, server and switch are connected to form
the network. These devices are connected through
a media to the network, which carry information
from one end to other end.
2024-
25
Central Server
Sharing Printer
connected to Switch
Switch
Sender
2024-
25
NOTES Example 11.1 A user wants to upload a text document at
the rate of 10 pages per 20 second. What will be the
required data rate of the channel? (Assume that 1 page
contains 1600 characters and each character is of 8 bits).
Solution:
OR
Both Directions
A B
Figure 11.5: Full duplex transmission of data
Protective
Plastic Covering Insulating
Material
Glass
Sender Receiver
Cladding of less
dense material
Figure 11.11: Fiber optic cable
Geostationary
satellites orbiting 11.6.2 Wireless Transmission Media
around the Earth In wireless communication technology, information
are used to
deliver broadband
In wireless communication technology, information
Internet service, travels in the form of electromagnetic signals through
similar to the way air. Electromagnetic spectrum of frequency ranging
satellite is used from 3 KHz to 900 THz is available for wireless
for television and communication (Figure 11.12). Wireless technologies
telephone signals.
allow communication between two or more devices in
These satellites
use microwaves short to long distance without requiring any physical
for communication media. There are many types of wireless communication
between a satellite technologies such as Bluetooth, WiFi, WiMax etc.
dish placed at our
home and the hub The electromagnetic spectrum range (3KHz to
of satellite internet 900THz) can be divided into 4 categories (Figure 11.12) -
service providers. Radio waves, Microwaves, Infrared waves and Visible or
Light waves, according to their frequency ranges. Some
Radio
Microwaves Infrared Light
Waves
Waves Waves
Figure 11.12: Electromagnetic waves spectrum
Table 11.1 Classification of transmission waves and their properties
Transmission
Properties
Waves
Radio Waves 1. Waves of frequency range 3 KHz - 1 GHz
2. Omni-directional, these waves can move in all directions
3. Radio waves of frequency 300KHz-30MHz can travel long distance
4. Susceptible to interference
5. Radio waves of frequency 3-300KHz can penetrate walls
6. These waves are used in AM and FM radio, television, cordless phones.
11.8 PROTOCOL
In communication, Protocol is a set of standard rules
that the communicating parties — the sender, the
receiver, and all other intermediate devices need
to follow. We know that the sender and receiver can
be parts of different networks, placed at different
geographic locations. Besides, the data transfer rates in
different networks can vary, requiring data to be sent
in different formats.
11.8.1 Need for Protocols
We need protocols for different reasons such as flow
control, access control, addressing, etc. Flow control is
required when the sender and receiver have different
speeds of sending and receiving the data. Figure 11.14
shows that Computer A is sending data at the speed
of 1024 Mbps and computer B is receiving data at the
speed of 512 Mbps. In this case, Computer B must be
able to inform computer A about the speed mismatch
so that computer A can adjust its data transmission
rate. Otherwise some data will be lost, as shown in
Figure 11.14.
Access control is required to decide which nodes in
a communication channel will access the link shared
among them at a particular instant of time. Otherwise,
the transmitted data packets will collide if computers
are sending data simultaneously through the same link
resulting in the loss or corruption of data.
216 COMPUTER SCIENCE - CLASS XII
2024-
25
A B
Received Packets
Loss Packets
Figure 11.14: Speed mismatch between two computers can result into
loss of data
SUMMARY
• Data communication refers to the exchange of
data between two or more networked or
connected devices like laptops, PC, printers,
routers etc.
• Sender, receiver, messages, channel and protocols
are major components of data communication.
• In data communication, transmission media are
the links that carry messages between two or
more communicating devices. These are broadly
classified into guided and unguided media.
• In guided transmission, there is a physical link
made of wire/cable through which data in terms
of signals are propagated between the nodes.
These are usually metallic cable, fiber-optic
cable, etc. They are also known as wired media.
• In unguided transmission, data travels in air in
terms of electromagnetic waves using an antenna.
They are also known as wireless media.
• The capacity of channels is measured in
bandwidth. The unit of bandwidth is Hertz.
• Communication can be done in three different
modes — simplex, half-duplex, and full-duplex
communication.
• Switching techniques are alternative to
dedicated lines whereby data is routed through
various nodes in a network. It forms a
temporary route for the data to be transmitted.
Two commonly used switching techniques are –
circuit switching and packet switching.
• Electromagnetic spectrum of frequency ranging
from 3 KHz to 900 THz is available for wireless
communication. This spectrum range (3KHz to
900THz) can be divided into four categories- Radio
EXERCISE
1. What is data communication? What are the main
components of data communication?
2. Which communication mode allows communication in
both directions simultaneously?
3. Among LAN, MAN, and WAN, which has the highest
speed and which one can cover the largest area?
— Clifford Stoll
In this Chapter
» Threats and Prevention
» Malware
» Antivirus
» Spam 12.1 THREATS AND PREVENTION
» HTTP vs HTTPS Being alone is the most ideal situation for an
» Firewall individual in terms of security. It applies to
» Cookies computers as well. A computer with no link to
» Hackers and Crackers an external device or computer is free from the
security threats arising otherwise. However,
» Network Security Threats
it is not an ideal solution for a human being
or a computer to stay aloof in order to mitigate
any security threats, as the world at present
is on its way to become fully connected. This
connectedness of various devices and computers
has brought into our focus the various network
threats and its prevention.
Network security is concerned with protection
of our device as well as data from illegitimate
access or misuse. Threats include all the ways in
which one can exploit any vulnerability or
weakness in a network or communication system
in order to cause harm or damage one’s
2024-
25
reputation.
2024-
25
NOTES 12.2 MALWARE
Malware is a short term used for MALicious softWARE.
It is any software developed with an intention to damage
hardware devices, steal data, or cause any other
trouble to the user. Various types of malware have
been created from time-to-time, and large-scale
damages have been inflicted. Many of these malware
programs have been identified and counter measures
have been initiated. However, different types of malware
keep on coming on a regular basis that compromise the
security of computer systems and cause intangible
damages. Besides, each year, malware incur financial
damages worth billions of dollars worldwide. Viruses,
Worms, Ransomware, Trojans, and Spyware are some
of the kinds of malware.
12.2.1 Virus
The term computer virus was coined by Fred Cohen in
1985 and has been borrowed from biological science
with almost similar meaning and behavior, the only
difference is that the victim is a computer system and
the virus is a malicious software. A virus is a piece of
software code created to perform malicious activities
and hamper resources of a computer system like CPU
time, memory, personal files, or sensitive information.
Mimicking the behaviour of a biological virus, the
computer virus spreads on contact with another system,
i.e. a computer virus infects other computer systems
that it comes into contact with by copying or inserting
its code into the computer programs or software
(executable files). A virus remains dormant on a system
and is activated as soon as the infected file is opened
(executed) by a user.
Viruses behave differently, depending upon the
reason or motivation behind their creation. Some of
the most common intentions or motives behind
viruses include stealing passwords or data, corrupting
files, spamming the user’s email contacts, and even
taking control of the user’s machine. Some well-known
viruses include CryptoLocker, ILOVEYOU, MyDoom,
Sasser and Netsky, Slammer, Stuxnet, etc.
12.2.2 Worms
The Worm is also a malware that incurs unexpected or
damaging behaviour on an infected computer system.
The major difference between a worm and a virus is that
224 COMPUTER SCIENCE - CLASS XII
2024-
25
unlike a virus, a worm does not need a host program NOTES
or software to insert its code into. Worms are
standalone programs that are capable of working on
its own. Also, a virus needs human triggering for
replication (i.e. when a user opens/executes the
infected file), while a worm replicates on its own and
can spread to other computers through the network.
Some prominent examples of worms include Storm
Worm, Sobig, MSBlast, Code Red, Nimda, Morris Worm,
etc.
12.2.3 Ransomware
It is a type of malware that targets user data. It
either blocks the user from accessing their own data
or threatens to publish the personal data online and
demands ransom payment against the same. Some
ransomware simply block the access to the data while
others encrypt data making it very difficult to access.
In May 2017, a ransomware WannaCry infected almost
200,000 computers across 150 countries. It worked by
encrypting data and demanding ransom payments in
the Bitcoin cryptocurrency. It literally made its victims
“cry” and hence the name.
12.2.4 Trojan
Since the ancient Greeks could not infiltrate the city
of Troy using traditional warfare methods, they gifted
the king of Troy with a big wooden horse with hidden
soldiers inside and eventually defeated them. Borrowing
SECURITY ASPECTS 225
2024-
25
NOTES the concept, a Trojan is a malware, that looks like a
legitimate software and once it tricks a user into
installing it, it acts pretty much like a virus or worm.
However, a Trojan does not self-replicate or infect other
files, it spreads through user interaction such as opening
an email attachment or downloading and executing a file
from the Internet. Some Trojans create backdoors to
give malicious users access to the system.
12.2.5 Spyware
It is a type of malware that spies on a person or an
organisation by gathering information about them,
without the knowledge of the user. It records and sends
the collected information to an external entity without
consent or knowledge of the user.
Spyware usually tracks internet usage data and
sells them to advertisers. They can also be used to
track and capture credit card or bank account
information, login and password information or user’s
personal identity.
12.2.6 Adware
An Adware is a malware that is created to generate
revenue for its developer. An adware displays
online advertisements using pop-ups, web pages, or
installation screens. Once an adware has infected a
substantial number of computer systems, it generates
revenue either by displaying advertisements or using
“pay per click” mechanism to charge its clients against
the number of clicks on their displayed ads. Adware
226 COMPUTER SCIENCE - CLASS XII
2024-
25
is usually annoying, but harmless. However, it often
paves way for other malware by displaying unsafe
links as advertisements. To implement a
keylogger in hardware,
12.2.7 Keyloggers a thin transparent
A keylogger can either be malware or hardware. The keyboard is placed
main purpose of this malware is to record the keys atop the actual
keyboard or input
pressed by a user on the keyboard. A keylogger makes pad of the intended
logs of daily keyboard usage and may send it to an machine, which then
external entity as well. In this way, very sensitive and records the keystrokes
personal information like passwords, emails, private pressed by the user.
conversations, etc. can be revealed to an external
entity without the knowledge of the user. One strategy
to avoid the threat of password leaks by keyloggers is
to use a virtual keyboard while signing into your
online accounts from an unknown computer.
12.3 ANTIVIRUS
Antivirus is a software, also known as anti-malware.
Initially, antivirus software was developed to detect
and remove viruses only and hence the name anti-
virus. However, with time it has evolved and now comes
bundled with the prevention, detection, and removal of
a wide range of malware.
12.3.1 Methods of Malware Identification used by
Antivirus
(A) Signature-based detection
In this method, an antivirus works with the help of
a signature database known as “Virus Definition File
(VDF)”. This file consists of virus signatures and is
updated continuously on a real-time basis. This makes
the regular update of the antivirus software a must. If
there is an antivirus software with an outdated VDF, it
is as good as having no antivirus software installed, as
Virus Signature the new malware will infect the system without getting
A virus signature detected. This method also fails to detect malware that
is a consecutive has an ability to change its signature (polymorphic)
sequence of bytes and the malware that has some portion of its code
that is commonly
found in a certain
encrypted.
malware sample.
That means it’s (B) Sandbox detection
contained within the In this method, a new application or file is executed
malware or the in a virtual environment (sandbox) and its behavioural
infected file and not in fingerprint is observed for a possible malware.
unaffected files. Depending on its behaviour, the antivirus engine
determines if it is a potential threat or not and
proceeds accordingly. Although this method is a little
slow, it is very safe as the new unknown application is
not given access to actual resources of the system.
(C) Data mining techniques
This method employs various data mining and machine
learning techniques to classify the behaviour of a file as
either benign or malicious.
12.4 SPAM
Spam is a broad term and applies to various digital
platforms like messaging, forums, chatting, emailing,
advertisement, etc. However, the widely recognised
form is email spam. Depending on their requirements,
organisations or individuals buy or create a mailing
list (list of email addresses) and repeatedly send
advertisement links and invitation emails to a large
number of users. This creates unnecessary junk in the
inbox of the receiver’s email and often tricks a user into
buying something or downloading a paid software or
malware.
Nowadays, email services like Gmail, Hotmail, etc.
have an automatic spam detection algorithm that
filters emails and makes things easier for the end
users. A user can also mark an undetected unsolicited
email as “spam”, thereby ensuring that such type of
email is not delivered into the inbox as normal email in
future.
Always look for
12.5 HTTP VS HTTPS the “https://” at
Both the HTTP (Hyper Text Transfer Protocol) and its the beginning of
the address (URL)
variant HTTPS (Hyper Text Transfer Protocol Secure) of the websites
are a set of rules (protocol) that govern how data can while entering your
be transmitted over the WWW (World Wide Web). In banking, personal,
other words, they provide rules for the client web or other sensitive
browser and servers to communicate. information.
HTTP sends information over the network as it is. It
does not scramble the data to be transmitted, leaving
LAN
WAN
Firewall
0 0
0 1
1 0
1
11 01
11 111
10 1
10 11
10 1 11
1 01 0
0 1 1000
SUMMARY
• Malware is a software developed with an intention
to damage computer hardware, software, steal
data, or cause any other trouble to a user.
• A virus is a piece of software code created
to perform malicious activities and hamper
resources of a computer system.
• The Worm is also a malware that incurs
unexpected or damaging behaviour on an infected
computer system.
• Worms are standalone programs that are capable
of working on its own.
• Ransomware is a type of malware that targets
user data.
• Ransomware either blocks the user from
accessing their own data or threatens to publish
their personal data online and demands ransom
payment against the same.
• Trojan is a malware, that looks like a legitimate
software and once it tricks a user into installing
it, it acts pretty much like a virus or a worm.
• Spyware records and sends the collected
information to an external entity without the
consent or knowledge of a user.
• An adware displays unwanted online
advertisements using pop-ups, web pages, or
installation screens.
• A keylogger makes logs of daily keyboard usage
and may send it to an external entity as well.
• The on-screen keyboard is an application software
that uses a fixed QWERTY key layout.
• Online virtual keyboard is a web-based or a
standalone software with a randomised key
layout every time it is used.
• A malware can take many routes to reach your
computer, which include: Downloaded from the
EXERCISE
1. Why is a computer considered to be safe if it is not
connected to a network or Internet?
2. What is a computer virus? Name some computer viruses
that were popular in recent years.
3. How is a computer worm different from a virus?
4. How is Ransomware used to extract money from users?
5. How did a Trojan get its name?
6. How does an adware generate revenue for its creator?
7. Briefly explain two threats that may arise due to a
keylogger installed on a computer.
8. How is a Virtual Keyboard safer than On Screen
Keyboard?
9. List and briefly explain different modes of malware
distribution.
10. List some common signs of malware infection.
11. List some preventive measures against malware
infection.
12. Write a short note on different methods of malware
identification used by antivirus software.
13. What are the risks associated with HTTP? How can we
resolve these risks by using HTTPS?
14. List one advantage and disadvantage of using Cookies.
15. Write a short note on White, Black, and Grey Hat
Hackers.
16. Differentiate between DoS and DDoS attack.
17. How is Snooping different from Eavesdropping?
— Gautam Buddha
In this Chapter
» Introduction
» Approaches for Solving
Projects
» Teamwork
13.1 INTRODUCTION
» Project Descriptions
Project based learning gives a thorough practical
exposure to students regarding a problem upon
which the project is based. Through project based
learning, students learn to organise their project
and use their time effectively for successful
completion of the project. Projects are developed
generally in groups where students can learn
various skills such as working together, problem
solving, decision making, and investigating
activities. Project based learning involves the
steps such as analysing the problem, formulating
the problem into small modules, applying the
mechanism or method to solve each module and
then integrating the solution of all the modules
to arrive at the complete solution of the problem.
To solve a problem, it is required that those who
work on it gather the relevant data and process
it by applying a particular method. Data may
2024-
25
NOTES be collected as per the requirement of the project in
a particular format. All the team members should be
associated to accomplish the task. After collecting data,
it should be processed to solve the problem. The results
should be reported in a predetermined format.
Outcome
of project
13.3 TEAMWORK
Many real-life tasks are very complex and require a lot of
individuals to contribute in achieving them. Efforts made
by individuals collectively to accomplish a task is called
teamwork.
For example, in many sports, there is a team of
players. These players play together to win a match.
Take an example of a cricket team. We find that even if
a bowler bowls a good ball but if the fielder cannot take
Description
A new restaurant “Stay Healthy” is coming up in your
locality. The owner/management of the restaurant
wants to use a computer to generate bills and maintain
other records of the restaurant. Your team is asked to
develop an application software to automate the order
placing and associated processes.
Specifications
Make a group of students to undertake a project on
automating the order processing of the restaurant
‘Stay Healthy’. The owner of the restaurant wants the
following specific functionalities to be made available in
the developed application:
• There should be two types of Login options — one for
the manager of the joint and other for the customer.
• Kiosk(s) running the software for customers will be
placed at reception for placing the order. On the
opening screen, menu for placing orders will be
displayed.
• To place orders, customers will enter Item Code(s)
and quantity desired.
• After placing an order, a soft copy of the bill will be
displayed on the kiosk, having an Order Number.
• Every bill will have a unique identification (such as
combination of date, and order number of the day)
and should be saved in the data file/database.
• Order Number starts from 1 every day.
Description
Implement a puzzle solving game in Python. The game
presents a grid board composed of cells to the player, in
which some cells have Bomb. Player is required to clear
the board (of the bomb), without detonating any one of
them with the help of clue(s) provided on the board.
Specifications
For clearing the board, the player will click a cell on
the board, if the cell contains a bomb, the game
finishes. If the cell does not contain a bomb, then the
cell reveals a number giving a clue about the number
of bombs hidden in adjacent cells.
Before you start coding the game, play any
Minesweeper game five times. This will help you in
proper understanding of your project. To reduce the
complexity of the program you can fix the grid size to
6x6 and number of bombs to 6.
Note: Do ensure to handle various exception(s) which may
occur while playing the game, in your code.
Description
You are a member of the ICT club of your school. As a
club member, you are given the responsibility of
identifying ways to improve mathematical skills of kids,
in the age group of 5-7 years. One of the club members
suggested developing an Edutainment Game named
“Match the Sum” for it. Match the Sum will hone
summing skills of student(s), by allowing them to form
number 10 by adding 2/3 digits.