Second Puc Computer Science Notes Complete
Second Puc Computer Science Notes Complete
O
H
A
M
M
ED
M
AT
H
EE
N
L
R
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025
Contents
LICENSE 8
R
Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Built-in Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
L
Raising Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
N
The raise Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
The assert Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
EE
Handling Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
The try…except Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
The try..except..else Clause . . . . . . . . . .
The finally clause . . . . . . . . . . . . . . . . . H . . . . . . . . . . . . . . . . . . . 16
AT
. . . . . . . . . . . . . . . . . . . 17
Recovering and continuing with finally clause . . . . . . . . . . . . . . . . . . . . . 17
M
Types of Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Binary Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
M
File Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Closing a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
H
Closing a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Opening a File Using with Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Writing to a Text File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Syntax: write() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Example: write() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Syntax: writelines() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Example: writelines() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Reading from a Text File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Syntax: read(n) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Example: read(n) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Syntax: read() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Example: read() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Syntax: readline(n) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Example: readline(n) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
R
Syntax: readlines() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
L
Example: readlines() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Complete Example from Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
N
File Offset Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
EE
Syntax: tell() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Syntax: seek(offset, reference_point) . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Creating and Traversing a Text File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Creating File and Writing Data . . . . . . .
H. . . . . . . . . . . . . . . . . . . . . . . 26
AT
Displaying File Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Combined Read/Write Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Pickle Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
M
Pickling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Unpickling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
ED
Import Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Syntax for dump() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
M
CHAPTER 3: STACKS 30
H
CHAPTER NOTES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
O
3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
M
3.2 Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.2.1 Applications of Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.3 Operations on Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.4 Implementation of Stack in Python . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.5 Notations for Arithmetic Expressions . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.6 Conversion from Infix to Postfix . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.7 Evaluation of Postfix Expression . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Summary Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
CHAPTER 4: QUEUE 35
CHAPTER NOTES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.1 Introduction to Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.1.1 FIFO Principle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Applications of Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.2 Operations on Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
R
4.3 Implementation of Queue using Python . . . . . . . . . . . . . . . . . . . . . . . . 37
4.4 Introduction to Deque (Double-Ended Queue) . . . . . . . . . . . . . . . . . . . . . 38
L
Applications of Deque (Double-Ended Queue) . . . . . . . . . . . . . . . . . . . . . . 38
N
4.4.2 Operations on Deque . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Algorithm 4.1: Palindrome using Deque . . . . . . . . . . . . . . . . . . . . . . . . . . 39
EE
4.5 Implementation of Deque using Python . . . . . . . . . . . . . . . . . . . . . . . . 39
Summary Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
CHAPTER 5: SORTING H 42
AT
CHAPTER NOTES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
M
CHAPTER 6: SEARCHING 48
M
CHAPTER NOTES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
A
6.4.1 Collision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
R
7.2 Data Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
7.3 Data Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
L
7.4 Data Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
N
Figure 7.2: Real-Life Data Processing Examples . . . . . . . . . . . . . . . . . . . . 58
7.5 Statistical Techniques for Data Processing . . . . . . . . . . . . . . . . . . . . . . . 58
EE
Glossary of Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
CHAPTER NOTES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
A
R
10.3.1 Personal Area Network (PAN) . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
10.4: Network Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
L
10.5: Networking Topologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
N
What is a Topology? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
10.6: Identifying Nodes in a Networked Communication . . . . . . . . . . . . . . . . . 120
EE
10.7: Internet, Web, and the Internet of Things (IoT) . . . . . . . . . . . . . . . . . . . 121
10.8: Domain Name System (DNS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
R
L
N
EE
H
AT
M
ED
M
M
A
H
O
M
LICENSE
This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 4.0 Interna-
tional License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/ or
send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
“Karnataka Second PUC Computer Science Study Material / Student Notes” by L R Mohammed Matheen
is licensed under CC BY-NC-ND 4.0.
R
L
N
Figure 1: Licence
EE
This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 4.0 Interna-
tional License.
H
Portions of this work may include material under separate copyright. These materials are not covered by
AT
this Creative Commons license and are used by permission or under applicable copyright exceptions.
tional License.
ED
M
M
A
H
O
M
CHAPTER SYNOPSIS
Introduction
When there are syntax errors, runtime errors or logical errors in the code, program does not execute at all
or the program executes but generates unexpected output or behaves abnormally.
R
Exception handling in Python allows a programmer to deal with runtime errors, ensuring that the program
L
continues to operate in the presence of unexpected conditions. This process involves identifying, catching,
and handling exceptions to maintain the normal flow of the program.
N
EE
Syntax Errors
Definition Syntax errors occur when the code written does not conform to the rules of the Python language.
H
These errors are detected during the parsing stage and must be fixed before the program can run. Syntax
AT
errors are also called parsing errors.
Example:
M
marks = 10
if marks>20:
ED
This code will produce a SyntaxError because of the missing closing quote.
M
R
L
N
EE
H
AT
M
ED
Exceptions
A
Definition These are errors that occur during the execution of the program. Unlike syntax errors, excep-
tions are detected during runtime and can be handled using exception handlers.. Examples include trying
H
Example:
M
result = 10 / 0
Built-in Exceptions
Commonly occurring exceptions are usually defined in the compiler/interpreter. These are called built-in
exceptions.
Exception Description
R
IOError Raised when an input/output operation fails.
Raised when the user interrupts the program’s execution (usually by pressing
KeyboardInterrupt
L
Ctrl+C).
N
ImportError Raised when an import statement fails to find the module definition.
EE
EOFError Raised when the input() function hits an end-of-file condition.
ZeroDivisionErrorRaised when the second argument of a division or modulo operation is zero.
IndexError Raised when an index is out of range.
H
AT
NameError Raised when a local or global name is not found.
IndentationError Raised when there is incorrect indentation.
M
Examples:
M
# Example of NameError
M
print(var + 40)
A
# Example of IndexError
lst = [1, 2, 3]
H
print(lst[5])
O
# Example of TypeError
M
print(10 +'5')
Built-in Exceptions:
R
L
N
EE
A programmer can also create custom exceptions to suit one’s requirements. These are called user-defined
exceptions.
Raising Exceptions H
AT
We can forcefully raise an exception using the raise or assert statement.
M
Example:
A
numbers = [40,50,60,70]
length = 10
H
if length>len(numbers):
O
raise IndexError
print ("No Execution")
M
else:
print(length)
The assert statement is used to test expressions and raise an AssertionError if the expression is false.
This statement is generally used in the beginning of the function or after a function call to check for
valid input. It is commonly used for debugging purposes. The syntax for assert statement is: assert
Expression[,arguments]
Example:
R
negativecheck(100)
L
negativecheck(-350)
N
Handling Exceptions
EE
Exception Handling
Exception handling refers to the process of responding to the occurrence of exceptions during the execu-
H
tion of a program. This is typically done using try, except, finally, and else blocks in Python.
AT
Need for Exception Handling: - Essential to prevent program crashes by capturing and managing run-
time errors.
M
- Separates main program logic from error detection and correction code.
- The compiler/interpreter tracks the exact error location.
ED
• When an error occurs, Python interpreter creates an object called the exception object.
M
• This object contains information about the error like its type, file name, and position in the
A
• The object is handed over to the runtime system to find an appropriate code to handle this particular
O
exception.
M
• This process of creating an exception object and handing it over to the runtime system is called
throwing an exception.
• When an exception occurs while executing a particular program statement, the control jumps to an
exception handler, abandoning the execution of the remaining program statements.
• The runtime system searches the entire program for a block of code, called the exception handler,
that can handle the raised exception.
• The runtime system first searches the method in which the error occurred and the exception was
raised. If not found, it searches the method from which this method was called.
• This hierarchical search in reverse order continues until the exception handler is found.
• This entire list of methods is known as the call stack.
R
L
• When a suitable handler is found in the call stack, it is executed by the runtime process.
N
• The process of executing a suitable handler is known as catching the exception.
EE
• If the runtime system cannot find an appropriate exception after searching all the methods in the
call stack, then the program execution stops.
H
AT
M
ED
M
M
A
H
O
M
R
L
N
EE
H
AT
M
ED
M
M
A
H
O
The try...except block is used to handle exceptions in Python. Code that might raise an exception is
placed inside the try block, and the handling of the exception is done in the except block.
Syntax:
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
Example:
R
denom = int(input("Enter the denominator: "))
quotient = (numerator / denom)
print(quotient)
L
print("Division performed successfully")
N
except ZeroDivisionError:
print("Denominator as ZERO.... not allowed")
EE
print("OUTSIDE try..except block")
try: H
AT
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError as e:
M
try:
num = int(input("Enter a number: "))
M
result = 10 / num
except Exception as e:
A
We can put an additional else clause to the normal try...except. Code inside the else block will run
if no exceptions are raised in the try block.
R
The finally clause
L
The finally clause is an optional part of the try statement in Python. The code inside the finally
block is always executed, regardless of whether an exception occurred or not. It is typically used for
N
cleanup actions, like closing files or releasing resources.
EE
Example:
else:
print("The result of the division operation is", quotient)
M
finally:
print("OVER AND OUT")
A
In this example, the message “OVER AND OUT” will be displayed regardless of whether an exception
H
is raised or not .
O
M
If an error has been detected in the try block and the exception has been thrown, the appropriate except
block will be executed to handle the error. But if the exception is not handled by any of the except clauses,
then it is re-raised after the execution of the finally block.
Example:
R
print("The result of the division operation is", quotient)
finally:
L
print("OVER AND OUT")
N
EE
H
AT
M
ED
M
M
A
H
O
M
Introduction to Files
• In Python, data stored in variables is temporary and disappears after the program ends.
• To store data permanently, we use files, which are saved on secondary storage (e.g., hard disks).
• Files allow us to store inputs, outputs, and objects for later use.
• A Python file (source code) is saved with a .py extension.
R
L
Types of Files
N
Files can be classified into two major types:
EE
Text Files
• H
Human-readable and stored using characters like letters, digits, symbols.
AT
• Examples: .txt, .py, .csv, etc.
• Stored using encoding formats like ASCII, Unicode.
M
Example:
Binary Files
M
A
Opening a File
• Files are opened using the open() function which returns a file object.
Syntax:
Read Mode - r
R
• File must exist.
L
• File pointer at the beginning.
f = open("myfile.txt", "r")
N
EE
Binary Read Mode - rb
f = open("myfile.txt", "rb") H
AT
Read and Write Mode - r+
M
f = open("myfile.txt", "r+")
M
Write Mode - w
M
f = open("myfile.txt", "w")
O
f = open("myfile.txt", "wb+")
Append Mode - a
f = open("myfile.txt", "a")
R
• Opens file for both appending and reading.
L
f = open("myfile.txt", "a+")
N
Example from textbook:
EE
myObject = open("myfile.txt", "a+")
File Attributes H
AT
file.closed # True if file is closed
file.mode # Access mode of file
M
Closing a File
M
file_object.close()
M
A
content = myObject.read()
R
w Write only (overwrites if exists) Beginning
L
wb+ Write and read binary (overwrites) Beginning
a Append (creates file if it doesn’t exist) End
N
a+ Append and read End
EE
Example:
H
AT
myObject = open("myfile.txt", "a+")
M
File Attributes
Closing a File
M
Syntax:
A
file_object.close()
H
O
Syntax:
Syntax: write()
file_object.write(string)
R
Example: write()
L
• Writes a single string to the file.
N
myobject = open("myfile.txt", 'w')
EE
myobject.write("Hey I have started using files in Python\n")
myobject.close()
Writing numbers:
H
AT
marks = 58
myobject.write(str(marks))
M
Syntax: writelines()
ED
file_object.writelines(list_of_strings)
M
Example: writelines()
A
H
lines = ["Hello everyone\n", "Writing multiline strings\n", "This is the third line"]
myobject.writelines(lines)
M
Syntax: read(n)
file_object.read(n)
R
Example: read(n)
L
• Reads n bytes from the file.
N
print(myobject.read(10))
EE
myobject.close()
Syntax: read()
H
AT
file_object.read()
Example: read()
ED
print(myobject.read())
M
myobject.close()
A
Syntax: readline(n)
H
file_object.readline(n)
O
Example: readline(n)
Syntax: readlines()
file_object.readlines()
Example: readlines()
R
• Reads all lines and returns a list.
L
print(myobject.readlines())
N
myobject.close()
EE
Splitting into words:
fobject.write(sentence)
fobject.close()
A
fobject.close()
Syntax: tell()
file_object.tell()
R
file_object.tell()
L
Syntax: seek(offset, reference_point)
N
file_object.seek(offset, reference_point)
EE
• Moves pointer to specified position from reference point (0 = start, 1 = current, 2 = end).
Program Example:
M
print(str)
print("Initially, position:", fileobject.tell())
fileobject.seek(0)
M
fileobject.close()
H
O
M
fileobject.write(data)
ans = input("Do you wish to enter more data?(y/n): ")
if ans == 'n': break
fileobject.close()
R
str = fileobject.readline()
while str:
L
print(str)
str = fileobject.readline()
N
fileobject.close()
EE
Combined Read/Write Program
print(fileobject.read())
fileobject.close()
M
A
H
Pickle Module
O
Pickling
M
Unpickling
Import Statement
import pickle
pickle.dump(object, file_object)
R
Syntax for load()
L
variable = pickle.load(file_object)
N
EE
Example for dump()
print(objectvar)
M
import pickle
H
while True:
M
R
except EOFError:
pass
L
N
EE
H
AT
M
ED
M
M
A
H
O
M
CHAPTER 3: STACKS
CHAPTER NOTES
3.1 Introduction
R
• Stack and Queue are not built-in Python structures but can be implemented using lists.
L
N
3.2 Stack
EE
• Definition: A linear data structure where elements are added/removed from one end (TOP).
H
• LIFO Principle: Last In, First Out – the last element added is the first to be removed.
AT
• Analogy: Stack of plates or books – add/remove only from the top.
M
Real-life Scenarios
M
1. Pile of clothes in an almirah – Clothes are added or removed from the top of the pile, following
the LIFO order.
M
2. Multiple chairs in a vertical pile – Chairs are stacked one on top of the other, and removed in
reverse order.
A
3. Bangles worn on the wrist – The last bangle worn is the first to be removed.
H
4. Boxes of eatables in pantry – Boxes are added and removed from the top for convenience.
O
Programming Applications
M
1. String Reversal
• Characters are added to a stack and popped in reverse order to reverse the string.
2. Undo/Redo in Editors
• Each edit (text/image) is pushed onto a stack. Undo removes the last change, redo re-applies
it.
• Navigated pages are pushed onto a stack. Pressing ‘Back’ pops the last visited page and
returns to the previous one.
• During program execution, a stack is used to ensure every opening parenthesis has a matching
closing one. It helps identify syntax errors like unmatched or misnested parentheses.
R
L
N
3.3 Operations on Stack
EE
• PUSH: Add an element to the TOP of the stack.
• POP: Remove the topmost element.
•
• H
Overflow: Trying to PUSH to a full stack (not typically an issue in Python).
Underflow: Trying to POP from an empty stack.
AT
M
Functions:
M
def isEmpty(glassStack):
return len(glassStack) == 0
H
O
# PUSH operation
def opPush(glassStack, element):
M
glassStack.append(element)
# POP operation
def opPop(glassStack):
if isEmpty(glassStack):
print("underflow")
return None
else:
return glassStack.pop()
R
print("Stack is empty")
return None
L
else:
N
return glassStack[-1]
EE
# Display all elements (from TOP to bottom)
def display(glassStack):
print("Current elements in the stack are:")
for i in range(len(glassStack)-1, -1, -1):
H
AT
print(glassStack[i])
M
Sample Program:
glassStack = list() # create empty stack
ED
element = 'glass1'
print("Pushing element", element)
M
opPush(glassStack, element)
M
element = 'glass2'
print("Pushing element", element)
A
opPush(glassStack, element)
H
element = opPop(glassStack)
M
element = 'glass3'
print("Pushing element", element)
opPush(glassStack, element)
R
L
N
3.5 Notations for Arithmetic Expressions
EE
Notation Description Example
Why? Computers struggle with operator precedence in infix; postfix avoids this.
O
• If ( → PUSH to stack
• If ) → POP and add to postExp until ( is found
• If operator:
– POP higher or equal precedence operators and append to postExp
R
L
3.7 Evaluation of Postfix Expression
N
Algorithm 3.2:
EE
1. For each character in postfix expression:
H
• If operator → POP two operands, apply operation, PUSH result
AT
2. At the end, if one item in stack → Result
3. Else → Invalid expression
M
Example: 7 8 2 * 4 / + → Result: 11
ED
M
Summary Points
M
•
• Notations: Infix, Prefix, Postfix
O
CHAPTER 4: QUEUE
CHAPTER NOTES
• A Queue is an ordered linear data structure that follows the FIFO (First In First Out) principle.
• Items are inserted at the rear (tail) and removed from the front (head).
R
• Real-life Examples: Bank queues, toll booths, printer tasks, IVRS systems.
L
4.1.1 FIFO Principle
N
• First-In-First-Out: The element added first is the one removed first.
EE
• Implemented using two ends:
Real-Life Applications
ED
• When you book a ticket and it shows W/L1, it means your request is added to a queue.
M
• If someone cancels their confirmed ticket, the one at the front of the queue (like W/L1) gets
confirmed.
M
• When you call a customer care number, you might hear: > “Please wait while your call is
O
transferred…”
• Your call is placed in a queue.
M
• As soon as a customer care executive is free, the first caller in the queue is attended.
• A server can handle only a limited number of simultaneous requests (say 50).
• If 1000 students try to check results at the same time, the server keeps extra requests in a
queue.
• These requests are served one by one as per FIFO.
R
2. CPU Task Scheduling in Operating Systems
• When multiple programs (called jobs) request CPU time, only one can run at a time.
L
• Jobs are queued and the CPU executes them in the order they arrive (simple job scheduling).
N
3. Printer Queue Management
EE
• If multiple print requests are sent to a shared printer:
– The first print command sent is executed first.
– Remaining ones wait in the print queue.
H
AT
4.2 Operations on Queue
M
Operation Description
ED
enqueue('Z') → Z
enqueue('X') → Z X
enqueue('C') → Z X C
dequeue() → X C
enqueue('V') → X C V
myQueue = list()
def isEmpty(myQueue):
return len(myQueue) == 0
R
def dequeue(myQueue):
L
if not isEmpty(myQueue):
return myQueue.pop(0)
N
else:
EE
print("Queue is empty")
def size(myQueue):
return len(myQueue)
H
AT
def peek(myQueue):
if isEmpty(myQueue):
M
print("Queue is empty")
return None
else:
ED
return myQueue[0]
M
myQueue = list()
A
for _ in range(3):
element = input("Enter person’s code to enter in queue: ")
enqueue(myQueue, element)
• Deque allows insertion and deletion from both ends – front and rear.
• Can behave as both:
R
– Stack (LIFO): insertion/deletion at same end.
– Queue (FIFO): insertion/deletion at opposite ends.
L
N
Applications of Deque (Double-Ended Queue)
EE
Real-Life Applications
H
• A person buys a ticket, leaves, and then comes back with a query.
AT
• Since they’ve already been served, they might get the privilege to rejoin from the front, not
the rear.
M
• This needs a data structure where you can insert from either end — a deque.
• URLs are added to a stack-like structure, but if the memory is limited, older entries (from
M
• Operations are stored so that the last action can be undone first, like a stack.
• But to manage multiple undo/redo and limited memory, deque provides efficient handling.
3. Palindrome Checking
R
Operation Description
------------------ --------------------------------
L
insertFront() Insert at front
insertRear() Insert at rear
N
deletionFront() Delete from front
EE
deletionRear() Delete from rear
isEmpty() Check if deque is empty
getFront() View front without removing
getRear() View rear without removing
H
AT
Algorithm 4.1: Palindrome using Deque
M
myDeque.append(element)
M
def isEmpty(myDeque):
return len(myDeque) == 0
def deletionRear(myDeque):
if not isEmpty(myDeque):
return myDeque.pop()
else:
print("Deque empty")
def deletionFront(myDeque):
if not isEmpty(myDeque):
return myDeque.pop(0)
else:
print("Deque empty")
def getFront(myDeque):
R
if not isEmpty(myDeque):
return myDeque[0]
L
else:
N
print("Queue empty")
EE
def getRear(myDeque):
if not isEmpty(myDeque):
return myDeque[-1]
else:
H
AT
print("Deque empty")
M
dQu = list()
choice = int(input("Enter 1 to use as queue, 2 otherwise: "))
M
if choice == 1:
element = input("Data for insertion at rear: ")
M
insertRear(dQu, element)
print("Data at front:", getFront(dQu))
A
print("Removed:", deletionFront(dQu))
O
print("Removed:", deletionFront(dQu))
else:
M
Summary Points
R
L
N
EE
H
AT
M
ED
M
M
A
H
O
M
CHAPTER 5: SORTING
CHAPTER NOTES
5.1 Introduction
• Sorting is the process of arranging elements in a particular order (ascending, descending, alpha-
betical, etc.).
R
• It is essential for easy data retrieval and efficient searching.
• Common applications:
L
– Dictionaries (alphabetical order)
N
– Exam seating plans (roll number order)
EE
– Sorting by height, weight, etc.
• After each pass, the largest unsorted element “bubbles up” to its correct position.
• Requires n – 1 passes for a list of size n.
ED
Optimization Tip If no swaps occur in a pass, the list is already sorted — the algorithm can be termi-
nated early.
M
M
Pass 1
O
Pass 2
Pass 3
R
[7, 1, -9, 4, 8, 13]
L
→ Swap 7 and 1 → [1, 7, -9, 4, 8, 13]
→ Swap 7 and -9 → [1, -9, 7, 4, 8, 13]
N
→ Swap 7 and 4 → [1, -9, 4, 7, 8, 13]
EE
Pass 4
Pass 5
BUBBLESORT(numList, n)
1. Set i = 0
A
7. j = j + 1
8. i = i + 1
Python Program
def bubble_Sort(list1):
n = len(list1)
for i in range(n):
R
L
5.3 Selection Sort
N
Concept
EE
• The list is divided into sorted and unsorted parts.
• The smallest element from the unsorted list is selected and swapped with the first unsorted element.
• Requires n – 1 passes for n elements.
H
AT
Diagram: Selection Sort Passes Starting List: [8, 7, 13, 1, -9, 4]
M
[-9, 1, 4, 7, 8, 13]
H
Python Program
R
def selection_Sort(list2):
n = len(list2)
L
for i in range(n):
min = i
N
for j in range(i + 1, n):
EE
if list2[j] < list2[min]:
min = j
list2[i], list2[min] = list2[min], list2[i]
H
AT
numList = [8, 7, 13, 1, -9, 4]
selection_Sort(numList)
print("The sorted list is:")
M
for i in range(len(numList)):
print(numList[i], end=" ")
ED
Concept
M
• Elements from the unsorted part are picked and inserted into the correct position of the sorted part.
• Like arranging cards in hand.
A
H
R
3. temp = numList[i]
4. Set j = i - 1
L
5. While j >= 0 and numList[j] > temp:
6. numList[j+1] = numList[j]
N
7. j = j - 1
8. numList[j+1] = temp
EE
9. i = i + 1
Python Program
H
AT
def insertion_Sort(list3):
n = len(list3)
for i in range(n):
M
temp = list3[i]
j = i-1
ED
list3[j+1] = temp
M
All three sorting algorithms in this chapter (bubble, selection, insertion) have O(n²) complexity due to
nested loops.
Summary Points
R
• Selection Sort: Select and place smallest, reduce unsorted list.
• Insertion Sort: Insert each element into sorted part at the correct position.
L
• Time Complexity: Helps choose suitable algorithms for large datasets.
N
EE
H
AT
M
ED
M
M
A
H
O
M
CHAPTER 6: SEARCHING
CHAPTER NOTES
6.1 Introduction
• Searching is the process of locating a specific element (called the key) in a collection.
• It determines whether the key is present and, if so, its position.
R
• Three main techniques:
L
1. Linear Search
2. Binary Search
N
3. Search by Hashing
EE
6.2 Linear Search (Sequential Search)
H
• It compares each element of the list with the key until a match is found or the list ends.
AT
• Useful for unsorted or small-sized lists.
M
LinearSearch(numList, key, n)
Step 1: SET index = 0
Step 2: WHILE index < n, REPEAT Step 3
M
STOP
A
ELSE
index = index + 1
H
Example
0 8 == 17 not found
1 -4 == 17 not found
2 7 == 17 not found
3 17 == 17 Found at index 3
R
for index in range(len(list)):
if list[index] == key:
L
return index + 1
return None
N
EE
list1 = []
maximum = int(input("How many elements in your list? "))
for i in range(maximum):
n = int(input())
H
AT
list1.append(n)
if position is None:
ED
BinarySearch(numList, key)
Step 1: SET first = 0, last = n - 1
Step 2: WHILE first <= last, REPEAT Step 3
Step 3: SET mid = (first + last)//2
IF numList[mid] == key THEN
R
Example
L
List: numList = [2,3,5,7,10,11,12,17,19,23,29,31,37,41,43], Key: 2 Here’s the corrected
N
and neatly formatted table in Markdown:
EE
Step Low High Mid Mid Value Comparison
1 0 14 7 17
H 2 < 17 → left half
AT
2 0 6 3 7 2 < 7 → left half
3 0 2 1 3 2 < 3 → left half
M
4 0 0 0 2 Match found
ED
last = len(list) - 1
O
if list[mid] == key:
return mid
elif key > list[mid]:
first = mid + 1
else:
last = mid - 1
return -1
numList = []
print("Enter elements in ascending order (-999 to stop):")
num = int(input())
while num != -999:
numList.append(num)
num = int(input())
R
if pos != -1:
print(key, "is found at position", pos + 1)
L
else:
N
print(key, "is not found in the list")
EE
6.3.1 Applications of Binary Search
Example
A
H
List: [34, 16, 2, 93, 80, 77, 51], Hash Table size = 10
O
34 4 4
16 6 6
2 2 2
93 3 3
80 0 0
77 7 7
51 1 1
R
Index Value
L
0 80
N
1 51
EE
2 2
3 93
4 34
H
AT
5 None
6 16
M
7 77
8 None
ED
9 None
M
return None
M
hashTable = [None]*10
L = [34, 16, 2, 93, 80, 77, 51]
for i in L:
hashTable[i % 10] = i
6.4.1 Collision
R
• Occurs when multiple elements hash to the same index.
• Requires collision resolution techniques (not covered here).
L
• A perfect hash function prevents collision by mapping each element uniquely.
N
EE
Summary
List Time
Technique Best For Requirement
H Complexity Notes
AT
Linear Search Small/Unordered None O(n) Simple but slow for large
lists n
M
Binary Search Large/Sorted lists Sorted O(log n) Fast, requires sorted input
ED
CHAPTER NOTES
Data is essential for human decision-making in nearly every field of life. Whether we are selecting a
college, making business plans, monitoring health, or predicting weather, we rely on data.
R
Data are raw facts and figures which, when processed, yield information that helps in making decisions.
L
For instance: - Colleges maintain placement data of students to attract new students. - Governments
conduct census to gather demographic data. - Banks maintain account-related data for every customer. -
N
Sports teams analyze opponent data to form strategies.
EE
Definition: Data is a collection of characters, numbers, or symbols that represent values of some
variables.
H
AT
Examples of Common Data Types:
Humans and computers both rely heavily on data. Computers can process large volumes of data quickly
H
Real-life Examples:
• ATM transactions: The system deducts the withdrawn amount from your bank account.
• Weather monitoring: Meteorological departments analyze satellite data for warnings.
• Businesses: Analyze market trends, customer feedback, and dynamic pricing.
• Transportation: Cab apps adjust pricing based on demand and supply.
• Restaurants: Offer discounts during “happy hours” by analyzing customer visits.
Other Scenarios:
R
7.1.2 Types of Data
L
(A) Structured Data: Organized in a tabular format (rows and columns), structured data can be easily
N
processed using spreadsheets or databases. Each row is a record, and each column is an attribute.
EE
Table 7.1: Structured Inventory Data
GH67 Jug 80 0 10
M
With structured data, you can calculate: - Total items in inventory - Total inventory value
Table 7.2: More Structured Examples - Books: Title, Author, Price, Year - Fee Payments: Student
M
Name, Roll No., Amount - ATM Withdrawals: Account No., Amount, ATM ID, Date & Time
A
H
(B) Unstructured Data: Lacks a fixed format or structure. Examples: - News articles - Emails -
Social media posts - Documents with images, audio, video
O
Example: A newspaper page can have a mix of text, ads, images with no fixed layout.
M
3 Scenarios:
Our daily digital activities constantly generate data (e.g., browsing, transactions, healthcare records).
R
Example Applications:
L
• Shopping malls: Analyze co-purchased items to optimize product placement.
N
• Social Media: Public sentiment analysis before elections.
• Global Institutions: Use economic data for forecasting.
EE
7.3 Data Storage
H
AT
After collection, data needs to be stored safely for current and future use. The volume of data is increasing
rapidly, making storage challenging.
M
• Tape Drives
• Pen Drives
M
• Memory Cards
A
Data such as documents, images, audio, video, etc., are stored as files. For complex requirements, we
H
Just storing data is not enough. Data needs to be processed to extract information. Raw data alone cannot
be used for analysis or decision-making.
Here is the Data Processing Cycle diagram from the textbook, properly redrawn and explained for
clarity and accuracy:
+------------------------+
| Data Collection |
+-----------+------------+
|
v
+------------------------+
R
| Data Preparation |
| (cleaning, formatting) |
L
+-----------+------------+
N
|
v
EE
+------------------------+
| Data Entry |
| (input into system) |
H
AT
+-----------+------------+
|
v
M
+------------------------+
| Data Storage |
ED
| (files/databases) |
+-----------+------------+
|
M
v
M
+------------------------+
| Data Retrieval |
A
+-----------+------------+
|
O
v
M
+------------------------+
| Data Processing |
| (classify, update, |
| analyze, compute) |
+-----------+------------+
|
v
+------------------------+
| Data Output |
| (Reports, results, |
| visualizations) |
+------------------------+
1. Data Collection
R
Gathering raw data from various sources like forms, sensors, logs, or digital inputs.
L
2. Data Preparation
Cleaning data (removing errors, duplicates), converting formats, and making it consistent.
N
3. Data Entry
EE
Inputting the cleaned data into digital systems (manually or via automated processes).
4. Data Storage
H
Saving data in files, spreadsheets, or databases for persistent use.
AT
5. Data Retrieval
Accessing stored data when needed for processing.
M
6. Data Processing
Analyzing, classifying, computing, and transforming data to generate meaningful results.
ED
7. Data Output
Presenting the results in the form of charts, tables, summaries, or reports.
M
Exam registration Student details, payment Validate data, assign roll no. Admit card
info
O
ATM withdrawal Account info, PIN Verify & deduct amount Currency,
M
receipt
Train ticket booking Journey info, payment Check availability, assign berth E-ticket
Example: [90, 102, 110, 115, 85, 90, 100, 110, 110]
→ Mean = 101.33
R
(B) Median
L
• If odd count → middle item
N
• If even count → average of two middle items
EE
Sorted Example: [85, 90, 90, 100, 102, 110, 110, 110, 115]
→ Median = 102
H
AT
(C) Mode
(A) Range
A
(B) Standard Deviation (𝜎) Measures how values differ from the mean.
∑(𝑥𝑖 − 𝑥)̄ 2
[𝜎 = √ ]
𝑛
Table 7.3: SD Calculation for Heights
• Mean = 101.33
• 𝑆𝐷 ≈ √(938/9) = 𝑎𝑝𝑝𝑟𝑜𝑥.10.21
R
L
Task Best Technique
N
Disparity in salaries Standard Deviation
EE
Average class performance Mean
Compare height in 2 cities Mean or SD
Popular car color
H Mode
AT
Find dominant data value Mode
Compare incomes Mean + SD
M
Term Explanation
M
Term Explanation
R
DBMS Software to manage large datasets efficiently
L
N
EE
H
AT
M
ED
M
M
A
H
O
M
CHAPTER NOTES
8.1 Introduction
Manual record-keeping systems are inefficient and prone to errors. Consider a teacher manually recording
attendance for 50 students over 26 working days: that results in 1,300 manual entries monthly!
R
L
Limitations of Manual Record-Keeping
N
2. Data redundancy and inconsistency due to repeated entries.
EE
3. Difficulty in modifying or retrieving information.
4. Risk of physical damage/loss.
5. Error-prone calculations.
H
AT
Why Move to Electronic Storage?
M
A file is a container on a computer to store data like text, code, images, videos, CSVs, etc.
H
• STUDENT
M
• ATTENDANCE
Roll
Number SName SDateofBirth GName GPhone GAddress
R
3 Taleem 2002-02- Himanshu 9818184855 26/77, West Patel Nagar,
Shah 28 Shah Ahmedabad
L
4 John 2003-08- Danny — S -13, Ashok Village, Daman
N
Dsouza 18 Dsouza
5 Ali Shah 2003-07- Himanshu 9818184855 26/77, West Patel Nagar,
EE
05 Shah Ahmedabad
6 Manika P. 2002-03- Sujata P. 7802983674 HNO-13, B- block, Preet Vihar,
10
H Madurai
AT
M
2018-09-01 6 Manika P. P
O
Problem Description
R
Data Redundancy Same data (e.g., guardian names)
L
repeated.
N
Data Inconsistency Inconsistent updates across files.
EE
Data Isolation No link/mapping between files.
Data Dependence Program changes needed when
structure changes.
Controlled Data Sharing H Difficult to manage user access levels.
AT
M
ED
A DBMS is software to store, manage, and retrieve logically related data efficiently.
M
M
• MySQL
A
• Oracle
H
• PostgreSQL
• SQL Server
O
• MS Access
M
• MongoDB
R
Online Shopping Items, users, preferences
L
File System to DBMS: Key Transformations
N
• Remove duplicated columns.
EE
• Split STUDENT table and creating another GUARDIAN table.
• By splitting the STUDENT file and creating a separate GUARDIAN table (linked using GUID),
the DBMS design removed redundancy.
ED
• Similarly, removing the student name from ATTENDANCE and linking it via RollNumber estab-
lished a clean reference.
M
GUID GAddress
R
5 Ali Shah 2003-07-05 101010101010
6 Manika P. 2002-03-10 466444444666
L
N
Table 8.5 — Snapshot of GUARDIAN Table
EE
GUID GName GPhone GAddress
2018-09-01 1 P
H
2018-09-01 2 P
O
2018-09-01 3 A
M
2018-09-01 4 P
2018-09-01 5 A
2018-09-01 6 P
2018-09-02 1 P
2018-09-02 2 P
2018-09-02 3 A
2018-09-02 4 A
2018-09-02 5 P
2018-09-02 6 P
R
L
Figure 8.2 — STUDENTATTENDANCE DBMS Environment
N
+---------------------+ +---------------------+
| Teacher | | Office Staff |
EE
+----------+----------+ +----------+----------+
| |
v v
H
AT
+-------------------------------------------+
| DBMS Software |
+-------------------------------------------+
M
| | |
v v v
ED
|
M
Database Catalog
A
Concept Description
M
Database Schema Structure of the database including table names, attributes, and constraints
Data Constraint Conditions imposed on values of attributes (e.g., NOT NULL, UNIQUE)
Meta-data Data about the data; includes schema and constraints
Database Instance Current snapshot of the data in the database
Query Request for accessing/manipulating data in the DBMS
Concept Description
R
The relational model stores data in the form of tables (relations) made up of attributes (columns) and
L
tuples (rows).
N
Table 8.7 — Relation Schemas
EE
Relation Attributes
STUDENT
H
RollNumber, SName, SDateofBirth, GUID
AT
ATTENDANCE AttendanceDate, RollNumber, AttendanceStatus
GUARDIAN GUID, GName, GPhone, GAddress
M
ED
Common Terminologies
Term Meaning
M
1. Properties of Attributes:
2. Properties of Tuples:
3. Properties of Values:
R
• All values in a column must be from the same domain.
L
Figure 8.4 — Relation GUARDIAN Example
N
GUID GName GPhone GAddress
EE
444444444444 Amit Ahuja 5711492685 G-35, Ashok Vihar, Delhi
111111111111 Baichung Bhutia 7110047139
H Flat no. 5, Darjeeling Appt., Shimla
AT
101010101010 Himanshu Shah 9818184855 26/77, West Patel Nagar, Ahmedabad
333333333333 Danny Dsouza — S -13, Ashok Village, Daman
M
R
L
Figure 8.5 — STUDENTATTENDANCE Schema Diagram
N
+-------------------------------+
EE
| STUDENT |
|-------------------------------|
| RollNumber (PK) |
| SName |
H
AT
| SDateofBirth |
| GUID (FK → GUARDIAN.GUID) |
M
+-------------------------------+
↑
|
ED
+-------------------------------+
| GUARDIAN |
M
|-------------------------------|
| GUID (PK) |
M
| GName |
| GPhone |
A
| GAddress |
H
+-------------------------------+
↑
O
|
M
+-------------------------------+
| ATTENDANCE |
|-------------------------------|
| AttendanceDate |
| RollNumber (FK → STUDENT) |
| AttendanceStatus |
| (PK = RollNumber + Date) |
+-------------------------------+
Summary of Chapter 8
R
• DBMS manages data efficiently, with support for querying and concurrent access.
• The relational model uses tables linked via keys.
L
• Primary keys uniquely identify rows; foreign keys link tables.
• All data is stored in atomic form with defined schemas and constraints.
N
EE
Summary of Key Terms
H
AT
Term Explanation
M
field.
Tuple A row in a table representing a single
record.
Domain Permissible set of values for an attribute.
Term Explanation
R
Candidate Key Attributes that qualify to be primary key.
L
Alternate Key Candidate key not chosen as primary
key.
N
Composite Key A primary key made up of multiple
EE
attributes.
Foreign Key Attribute referring to a primary key in
H another table.
AT
Query Request to retrieve or manipulate data in
the database.
M
unknown data.
A
CHAPTER NOTES
Introduction
R
• In the previous chapter, you learned about Relational Database Management Systems
(RDBMS) — systems that organize data in tables called relations.
L
• Examples of RDBMS:
N
– MySQL
– Microsoft SQL Server
EE
– PostgreSQL
– Oracle
H
AT
Purpose of RDBMS
• Allows us to:
M
• The tool used to perform all these actions is called SQL (Structured Query Language).
M
What is SQL?
A
• SQL (Structured Query Language) is a special-purpose language used to access and manipulate
data in a database.
H
• It is used instead of writing application programs, especially in the context of Database Man-
O
– MySQL
– ORACLE
– SQL Server
Feature Description
Easy to Learn SQL uses descriptive English words; it’s readable and intuitive.
Case-Insensitive Commands like SELECT and select are treated the same.
Declarative You tell SQL what you want, not how to do it.
R
Powerful SQL does more than just queries. It includes commands to define data,
insert data, update, and manage constraints.
L
N
Capabilities of SQL
EE
• Define data structures (tables, attributes, constraints)
• Manipulate data (insert, delete, update)
• Query data (retrieve specific or filtered data)
H
AT
• Declare constraints (rules on what kind of data can go into tables)
M
• The textbook uses the StudentAttendance database (introduced in Chapter 8) to explain SQL
ED
queries.
• Students will create, populate, and query this database using SQL.
M
What is MySQL?
A
– Once started, the terminal (or command-line interface) will show the prompt:
mysql>
Point Description
R
Case Insensitivity SQL keywords, table names, and column names are not case-sensitive.
End Statements with ;
L
Always terminate SQL commands with a semicolon.
Multiline Statements If an SQL statement is long: → Write it over multiple lines → Don’t
N
put ; until the last line → mysql> prompt changes to -> for
EE
continuation
H
Activity 9.1 Q: Find and list other types of databases besides RDBMS.
AT
Example Answers:
• Hierarchical databases
• Object-oriented databases
ED
• Network databases
M
• Each attribute:
H
– May have constraints — rules that restrict the values entered into that column.
M
R
to 65535. - Only actual input length occupies
space.
L
INT Integer values. - Occupies 4 bytes. - Use
N
BIGINT (8 bytes) for larger numbers.
EE
FLOAT Decimal (floating-point) numbers. - Occupies 4
bytes.
DATE
H
Stores dates in 'YYYY-MM-DD' format. - Range:
'1000-01-01' to '9999-12-31'.
AT
M
Activity 9.2: What other data types are supported in MySQL? Are there other variants of integer and
float?
ED
Examples:
9.3.2 Constraints
H
Definition: Constraints are rules or restrictions placed on data in a table to ensure accuracy and
O
reliability.
M
Constraint Description
Constraint Description
R
Used to create relationships.
L
N
Concept Check: Q: Which two constraints, when applied together, produce a Primary Key? NOT
NULL + UNIQUE
EE
9.4 SQL for Data Definition
H
AT
Purpose This section explains how to:
• Create a database
M
GUARDIAN)
SQL Command
SDateofBirth DATE,
GUID CHAR(12),
PRIMARY KEY (RollNumber)
);
DESCRIBE Output
R
+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
L
+--------------+-------------+------+-----+---------+-------+
| RollNumber | int | NO | PRI | NULL | |
N
| SName | varchar(20) | YES | | NULL | |
EE
| SDateofBirth | date | YES | | NULL | |
| GUID | char(12) | YES | | NULL | |
+--------------+-------------+------+-----+---------+-------+
H
AT
2. GUARDIAN Table Attributes & Description
M
The SHOW TABLES; command is used to list all tables present in the currently selected database.
Syntax:
SHOW TABLES;
Example:
R
USE StudentAttendance;
L
SHOW TABLES;
N
Output
EE
+------------------------------+
| Tables_in_studentattendance |
+------------------------------+
H
AT
| STUDENT |
| GUARDIAN |
| ATTENDANCE |
M
+------------------------------+
3 rows in set (0.00 sec)
ED
This shows that the database contains three tables: STUDENT, GUARDIAN, and ATTENDANCE.
M
Purpose of ALTER TABLE Once a table is created, you might need to:
A
H
All these structural changes are done using the ALTER TABLE command.
General Syntax:
ALTER TABLE table_name
<alteration_action>;
Example:
ALTER TABLE GUARDIAN
ADD PRIMARY KEY (GUID);
R
Composite Primary Key: Combines multiple columns to uniquely identify a record.
L
(B) Add Foreign Key to a Table
N
Ensure:
EE
• The referenced table exists.
• The referenced column is a primary key.
• Data types must match.
H
AT
Syntax:
M
Example:
M
(C) Add UNIQUE Constraint Ensures all values in a column are distinct.
H
O
Example:
M
Syntax:
ALTER TABLE table_name
ADD column_name datatype;
Example:
ALTER TABLE GUARDIAN
ADD Income INT;
R
(E) Modify Data Type of Attribute
L
N
Syntax:
EE
ALTER TABLE table_name
MODIFY column_name NEW_DATATYPE;
Example: H
AT
ALTER TABLE GUARDIAN
MODIFY GAddress VARCHAR(40);
M
Example:
M
Syntax:
M
Example:
ALTER TABLE STUDENT
MODIFY SDateofBirth DATE DEFAULT '2000-05-15';
Syntax:
ALTER TABLE table_name
DROP column_name;
Example:
R
ALTER TABLE GUARDIAN
L
DROP Income;
N
(I) Remove Primary Key
EE
Syntax:
ALTER TABLE table_name
H
AT
DROP PRIMARY KEY;
Example:
M
Note: Each table should have a primary key for data integrity. You can re-add it using ADD PRIMARY
KEY.
M
M
Add Primary To define a column(s) as a ALTER TABLE table_name ADD PRIMARY KEY
O
Add UNIQUE To ensure all values in a ALTER TABLE GUARDIAN ADD UNIQUE
Constraint column are unique (GPhone);
Add New To add a new column to an ALTER TABLE GUARDIAN ADD Income INT;
Attribute existing table
Modify Data To change data type of an ALTER TABLE GUARDIAN MODIFY GAddress
R
Type existing column VARCHAR(40);
L
Modify To enforce NOT NULL or ALTER TABLE STUDENT MODIFY SName
Constraint other constraints VARCHAR(20) NOT NULL;
N
Add To provide a default value ALTER TABLE STUDENT MODIFY SDateofBirth
EE
DEFAULT for a column DATE DEFAULT '2000-05-15';
Value
Remove
Attribute
To delete a column from a
table H
ALTER TABLE GUARDIAN DROP Income;
AT
Remove To drop an existing primary ALTER TABLE GUARDIAN DROP PRIMARY KEY;
Primary Key key
M
ED
Purpose of the DROP Statement The DROP statement in SQL is used to permanently delete a:
M
• Table, or
M
• Entire database
A
Once dropped:
H
A. DROP a Table
Syntax:
DROP TABLE table_name;
Example:
DROP TABLE STUDENT;
This command will delete the STUDENT table, including all its data and structure from the database.
B. DROP a Database
R
L
Syntax:
N
DROP DATABASE database_name;
EE
Example:
DROP DATABASE StudentAttendance;
H
This will delete the entire database and all tables (STUDENT, GUARDIAN, ATTENDANCE, etc.) within it.
AT
Important Notes:
M
• There is no undo for DROP. Once executed, the data is gone permanently.
• Always double-check before dropping tables or databases.
ED
• If you’re testing, it’s good practice to back up data or use temporary test tables.
• After defining tables (DDL), we use Data Manipulation Language (DML) commands to:
A
– Insert
H
– Update
O
– Delete
M
Use this when inserting values for all attributes in the same order as the table.
R
Result:
L
Query OK, 1 row affected (0.01 sec)
N
View the Inserted Record:
EE
SELECT * FROM GUARDIAN;
H
+--------------+--------------+-----------+----------------------------+
AT
| GUID | GName | GPhone | GAddress |
+--------------+--------------+-----------+----------------------------+
M
Or
+------------+--------------+--------------+--------------+
| RollNumber | SName | SDateofBirth | GUID |
+------------+--------------+--------------+--------------+
| 1 | Atharv Ahuja | 2003-05-15 | 444444444444 |
+------------+--------------+--------------+--------------+
R
Example 4: Insert Student with NULL GUID (Allowed)
L
INSERT INTO STUDENT
VALUES (3, 'Taleem Shah', '2002-02-28', NULL);
N
EE
Or using selected columns:
+------------+--------------+--------------+--------------+
| RollNumber | SName | SDateofBirth | GUID |
M
+------------+--------------+--------------+--------------+
M
+------------+--------------+--------------+--------------+
H
Tip:
O
If the order of attributes is not known, always use Syntax 2 (with column names).
M
Q: Can we insert two records with the same RollNumber? No, because RollNumber is a
PRIMARY KEY, it must be unique.
What is Data Querying? Once data is inserted into tables, we use SQL to retrieve specific infor-
mation. This process is called querying.
R
• Apply conditions to filter rows
L
N
EE
9.6.1 SELECT Statement Syntax:
Explanation:
ED
Output:
M
+------------+--------------+--------------+--------------+
M
Output:
+------------+--------------+
| RollNumber | SName |
+------------+--------------+
| 1 | Atharv Ahuja |
| 3 | Taleem Shah |
+------------+--------------+
R
WHERE GUID IS NOT NULL;
L
Output:
N
+------------+--------------+--------------+--------------+
EE
| RollNumber | SName | SDateofBirth | GUID |
+------------+--------------+--------------+--------------+
| 1 | Atharv Ahuja | 2003-05-15 | 444444444444 |
+------------+--------------+--------------+--------------+
H
AT
9.6.2 — Querying Using Database OFFICE
M
Context Many organizations manage data using databases like OFFICE, which include related ta-
bles such as EMPLOYEE and DEPARTMENT. Each employee belongs to a department, and the DeptId in
ED
R
SELECT EmpNo FROM EMPLOYEE;
L
Output:
N
+-------+
EE
| EmpNo |
+-------+
|
|
101 |
102 | H
AT
| 103 |
| 104 |
M
| 105 |
| 106 |
ED
| 107 |
| 108 |
| 109 |
M
| 110 |
+-------+
M
A
Query 2:
H
Output:
M
+-------+----------+
| EmpNo | Ename |
+-------+----------+
| 101 | Aaliya |
| 102 | Kritika |
| 103 | Shabbir |
| 104 | Gurpreet |
| 105 | Joseph |
| 106 | Sanya |
| 107 | Vergese |
| 108 | Nachaobi |
| 109 | Daribha |
| 110 | Tanya |
+-------+----------+
R
L
(B) Renaming Columns (Using Alias) Query:
N
SELECT Ename AS Name FROM EMPLOYEE;
EE
Output:
+----------+
| Name | H
AT
+----------+
| Aaliya |
M
| Kritika |
| Shabbir |
ED
| Gurpreet |
| Joseph |
| Sanya |
M
| Vergese |
| Nachaobi |
M
| Daribha |
A
| Tanya |
+----------+
H
O
Output:
+----------+-----------+
| Name | Salary*12 |
+----------+-----------+
| Aaliya | 120000 |
| Kritika | 720000 |
| Shabbir | 540000 |
| Gurpreet | 228000 |
| Joseph | 408000 |
| Sanya | 576000 |
| Vergese | 180000 |
| Nachaobi | 348000 |
R
| Daribha | 504000 |
L
| Tanya | 600000 |
+----------+-----------+
N
To rename the calculated column:
EE
Query (Using Alias with Space):
H
SELECT Ename AS Name, Salary*12 AS 'Annual Income' FROM EMPLOYEE;
AT
Output:
+----------+---------------+
M
| Aaliya | 120000 |
| Kritika | 720000 |
| Shabbir | 540000 |
M
| Gurpreet | 228000 |
M
| Joseph | 408000 |
| Sanya | 576000 |
A
| Vergese | 180000 |
| Nachaobi | 348000 |
H
| Daribha | 504000 |
O
| Tanya | 600000 |
M
+----------+---------------+
Note: Aliased column names with spaces should be enclosed in single quotes ('Annual Income').
(D) Using DISTINCT — To Avoid Duplicates Purpose: The DISTINCT clause is used to retrieve
unique values only, avoiding repetitions.
Query: Display Unique Department IDs
Output:
+--------+
| DeptId |
+--------+
| D01 |
R
| D02 |
| D04 |
L
| D03 |
N
| D05 |
+--------+
EE
Without DISTINCT, repeated DeptIds would be shown for each employee.
H
AT
(E) Using WHERE Clause — To Filter Rows Purpose: The WHERE clause helps select only those
rows that satisfy a specific condition.
M
Output:
M
+-------+----------+--------+-------+--------+
M
+-------+----------+--------+-------+--------+
| 102 | Kritika | 60000 | 123 | D01 |
H
Output:
+-------+--------+--------+-------+--------+
| EmpNo | Ename | Salary | Bonus | DeptId |
+-------+--------+--------+-------+--------+
| 101 | Aaliya | 10000 | 234 | D02 |
| 106 | Sanya | 48000 | 695 | D02 |
+-------+--------+--------+-------+--------+
R
Query 3: Employees with Salary > 25000
L
FROM EMPLOYEE
WHERE Salary > 25000;
N
Output:
EE
+-------+----------+--------+
| EmpNo | Ename | Salary |
H
AT
+-------+----------+--------+
| 102 | Kritika | 60000 |
| 103 | Shabbir | 45000 |
M
Query 4 Query: Display all details of employees from department D04 who earn more than 5000.
A
Output:
M
+-------+----------+--------+-------+--------+
| EmpNo | Ename | Salary | Bonus | DeptId |
+-------+----------+--------+-------+--------+
| 104 | Gurpreet | 19000 | 565 | D04 |
| 109 | Daribha | 42000 | NULL | D04 |
+-------+----------+--------+-------+--------+
Query 5
Query: Display all employee records except Aaliya.
Output:
+-------+----------+--------+-------+--------+
R
| EmpNo | Ename | Salary | Bonus | DeptId |
L
+-------+----------+--------+-------+--------+
| 102 | Kritika | 60000 | 123 | D01 |
N
| 103 | Shabbir | 45000 | 566 | D01 |
| 104 | Gurpreet | 19000 | 565 | D04 |
EE
| 105 | Joseph | 34000 | 875 | D03 |
| 106 | Sanya | 48000 | 695 | D02 |
| 107 | Vergese | 15000 | NULL | D01 |
H
AT
| 108 | Nachaobi | 29000 | NULL | D05 |
| 109 | Daribha | 42000 | NULL | D04 |
| 110 | Tanya | 50000 | 467 | D05 |
M
+-------+----------+--------+-------+--------+
ED
FROM EMPLOYEE
WHERE Salary BETWEEN 20000 AND 50000;
M
Output:
A
H
+----------+--------+
| Ename | DeptId |
O
+----------+--------+
M
| Shabbir | D01 |
| Joseph | D03 |
| Sanya | D02 |
| Nachaobi | D05 |
| Daribha | D04 |
| Tanya | D05 |
+----------+--------+
Query 7 Query: Employees from departments D01, D02, or D04 using OR:
Output:
R
L
+-------+----------+--------+-------+--------+
| EmpNo | Ename | Salary | Bonus | DeptId |
N
+-------+----------+--------+-------+--------+
| 101 | Aaliya | 10000 | 234 | D02 |
EE
| 102 | Kritika | 60000 | 123 | D01 |
| 103 | Shabbir | 45000 | 566 | D01 |
| 104 | Gurpreet | 19000 | 565 | D04 |
H
AT
| 106 | Sanya | 48000 | 695 | D02 |
| 107 | Vergese | 15000 | NULL | D01 |
| 109 | Daribha | 42000 | NULL | D04 |
M
+-------+----------+--------+-------+--------+
ED
(F) Using IN — Multiple Matching Values Purpose: The IN operator allows checking if a value
matches any value in a list.
M
Output:
H
O
+-------+----------+--------+-------+--------+
M
Query: Select all employees except those working in departments D01 or D02.
R
WHERE DeptId NOT IN ('D01', 'D02');
L
Output:
N
+-------+----------+--------+-------+--------+
EE
| EmpNo | Ename | Salary | Bonus | DeptId |
+-------+----------+--------+-------+--------+
| 104 | Gurpreet | 19000 | 565 | D04 |
| 105 | Joseph | 34000 | 875 | D03 |
H
AT
| 108 | Nachaobi | 29000 | NULL | D05 |
| 109 | Daribha | 42000 | NULL | D04 |
M
(G) Using IS NULL — Check for Missing Data Purpose: To check whether a column contains a
NULL (empty) value.
M
Output:
O
+-------+----------+-------+
M
Query: Select names of employees with bonus and working in department D01.
Output:
R
L
+----------+
| EName |
N
+----------+
EE
| Kritika |
| Shabbir |
+----------+
H
AT
(H) Using LIKE — Pattern Matching Purpose: The LIKE operator is used to match text patterns
using wildcards:
M
Output:
A
+----------+
H
| Ename |
O
+----------+
| Shabbir |
M
| Sanya |
+----------+
Output:
+----------+
| Ename |
+----------+
| Aaliya |
| Kritika |
| Sanya |
R
| Daribha |
L
| Tanya |
+----------+
N
EE
Query: Names containing ‘ya’
+--------+
M
| Ename |
+--------+
ED
| Sanya |
| Tanya |
M
+--------+
M
Output:
O
M
+-------+---------+--------+-------+--------+
| EmpNo | Ename | Salary | Bonus | DeptId |
+-------+---------+--------+-------+--------+
| 102 | Kritika | 60000 | 123 | D01 |
+-------+---------+--------+-------+--------+
Query: Select employees whose name ends with ‘a’ and earn salary > 45000.
Output:
+-------+--------+--------+-------+--------+
| EmpNo | Ename | Salary | Bonus | DeptId |
R
+-------+--------+--------+-------+--------+
| 102 | Kritika| 60000 | 123 | D01 |
L
| 106 | Sanya | 48000 | 695 | D02 |
| 110 | Tanya | 50000 | 467 | D05 |
N
+-------+--------+--------+-------+--------+
EE
Query: Select employees whose names are exactly 5 letters and have ‘ANYA’ starting from second
character.
H
AT
SELECT * FROM EMPLOYEE
WHERE Ename LIKE '_ANYA';
M
Output:
ED
+-------+-------+--------+-------+--------+
| EmpNo | Ename | Salary | Bonus | DeptId |
+-------+-------+--------+-------+--------+
M
+-------+-------+--------+-------+--------+
A
H
Purpose of ORDER BY The ORDER BY clause in SQL is used to sort the result set of a query by:
O
Basic Syntax:
Output:
+----------+--------+
R
| Ename | Salary |
+----------+--------+
L
| Aaliya | 10000 |
N
| Vergese | 15000 |
| Gurpreet | 19000 |
EE
| Joseph | 34000 |
| Nachaobi | 29000 |
| Shabbir | 45000 |
H
AT
| Daribha | 42000 |
| Sanya | 48000 |
| Tanya | 50000 |
M
| Kritika | 60000 |
+----------+--------+
ED
Output:
O
+----------+--------+
M
| Ename | Salary |
+----------+--------+
| Kritika | 60000 |
| Tanya | 50000 |
| Sanya | 48000 |
| Shabbir | 45000 |
| Daribha | 42000 |
| Joseph | 34000 |
| Nachaobi | 29000 |
| Gurpreet | 19000 |
| Vergese | 15000 |
| Aaliya | 10000 |
+----------+--------+
R
L
9.7 — Data Updation and Deletion
N
9.7.1 Data Updation Syntax:
EE
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
H
AT
Caution: Missing the WHERE clause will update all rows.
The student with roll number 3 is a sibling of student 5, so assign same GUID.
ED
Output:
M
Output:
After Update:
R
+--------------+---------------+------------+--------------------------------------+
L
| GUID | GName | GPhone | GAddress |
N
+--------------+---------------+------------+--------------------------------------+
| 444444444444 | Amit Ahuja | 5711492685 | G-35, Ashok Vihar, Delhi |
EE
| 111111111111 | Baichung B. | 7110047139 | Flat 5, Darjeeling Appt., Shimla |
| 101010101010 | Himanshu Shah | 9818184855 | 26/77, West Patel Nagar, Ahmedabad |
| 333333333333 | Danny Dsouza | NULL
| 466444444666 | Sujata P. H
| S -13, Ashok Village, Daman
| 9010810547 | WZ - 68, Azad Avenue, Bijnour, MP
|
|
AT
+--------------+---------------+------------+--------------------------------------+
M
Caution: Omitting WHERE will delete all records from the table.
M
Output:
O
M
After Deletion:
+------------+--------------+--------------+--------------+
| RollNumber | SName | SDateofBirth | GUID |
+------------+--------------+--------------+--------------+
| 1 | Atharv Ahuja | 2003-05-15 | 444444444444 |
| 3 | Taleem Shah | 2002-02-28 | 101010101010 |
| 4 | John Dsouza | 2003-08-18 | 333333333333 |
| 5 | Ali Shah | 2003-07-05 | 101010101010 |
| 6 | Manika P. | 2002-03-10 | 466444444666 |
R
+------------+--------------+--------------+--------------+
L
9.8: Functions in SQL
N
EE
Introduction Functions in SQL are predefined commands that perform operations on data. They are
used for:
• Performing calculations
H
AT
• Modifying strings
• Extracting date components
• Summarizing data
M
1. Single Row Functions (Scalar Functions): Operate on individual row values (return one result
per row)
2. Multiple Row Functions (Aggregate Functions): Work on groups of rows (return one result per
M
group)
M
• CUSTOMER
• EMPLOYEE
• INVENTORY
• SALE
R
L
1. Single Row (Scalar) Functions
N
A. Math Functions
EE
Function Description Example Output
1. GST Calculation:
M
3. Rounded Commission:
M
B. String Functions
R
LEFT(str,n) Leftmost n characters SELECT LEFT(‘Email’, 4); Emai
L
INSTR(s,sub)Position of substring in string SELECT 6
N
INSTR(‘Informatics’,‘ma’);
EE
TRIM() Remove leading/trailing/specific SELECT TRIM(‘.com’ FROM abc@gmail
chars ‘[email protected]’);
C. Date Functions
M
R
DAYNAME(‘2019-07-11’);
L
N
Examples with EMPLOYEE table:
EE
1. DOJ components:
3. Day of birth:
ED
FROM MANAGER;
M
COUNT(DISTINCT)
Unique values SELECT COUNT(DISTINCT Model) 6
FROM INVENTORY;
SUM() Total of numeric column SELECT SUM(Price) FROM 4608733.00
INVENTORY;
AVG() Average of numeric column SELECT AVG(Price) FROM 576091.625
INVENTORY;
R
Examples with INVENTORY/SALE tables:
L
1. Count cars with model VXI:
N
SELECT COUNT(*) FROM INVENTORY WHERE Model = 'VXI';
EE
2. Distinct models:
Basic Syntax:
A
FROM table_name
O
GROUP BY column_name;
M
Output:
+--------+------------------+
R
| CustID | Number of Cars |
+--------+------------------+
L
| C0001 | 2 |
N
| C0002 | 2 |
| C0003 | 1 |
EE
| C0004 | 1 |
+--------+------------------+
H
AT
Displays how many cars each customer bought
Output:
M
+----------+---------------------------+
| Model | COUNT(DISTINCT EmpID) |
A
+----------+---------------------------+
H
| LXI | 2 |
| VXI | 1 |
O
+----------+---------------------------+
M
Combines two tables using JOIN condition (implicit syntax), then groups
Output:
+--------------+----------+
| PaymentMode | COUNT(*) |
+--------------+----------+
| Cheque | 1 |
| Credit Card | 1 |
| Online | 1 |
R
+--------------+----------+
L
Finds frequency of each payment type
N
Display Customers Who Bought More Than 1 Car
EE
SELECT CustID, COUNT(*)
FROM SALE
GROUP BY CustID
HAVING COUNT(*) > 1; H
AT
Output:
M
+--------+----------+
| CustID | COUNT(*) |
ED
+--------+----------+
| C0001 | 2 |
M
| C0002 | 2 |
+--------+----------+
M
Displays customers and number of cars bought, but only if more than 1 car was purchased.
A
FROM SALE
M
GROUP BY PaymentMode
HAVING COUNT(*) > 1
ORDER BY PaymentMode;
Output:
+--------------+--------------------+
| PaymentMode | Count(PaymentMode) |
+--------------+--------------------+
| Bank Finance | 2 |
| Credit Card | 2 |
+--------------+--------------------+
Filters only those payment modes used more than once, after grouping all SALE records by Payment-
Mode.
R
9.10 – Operations on Relations
L
Introduction SQL allows operations that involve multiple tables (relations). These are called set
N
operations and work when:
EE
• Both tables have the same number of columns
• Corresponding columns have the same data types (domain compatibility)
1 Aastha 7A
2 Mahira 6A
3 Mohit 7B
4 Sanjay 7A
Table: MUSIC
1 Mehak 8A
2 Mahira 6A
3 Lavanya 7A
4 Sanjay 7A
R
5 Abhay 8A
L
9.10.1 – UNION ( ∪ ) Query:
N
SELECT * FROM DANCE
EE
UNION
SELECT * FROM MUSIC;
1 Aastha 7A
2 Mahira 6A
ED
3 Mohit 7B
4 Sanjay 7A
M
1 Mehak 8A
M
3 Lavanya 7A
A
5 Abhay 8A
H
O
2 Mahira 6A
4 Sanjay 7A
R
Finds students common to both DANCE and MUSIC
L
N
EE
9.10.3 – MINUS ( - ) Query:
1 Mehak 8A
3 Lavanya 7A
M
5 Abhay 8A
M
• Degree (columns): 6
• Cardinality (rows): 4 × 5 = 20 rows
1 Aastha 7A 1 Mehak 8A
1 Aastha 7A 2 Mahira 6A
… … … … … …
4 Sanjay 7A 5 Abhay 8A
R
Generates all possible combinations of students from both tables
L
N
EE
H
AT
M
ED
M
M
A
H
O
M
CHAPTER NOTES
What is a Network? A network is a group of interconnected entities. These can be: - People (like
in social networks) - Systems (like in mobile networks) - Devices (like in computer networks)
R
L
What is a Computer Network? A Computer Network is: - A system where two or more computers
or computing devices are interconnected. - Allows devices to share data and resources.
N
EE
Size and Scale
H
• Large networks can span buildings, cities, or countries.
AT
What Makes Up a Network?
M
• Communication Media:
Data Transfer
A
Benefits of Networks
• In the 1960s, the U.S. Department of Defence initiated a project called ARPANET through its
Advanced Research Projects Agency (ARPA).
• Objective: Connect academic and research institutions for scientific collaboration.
• First message was transmitted between:
R
– University of California, Los Angeles (UCLA)
– Stanford Research Institute (SRI)
L
N
Key Milestones in Networking Evolution Here is a timeline of major events:
EE
Year Event
1961
H
Concept of ARPANET was proposed.
AT
1969 ARPANET became functional (UCLA ↔ SRI).
1971 Email (E-mail) developed by Ray Tomlinson;
M
ARPANET.
1982 The term “Internet” was coined.
M
Computer networks vary in size, coverage area, and data transfer speed. Based on these characteristics,
networks are broadly categorized as:
R
• Range: Up to 10 meters.
L
• Can be wired (e.g., USB cable between phone and laptop) or wireless (e.g., Bluetooth between
smartphones).
N
Examples: - Smartphone connected to a printer via Bluetooth. - Laptop connected to phone using a USB
EE
cable.
Features: - Range: Up to 1 km. - High-speed data transfer: - Ethernet: 10 Mbps - Gigabit Ethernet:
ED
1000 Mbps - Secure: Only authorized users can access shared resources. - Devices can share printers,
access servers, and transfer files.
M
Range: Up to 30–40 km
M
Examples: - The Internet: Largest example of a WAN - Large business or government networks linking
offices globally
Think About This: If you’re accessing your bank account from another city, what type of network is
enabling that access?
It’s a WAN.
To establish communication and functionality in a network, various hardware devices are used. Here’s
R
a breakdown of key devices:
L
10.4.1 Modem
N
• Full Form: MOdulator-DEModulator
• Purpose: Converts digital data (used by computers) to analog signals (used for transmission) and
EE
vice versa.
• Usage:
H
– At sender’s end: Converts digital → analog (modulation)
AT
– At receiver’s end: Converts analog → digital (demodulation)
10.4.4 Repeater
10.4.5 Hub
10.4.6 Switch
R
Smarter than a hub.
• Sends data only to the intended recipient using the destination address in the packet.
L
• More secure and efficient than hubs.
• Can filter corrupted data and ask for retransmission.
N
• Commonly used in homes and offices to create LANs.
EE
10.4.7 Router
•
H
Connects different networks, including LAN to the Internet.
AT
• Can analyze, alter, and repackage data as per the network type.
• May be wired or wireless.
• Home routers often work as a modem + router + switch.
M
10.4.8 Gateway
ED
• Acts as a gate between a local network and the outside world (e.g., the Internet).
• All incoming/outgoing data passes through the gateway.
M
Example: Your home Internet provider acts as the gateway to the Internet.
A
H
What is a Topology?
M
R
10.5.2 Ring Topology
L
• Each node is connected to two other nodes, forming a ring.
• Data travels in one direction (either clockwise or counterclockwise).
N
• Limitation: If one node fails, it can affect the whole network.
EE
10.5.3 Bus Topology
•
H
All nodes are connected to a single communication line (bus or backbone).
AT
• Cost-effective and easy to install.
• Data travels along the bus and is available to all connected devices.
M
• Advantages:
Reflection:
How do bus and ring topologies behave when a node goes down? - In bus: The whole network may fail.
- In ring: Data cannot be passed beyond the failed node.
To ensure data reaches the correct destination in a network, each node (device) must have a unique
R
identity. Two primary identifiers are used:
L
10.6.1 MAC Address (Media Access Control Address)
N
• Definition: A permanent, unique hardware address assigned to a device’s Network Interface
EE
Card (NIC).
• Also called: Physical Address or Hardware Address.
• Burned into the NIC during manufacturing and cannot be changed.
Structure: H
AT
• 12-digit hexadecimal number (48 bits)
M
• Definition: A logical address assigned to a device on a network that uses the Internet Protocol.
A
Versions:
O
M
• 32-bit address
• Written as four decimal numbers separated by dots (e.g., 192.168.0.178)
• Each part ranges from 0–255
• Limited to ~4.3 billion addresses
• 128-bit address
• Written in 8 groups of hexadecimal numbers separated by colons
• Example: 2001:CDBA:0000:0000:0000:0000:3257:9652
• Designed to support the growing number of devices on the Internet
Activity Suggestion: Explore how to find the MAC address of your computer system (e.g., using
ipconfig /all in Windows or ifconfig in Linux/macOS).
R
L
10.7: Internet, Web, and the Internet of Things (IoT)
N
10.7.1 The Internet
EE
• The Internet is a global network connecting billions of devices—like desktops, laptops, smart-
phones, tablets, routers, and smart appliances.
• These devices communicate using standardized protocols, allowing data to travel around the
world. H
AT
Examples of Internet-enabled devices: - Computers, printers, scanners - Smart devices: TVs, ACs,
refrigerators, lights, fans, security cameras - Modern IoT devices: drones, smart vehicles, door locks
M
• The WWW is a collection of interlinked web pages and resources, stored on web servers and
O
R
• A set of rules for retrieving linked pages from the web.
• HTTPS is the secure version of HTTP.
L
Internet ≠ Web: - Internet: The underlying network infrastructure (hardware + communication). - Web:
N
The content (documents, multimedia, etc.) shared and retrieved over the Internet.
EE
Discussion Prompt: What areas of life (like traffic management or health monitoring) do you think IoT
can improve?
H
AT
10.8: Domain Name System (DNS)
Why DNS is Needed Every website or server on the Internet is stored on a device with an IP address.
M
Example:
ncert.nic.in 164.100.60.233
cbse.nic.in 164.100.107.32
mhrd.gov.in 164.100.163.45
wikipedia.org 198.35.26.96
R
• Converts a domain name → IP address.
L
• This process is called Domain Name Resolution.
How it works:
N
EE
1. You type a URL in your browser (e.g., www.ncert.nic.in).
2. Your browser contacts a DNS server to find the IP address.
3. The DNS server replies with the correct IP (e.g., 164.100.60.233).
4. Your browser uses the IP to retrieve the webpage.
H
AT
Illustration:
M
– 10 in the US
A
– 1 in London
H
– 1 in Stockholm
– 1 in Japan
O
CHAPTER NOTES
R
• Data can be:
L
– Text
N
– Image
EE
– Audio
– Video H
AT
– Multimedia
M
– Networked/Connected
A
Examples of Devices
• Personal computers
• Laptops
• Mobile phones
• Printers
• Servers
• Switches
Any successful data communication involves the following five essential components:
1. Sender
R
2. Receiver
L
• Device that receives data.
N
• Can be: Printer, laptop, mobile phone, TV, etc.
EE
• Both sender and receiver are also called nodes in a network.
3. Message
H
AT
• The data or information being exchanged.
• Can be in the form of:
M
– Text
– Numbers
– Images
ED
– Audio
– Video
M
– Multimedia
M
4. Communication Medium
A
5. Protocol
In data communication, the transmission medium (also called a channel) has a capacity, which deter-
mines how much data it can carry.
11.3.1 Bandwidth
R
• Definition: Bandwidth is the range of frequencies available for data transmission through a chan-
L
nel.
• It is the difference between the maximum and minimum frequencies that a channel can carry.
N
• Higher bandwidth = higher data transfer rate
• Unit of measurement: Hertz (Hz)
EE
Conversion Units:
• Definition: Data Transfer Rate (also called bit rate) is the number of bits transmitted per second
between the source and destination.
M
Common Units:
H
O
Unit Value
M
R
Solution:
- Total bits = 10 × 1600 × 8 = 128,000 bits
L
- Time = 20 seconds
N
- Data rate = 128,000 / 20 = 6,400 bps
EE
11.4: Types of Data Communication
H
Data is exchanged as signals between two or more devices/nodes over communication channels. De-
pending on the direction of data flow, communication can be of three types:
AT
11.4.1 Simplex Communication
M
Analogy:
M
• Like a one-way street — vehicles (data) can move in only one direction.
A
Examples:
H
• Keyboard to computer
O
• Speaker output
M
Examples:
• Walkie-talkie: Press-to-talk — while one speaks, others listen.
R
L
How It Works:
• Either:
N
– Two separate channels: One for sending, one for receiving
EE
OR
– One channel split to handle both directions at the same time
H
AT
Examples:
• Mobile phones
M
• Landline telephones
• Online video conferencing
ED
Analogy:
• Like a two-lane road — traffic moves in both directions at the same time.
M
M
When multiple devices exist in a network, we need a way to establish communication between sender
H
and receiver efficiently. Instead of creating permanent links (which are expensive in large networks),
switching techniques are used.
O
Switching involves temporarily routing data through various network nodes to reach the destination.
M
Real-life Example:
Features:
• Reliable
• All data follows the same path
R
• Useful for real-time communication
L
Limitation:
N
• Path is reserved, even if no data is being transferred — wastes resources
EE
11.5.2 Packet Switching
Packet Structure:
ED
Features:
M
Examples:
M
• Internet
• Email
• Streaming services
R
Suitability Voice calls Data communication (Internet, VoIP)
L
11.6: Transmission Media
N
What is a Transmission Medium? A transmission medium is anything that can carry signals or
EE
data from a sender (source) to a receiver (destination).
Examples:
- Wires, cables (in case of fans, bulbs, etc.) H
AT
- Air (when two people talk or devices communicate wirelessly)
M
In guided media, data travels through a physical path like wires or cables.
A
H
• Made of two insulated copper wires twisted together like a DNA helix.
• Often bundled into larger cables with many such pairs.
M
Types:
• UTP (Unshielded Twisted Pair)
• STP (Shielded Twisted Pair) — has extra shielding for noise protection
– Insulating material
– Outer conductor (copper mesh) for shielding
– Plastic covering
R
• Used in:
– Cable TV
L
– High-frequency signals over longer distances
N
EE
(C) Optical Fiber Cable
Advantages:
M
• High bandwidth
• Long-distance transmission
M
Disadvantages:
H
• Expensive
O
Here, data is transmitted using electromagnetic waves through the air via antennas.
Frequency Range:
• Divided into:
– Radio Waves
– Microwaves
– Infrared Waves
R
– Light Waves (Visible spectrum)
L
Electromagnetic Waves Overview
N
EE
Radio Waves (3 KHz – 1 GHz)
• Omnidirectional
• Can penetrate walls
• Used in: H
AT
– AM/FM Radio
M
– TV
– Cordless phones
ED
• Unidirectional
M
• Needs line-of-sight
M
• Used in:
– Satellite communication
A
– Radar
H
– Mobile phones
O
– TV remotes
– Bluetooth devices
– Mobile-to-printer or mobile-to-mobile connections
Wireless technologies enable devices to communicate without physical cables, using electromagnetic
waves over the air. Here are the major types discussed:
(A) Bluetooth
R
• Connects devices like:
L
– Mobile phones
– Headphones
N
– Printers
EE
– Keyboards
– Mice
– Computers
H
AT
Key Features:
• Speed: 1 to 2 Mbps
• Range: Up to 10 meters
ED
Network Type:
– Total up to 255 devices can be part of a piconet, but only 8 are active at a time.
O
Key Components:
Advantages:
R
L
(C) WiMAX (Worldwide Interoperability for Microwave Access)
• Similar to Wi-Fi but with a larger coverage area and higher data rates.
N
• Used in MAN (Metropolitan Area Network) applications.
EE
Key Features:
Mobile telecommunication allows wireless communication while on the move — this includes calls,
text messaging, and Internet access. With time, mobile network technologies have progressed through
M
– Internet browsing
– Video calling
– Mobile apps
R
• Voice and Internet used the same radio towers.
L
4G (Fourth Generation)
N
• Much faster than 3G.
EE
• Enhanced Internet experiences with:
– HD streaming
–
–
Video conferencing
Online gaming H
AT
– Interactive multimedia services
• Will support:
– Smart cities
– Connected vehicles
O
M
Key Concepts:
• IoT: Enables devices (like smart bulbs, ACs, cars) to communicate over the Internet.
• M2M: Direct device-to-device communication without human intervention.
11.8: Protocol
What is a Protocol? A protocol is a set of rules and standards that define how devices communicate
over a network.
It ensures proper: - Data transmission - Error handling - Authentication - Synchronization
R
11.8.1 Need for Protocols Protocols handle critical functions like:
L
Flow Control
N
• Regulates data speed between sender and receiver.
EE
• Example: If sender is faster than the receiver, data may get lost unless sender slows down.
– Example case:
Access Control
• Decides which device gets to send data on a shared medium to avoid data collisions.
M
M
Addressing
• Helps with:
– Packet order
– Missing data
– Data reassembly
R
• Works over TCP (Transmission Control Protocol).
• Handles web commands like loading a webpage or clicking a link.
L
N
(B) FTP – File Transfer Protocol
EE
• Used to transfer files between two systems.
• Also follows the client-server model.
• Optionally requires username & password.
• Handles:
H
AT
– Differences in file formats
– Directory structures
M
• Used for direct link between two devices (like routers or modems).
M
– Device authentication
A
– Packet order
– Error reporting and recovery
H
O
IP (Internet Protocol) - Assigns unique addresses (IP addresses) to each device. - Routes packets
through the Internet.
TCP (Transmission Control Protocol) - Breaks data into packets. - Ensures delivery and correct order.
R
- Handles packet reassembly at the receiver.
L
Recap:
N
• HTTP: Web browsing
EE
• FTP: File transfer
CHAPTER NOTES
R
• Isolation as Ideal
L
N
• Connectedness as Reality
EE
– Modern computing requires connectivity; complete isolation is not feasible.
3. Key Terminology
M
• Prevention focuses on identifying and mitigating these threats before they succeed.
12.2 - Malware
Definition:
- Malware = MALicious softWARE.
- Software developed to damage hardware, steal data, or cause trouble for the user.
- Causes financial damages worth billions annually.
Common Types:
R
- Viruses
- Worms
L
- Ransomware
- Trojans
N
- Spyware
EE
- Adware
- Keyloggers
12.2.1 Virus H
AT
• Coined by Fred Cohen in 1985.
M
• Behaves like a biological virus: infects by copying/inserting its code into executable files.
ED
• Common motives: steal passwords/data, corrupt files, spam contacts, control machines.
A
12.2.2 Worms
M
• Examples: Storm Worm, Sobig, MSBlast, Code Red, Nimda, Morris Worm.
12.2.3 Ransomware
• Example: WannaCry (May 2017) infected ~200,000 computers across 150 countries; encrypted
data and demanded Bitcoin ransom.
R
12.2.4 Trojan
L
• Named after the wooden horse of Troy.
N
EE
• Appears as legitimate software to trick users into installing.
• Does not self-replicate or infect other files; spreads via user action (e.g., email attachments).
H
AT
• Often creates backdoors for remote access.
M
12.2.5 Spyware
• Records and sends data (e.g., browsing habits, credentials) to external entities.
M
12.2.6 Adware
A
• Generally annoying but can pave the way for more dangerous malware via unsafe links.
12.2.7 Keyloggers
R
• Countermeasure: Use an online virtual keyboard (randomized layout) instead of fixed on-screen
keyboard to thwart software keyloggers.
L
– On-screen keyboard: fixed QWERTY layout (vulnerable).
N
– Online virtual keyboard: randomizes keys each use (more secure).
EE
12.2.8 Modes of Malware Distribution
H
1. Downloaded from the Internet: disguised as free software/files.
AT
2. Spam Email: unsolicited emails with malicious links or attachments.
M
3. Removable Storage Devices: infects USB drives, SSD cards, etc., then transfers to other systems.
ED
4. Network Propagation: some malware (e.g., worms) spread through network connections.
M
Preventive Measures:
- Use and regularly update antivirus/anti-malware software.
- Configure browser security settings.
- Check for lock icon (HTTPS) when making payments.
- Avoid pirated or unlicensed software; prefer FOSS.
R
- Close pop-ups via the window’s “X” rather than in-ad buttons; cancel installations immediately if
L
launched.
N
12.3 - Antivirus
EE
Definition:
- Antivirus (also called anti-malware) is software initially developed to detect and remove viruses.
H
- Evolved to include prevention, detection, and removal of a wide range of malware.
AT
12.3.1 Methods of Malware Identification Antivirus programs employ multiple techniques to iden-
M
1. Signature-Based Detection
ED
• Uses a database of known virus signatures called the Virus Definition File (VDF).
M
• VDF must be updated continuously; outdated VDF renders antivirus ineffective against new
threats.
M
A
2. Sandbox Detection
O
• Safer but slower, as it isolates unknown code from actual system resources.
• Applies data mining and machine learning to classify files as benign or malicious.
4. Heuristics
• Compares source code of suspect programs against known malware patterns in a heuristic
database.
• Flags code as malicious if it shares a significant pattern match with known malware.
5. Real-Time Protection
R
• Runs in the background, monitoring active memory for suspicious behavior.
L
• Detects malware that is dormant at startup but activates later.
N
12.4 - Spam
EE
• Definition:
H
– Broad term for unwanted digital content across email, messaging, forums, chat, and adver-
AT
tising.
• How It Works:
ED
– Fills recipients’ inboxes with junk, aiming to trick users into purchases or malware down-
loads.
A
– Modern services (e.g., Gmail, Hotmail) use automatic spam-detection algorithms to filter
O
unsolicited mail.
M
– Users can manually mark undetected spam as “spam,” training the filter to block similar future
messages.
– Sends information “in the clear” (unencrypted), making it vulnerable to interception by at-
tackers.
R
– Decrypts data at the receiver’s end to recover the original content.
L
– Requires an SSL digital certificate on the server.
N
• Use Cases:
EE
– HTTP: Suitable for websites with purely public information (e.g., news portals, blogs).
H
– HTTPS: Essential for sites handling personal data, banking credentials, passwords.
AT
– Always look for “https://” (and a lock icon) in the address bar when entering sensitive infor-
mation.
M
12.6 - Firewall
ED
• Definition:
M
– A network security system designed to protect a trusted private network from unauthorized
access or traffic originating from an untrusted outside network (e.g., the Internet or other
M
network segments).
A
• Function:
O
– Continuously monitors and controls incoming and outgoing traffic based on predefined
security rules.
– Example rule: School LAN prevents students from accessing finance server, while allowing
accountants to connect.
1. Network Firewall
2. Host-based Firewall
R
• Installed on individual computers.
L
• Monitors and controls traffic to and from that single host.
N
EE
12.7 - Cookies
• Origin of Term:
H
– Derived from the Unix “magic cookie”: a data packet received and returned unchanged by a
AT
program.
• Definition:
M
• Common Uses:
M
– Preferences: Language choice, search queries, recently viewed pages, autofill data (name,
M
• Supercookies/Zombie Cookies:
• Third-Party Tracking:
– Third-party cookies may share user data without consent for advertising/tracking.
– E.g., search for an item—later see ads for similar items on other websites.
• Precautions:
R
– Be careful granting sites permission to create/store cookies on your device.
L
12.8 - Hackers and Crackers
N
• Definitions:
EE
– Hackers/Crackers: Individuals with deep knowledge of computer systems, operating sys-
tems, networks, and programming who exploit vulnerabilities to gain unauthorized access.
• Categories by Intent: H
AT
1. White Hats (Ethical Hackers)
M
3. Grey Hats
M
• DoS Attack: Attacker floods a resource with illegitimate requests, making it unavailable to legiti-
mate users.
– E.g., overloading a web server with massive packets so it can’t respond to real traffic.
• Recovery:
– More difficult to mitigate because attack traffic originates from many sources.
R
L
12.9.2 Intrusion Problems
N
• Network Intrusion: Any unauthorized activity on a network (e.g., DoS, Trojans, worms).
EE
• Other Intrusion Attacks:
1. Asymmetric Routing:
H
– Attacker sends intrusion packets via multiple paths to bypass intrusion sensors.
AT
2. Buffer Overflow Attacks:
M
3. Traffic Flooding:
– Overwhelms intrusion detection systems with packets, preventing proper monitoring.
M
• Method:
H
O
– Taps into communication channel, reads packets, then re-injects them so network appears
normal.
M
• Use Cases:
• Tools:
12.9.4 Eavesdropping
R
• Difference from Snooping:
L
– Eavesdropping: Live interception; doesn’t store for later.
N
– Snooping: Captures traffic for later analysis.
EE
• Examples:
https://matheenhere.blogspot.com
M
M
A
H
O
M