100% found this document useful (1 vote)
3K views149 pages

Second Puc Computer Science Notes Complete

This document contains student notes for Second PUC Computer Science, focusing on topics such as exception handling and file handling in Python. It includes detailed sections on syntax errors, built-in exceptions, raising exceptions, and various file operations like reading and writing. The notes serve as a comprehensive guide for students studying Python programming.

Uploaded by

sureshdn1997
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
3K views149 pages

Second Puc Computer Science Notes Complete

This document contains student notes for Second PUC Computer Science, focusing on topics such as exception handling and file handling in Python. It includes detailed sections on syntax errors, built-in exceptions, raising exceptions, and various file operations like reading and writing. The notes serve as a comprehensive guide for students studying Python programming.

Uploaded by

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

M

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

CHAPTER 1: EXCEPTION HANDLING IN PYTHON 9


CHAPTER SYNOPSIS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Syntax Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

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

CHAPTER 2: FILE HANDLING IN PYTHON 19


Introduction to Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
ED

Types of Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Binary Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
M

Opening and Closing a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19


Opening a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
M

File Access Modes with Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20


A

File Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Closing a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
H

Opening a File Using with Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21


O

File Access Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22


File Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
M

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
2
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

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

Syntax for load() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28


Example for dump() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
M

Example for load() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28


Complete Program Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
A

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
3
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

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

5.2 Bubble Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42


5.3 Selection Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
ED

5.4 Insertion Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45


5.5 Time Complexity of Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Summary Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
M

CHAPTER 6: SEARCHING 48
M

CHAPTER NOTES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
A

6.2 Linear Search (Sequential Search) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48


H

Algorithm 6.1: Linear Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48


Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
O

6.3 Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49


M

Algorithm 6.2: Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49


Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Program 6-2: Binary Search in Python . . . . . . . . . . . . . . . . . . . . . . . . . . 50
6.3.1 Applications of Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
6.4 Search by Hashing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Program 6-3: Hashing in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
4
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

6.4.1 Collision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

CHAPTER 7: UNDERSTANDING DATA 54


CHAPTER NOTES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
7.1 Introduction to Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
7.1.1 Importance of Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
7.1.2 Types of Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

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 8 DATABASE CONCEPTS 62


CHAPTER NOTES . . . . . . . . . . . . . . . .H . . . . . . . . . . . . . . . . . . . . . . . 62
AT
8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
8.2 File System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
M

8.3 Database Management System (DBMS) . . . . . . . . . . . . . . . . . . . . . . . . 64


8.4 Relational Data Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
ED

8.5 Keys in a Relational Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69


Summary of Chapter 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Summary of Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
M

CHAPTER 9 STRUCTURED QUERY LANGUAGE (SQL) 73


M

CHAPTER NOTES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
A

9.2 Structured Query Language (SQL) . . . . . . . . . . . . . . . . . . . . . . . . . 73


H

9.2.1 Installing MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74


9.3 Data Types and Constraints in MySQL . . . . . . . . . . . . . . . . . . . . . . . 75
O

9.4 SQL for Data Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77


M

9.4.4 — ALTER TABLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79


9.4.5 — DROP Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
9.5 — SQL for Data Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
9.6 — SQL for Data Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
9.6.2 — Querying Using Database OFFICE . . . . . . . . . . . . . . . . . . . . . . . . 88
9.7 — Data Updation and Deletion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
9.8: Functions in SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
5
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

9.9 — GROUP BY Clause in SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107


9.10 – Operations on Relations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

CHAPTER 10 COMPUTER NETWORKS 114


CHAPTER NOTES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
10.1: Introduction to Computer Networks . . . . . . . . . . . . . . . . . . . . . . . . . 114
10.2: Evolution of Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
10.3: Types of Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116

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

CHAPTER 11 DATA COMMUNICATION H 124


AT
CHAPTER NOTES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
11.1 Concept of Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
M

11.2: Components of Data Communication . . . . . . . . . . . . . . . . . . . . . . . 125


11.3: Measuring Capacity of Communication Media . . . . . . . . . . . . . . . . . . 126
ED

11.4: Types of Data Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . 127


11.5: Switching Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
11.6: Transmission Media . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
M

11.6.1 Wired (Guided) Transmission Media . . . . . . . . . . . . . . . . . . . . . . . 130


11.6.2 Wireless (Unguided) Transmission Media . . . . . . . . . . . . . . . . . . . . 131
M

11.6.3: Wireless Technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133


A

11.7: Mobile Telecommunication Technologies . . . . . . . . . . . . . . . . . . . . . 134


11.8: Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
H

CHAPTER 12 SECURITY ASPECTS 139


O

CHAPTER NOTES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139


M

12.1 - Threats and Prevention . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139


12.2 - Malware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
12.3 - Antivirus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
12.4 - Spam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
12.5 - HTTP vs HTTPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
12.6 - Firewall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
12.7 - Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
6
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

12.8 - Hackers and Crackers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147


12.9 - Network Security Threats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

R
L
N
EE
H
AT
M
ED
M
M
A
H
O
M

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
7
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

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.

This book is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 4.0 Interna-


M

tional License.
ED
M
M
A
H
O
M

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
8
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

CHAPTER 1: EXCEPTION HANDLING IN PYTHON

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

print "GOOD SCORE!"

This code will produce a SyntaxError because of the missing closing quote.
M

Syntax error in interactive/shell mode:


M
A
H
O
M

Figure 2: Syntax error in Shell mode

Syntax error detected in script mode:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
9
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

R
L
N
EE
H
AT
M
ED

Figure 3: Syntax Error in Script mode


M
M

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

to open a file that does not exist or dividing a number by zero.


O

Example:
M

result = 10 / 0

Built-in Exceptions

Commonly occurring exceptions are usually defined in the compiler/interpreter. These are called built-in
exceptions.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
10
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Common Built-in Exceptions Some common built-in exceptions in Python include:

Exception Description

SyntaxError Raised when there is an error in the syntax of the code.


ValueError Raised when a built-in method or operation receives an argument with the right data
type but an inappropriate value.

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

TypeError Raised when an operation is applied to an object of inappropriate type.


OverflowError Raised when a calculation exceeds the maximum limit for a numeric data type.
ED

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:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
11
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

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

The raise Statement


ED

The syntax of raise statement is:


raise exception-name[(optional argument)]
M

raise ValueError("This is a forced exception")


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

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
12
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

valid input. It is commonly used for debugging purposes. The syntax for assert statement is: assert
Expression[,arguments]

Example:

print("use of assert statement")


def negativecheck(number):
assert(number>=0), "OOPS... Negative Number"
print(number*number)

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

- Applicable to both user-defined and built-in exceptions.

Process of Handling Exception


M

• 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

program where the error has occurred.


H

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
13
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

• 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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
14
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

R
L
N
EE
H
AT
M
ED
M
M
A
H
O

The try…except Block


M

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
15
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

except ExceptionType:
# Code to handle the exception

Example:

print("Practicing for try block")


try:
numerator = 50

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")

Multiple except Blocks Handling different exceptions separately.

try: H
AT
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError as e:
M

print("Error: Division by zero -",e)


except ValueError as e:
ED

print("Error: Invalid input - ",e)

Catching All Exceptions Using a generic except clause.


M

try:
num = int(input("Enter a number: "))
M

result = 10 / num
except Exception as e:
A

print(f"An error occurred: {e}")


H
O

The try..except..else Clause


M

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.

print("Handling exception using try...except...else...finally")


try:
numerator = 50
denom = int(input("Enter the denominator: "))
quotient = (numerator / denom)

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
16
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

print("Division performed successfully")


except ZeroDivisionError:
print("Denominator as ZERO is not allowed")
except ValueError:
print("Only INTEGERS should be entered")
else:
print("The result of the division operation is", quotient)

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:

print("Handling exception using try...except...else...finally")


try:
H
AT
numerator = 50
denom = int(input("Enter the denominator: "))
quotient = (numerator / denom)
M

print("Division performed successfully")


except ZeroDivisionError:
ED

print("Denominator as ZERO is not allowed")


except ValueError:
print("Only INTEGERS should be entered")
M

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

Recovering and continuing with finally clause

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:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
17
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

print("Handling exception using try...except...else...finally")


try:
numerator = 50
denom = int(input("Enter the denominator: "))
quotient = (numerator / denom)
print("Division performed successfully")
except ZeroDivisionError:
print("Denominator as ZERO is not allowed")
else:

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
18
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

CHAPTER 2: FILE HANDLING IN PYTHON

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

• Each character is represented by its byte equivalent.


• End of Line (EOL) character (\n) is used to separate lines.
ED

Example:

The ASCII value of 'A' is 65 → Binary: 1000001


M

Binary Files
M
A

• Not human-readable (appear as symbols or garbage in text editors).


• Store data such as images, audio, video, compressed or executable files.
H

• Readable only with appropriate programs.


O
M

Opening and Closing a File

Opening a File

• Files are opened using the open() function which returns a file object.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
19
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Syntax:

file_object = open("filename", "mode")

File Access Modes with Examples

Read Mode - r

• Opens file for reading only.

R
• File must exist.

L
• File pointer at the beginning.

f = open("myfile.txt", "r")

N
EE
Binary Read Mode - rb

• Opens file in binary mode for reading.

f = open("myfile.txt", "rb") H
AT
Read and Write Mode - r+
M

• Opens file for reading and writing.


• File must exist.
ED

f = open("myfile.txt", "r+")
M

Write Mode - w
M

• Opens file for writing only.


A

• Overwrites file if it exists or creates a new one.


H

f = open("myfile.txt", "w")
O

Write Binary and Read Mode - wb+


M

• Opens file in binary mode for writing and reading.


• Overwrites or creates a new file.

f = open("myfile.txt", "wb+")

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
20
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Append Mode - a

• Opens file for appending data.


• Creates file if it doesn’t exist.
• File pointer at the end.

f = open("myfile.txt", "a")

Append and Read Mode - 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

file.name # Name of the file


ED

Closing a File
M

• Always close files after use to free system resources. Syntax:

file_object.close()
M
A

Opening a File Using with Clause


H

• Preferred method for file operations as it auto-closes the file. Syntax:


O

with open("myfile.txt", "r+") as myObject:


M

content = myObject.read()

Opening a File Syntax:

file_object = open("filename", "mode")

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
21
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

File Access Modes

Mode Description File Pointer Position

r Read only Beginning


rb Read binary Beginning
r+ Read and write Beginning

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

file.closed # True if file is closed


ED

file.mode # Access mode of file


file.name # Name of the file
M

Closing a File
M

Syntax:
A

file_object.close()
H
O

Opening a File Using with Clause


M

Syntax:

with open("myfile.txt", "r+") as myObject:


content = myObject.read()

• Automatically closes the file when the block is exited.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
22
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Writing to a Text File

Syntax: write()

file_object.write(string)

• Writes a single string to the file.


• Returns the number of characters written.

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

• Writes multiple strings to the file.


• Takes an iterable like a list or tuple.
M

Example: writelines()
A
H

• Writes a sequence (like a list or tuple) of strings.


O

lines = ["Hello everyone\n", "Writing multiline strings\n", "This is the third line"]
myobject.writelines(lines)
M

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
23
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Reading from a Text File

Syntax: read(n)

file_object.read(n)

• Reads n bytes from the file.

R
Example: read(n)

L
• Reads n bytes from the file.

myobject = open("myfile.txt", 'r')

N
print(myobject.read(10))

EE
myobject.close()

Syntax: read()
H
AT
file_object.read()

• Reads the entire content of the file.


M

Example: read()
ED

• Reads the entire file content.

myobject = open("myfile.txt", 'r')


M

print(myobject.read())
M

myobject.close()
A

Syntax: readline(n)
H

file_object.readline(n)
O

• Reads one line or up to n bytes until newline character.


M

Example: readline(n)

• Reads one line or n bytes until newline.

myobject = open("myfile.txt", 'r')


print(myobject.readline(10))
myobject.close()

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
24
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Syntax: readlines()

file_object.readlines()

• Reads all lines and returns them as a list.

Example: readlines()

R
• Reads all lines and returns a list.

myobject = open("myfile.txt", 'r')

L
print(myobject.readlines())

N
myobject.close()

EE
Splitting into words:

for line in lines:


words = line.split()
print(words) H
AT
Using splitlines():
M

for line in lines:


print(line.splitlines())
ED

Complete Example from Text


M

fobject = open("testfile.txt", "w")


sentence = input("Enter the contents to be written in the file: ")
M

fobject.write(sentence)
fobject.close()
A

print("Now reading the contents of the file: ")


H

fobject = open("testfile.txt", "r")


O

for str in fobject:


print(str)
M

fobject.close()

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
25
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

File Offset Methods

Syntax: tell()

file_object.tell()

• Returns current position of file pointer.

• Returns current file pointer position.

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

• Moves pointer to specified position.


H
AT
file_object.seek(5, 0) # Move to 5th byte from start

Program Example:
M

fileobject = open("testfile.txt", "r+")


str = fileobject.read()
ED

print(str)
print("Initially, position:", fileobject.tell())
fileobject.seek(0)
M

print("Now at beginning:", fileobject.tell())


fileobject.seek(10)
M

print("Pointer at:", fileobject.tell())


print(fileobject.read())
A

fileobject.close()
H
O
M

Creating and Traversing a Text File

Creating File and Writing Data

fileobject = open("practice.txt", "w+")


while True:
data = input("Enter data to save in the text file: ")

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
26
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

fileobject.write(data)
ans = input("Do you wish to enter more data?(y/n): ")
if ans == 'n': break
fileobject.close()

Displaying File Contents

fileobject = open("practice.txt", "r")

R
str = fileobject.readline()
while str:

L
print(str)
str = fileobject.readline()

N
fileobject.close()

EE
Combined Read/Write Program

fileobject = open("report.txt", "w+")


H
AT
while True:
line = input("Enter a sentence ")
fileobject.write(line + "\n")
M

choice = input("Do you wish to enter more data? (y/n): ")


if choice.lower() == 'n': break
ED

print("File position:", fileobject.tell())


fileobject.seek(0)
print("Reading contents:")
M

print(fileobject.read())
fileobject.close()
M
A
H

Pickle Module
O

Pickling
M

• Process of converting Python objects to a byte stream (serialization).


• Can store complex objects like lists, dictionaries.

Unpickling

• Restores the byte stream back into original object (deserialization).

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
27
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Import Statement

import pickle

Syntax for dump()

pickle.dump(object, file_object)

R
Syntax for load()

L
variable = pickle.load(file_object)

N
EE
Example for dump()

listvalues = [1, "Geetika", 'F', 26]


fileobject = open("mybinary.dat", "wb")
pickle.dump(listvalues, fileobject) H
AT
fileobject.close()
M

Example for load()


ED

fileobject = open("mybinary.dat", "rb")


objectvar = pickle.load(fileobject)
fileobject.close()
M

print(objectvar)
M

Complete Program Example


A

import pickle
H

bfile = open("empfile.dat", "ab")


recno = 1
O

while True:
M

eno = int(input("Employee number: "))


ename = input("Name: ")
ebasic = int(input("Basic Salary: "))
allow = int(input("Allowances: "))
totsal = ebasic + allow
edata = [eno, ename, ebasic, allow, totsal]
pickle.dump(edata, bfile)
if input("More records? (y/n): ").lower() == 'n': break

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
28
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

print("File size:", bfile.tell())


bfile.close()

print("Reading employee records")


try:
with open("empfile.dat", "rb") as bfile:
while True:
edata = pickle.load(bfile)
print(edata)

R
except EOFError:
pass

L
N
EE
H
AT
M
ED
M
M
A
H
O
M

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
29
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

CHAPTER 3: STACKS

CHAPTER NOTES

3.1 Introduction

• Data Structures: Ways to store, organize, and access data efficiently.


• Examples: String, List, Set, Tuple, Array, Linked List, Stack, Queue, Trees, Graphs, etc.

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

3.2.1 Applications of Stack


ED

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.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
30
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

3. Back Function in Web Browsers

• Navigated pages are pushed onto a stack. Pressing ‘Back’ pops the last visited page and
returns to the previous one.

4. Parentheses Matching in Expressions

• 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

3.4 Implementation of Stack in Python


ED

Functions:
M

# Create an empty stack


glassStack = list()
M

# Check if stack is empty


A

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:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
31
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

return glassStack.pop()

# Return stack size


def size(glassStack):
return len(glassStack)

# Return top element


def top(glassStack):
if isEmpty(glassStack):

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

print("Current number of elements in stack is", size(glassStack))


O

element = opPop(glassStack)
M

print("Popped element is", element)

element = 'glass3'
print("Pushing element", element)
opPush(glassStack, element)

print("Top element is", top(glassStack))


display(glassStack)

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
32
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

# delete all elements


while True:
item = opPop(glassStack)
if item is None:
break
print("Popped element is", item)

print("Stack is empty now")

R
L
N
3.5 Notations for Arithmetic Expressions

EE
Notation Description Example

Infix Operator between operands H (x + y) / (z * 5)


AT
Prefix Operator before operands /+xy*z5
M

Postfix Operator after operands xy+z5*/


ED

• Prefix (Polish) and Postfix (Reverse Polish) do not require parentheses.


• Infix needs BODMAS and parentheses for clarity.
M
M

3.6 Conversion from Infix to Postfix


A
H

Why? Computers struggle with operator precedence in infix; postfix avoids this.
O

Algorithm 3.1: Infix to Postfix


M

1. Create empty string postExp and stack stack.


2. For each character in infix expression:

• 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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
33
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

– PUSH current operator


• If operand → Append to postExp

3. POP remaining operators to postExp.

Example: (x + y)/(z * 8) → xy+z8/

R
L
3.7 Evaluation of Postfix Expression

N
Algorithm 3.2:

EE
1. For each character in postfix expression:

• If operand → PUSH to stack

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

• Stack = Linear structure, LIFO principle.


A

• Core ops: PUSH, POP; special cases: Overflow, Underflow.


Python list + append() and pop() can simulate stack.
H


• Notations: Infix, Prefix, Postfix
O

• Stacks are essential in converting and evaluating arithmetic expressions.


M

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
34
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

CHAPTER 4: QUEUE

CHAPTER NOTES

4.1 Introduction to Queue

• 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:

– REAR (TAIL) → for insertion


– FRONT (HEAD) → for deletion H
AT
Applications of Queue
M

Real-Life Applications
ED

1. Train Ticket Waiting List

• 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

• This strictly follows the First-In-First-Out (FIFO) principle.


A

2. Customer Care Calls (IVRS Systems)


H

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

3. Traffic Management (One-Way Road or Toll Booth)

• Vehicles on a one-way street or at a fuel pump/toll plaza form a queue.


• The vehicle that arrived first gets to move first.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
35
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Applications in Computer Science

1. Web Server Request Handling

• 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() Insert an element at rear. Exception: Overflow if full (static case).


dequeue() Remove from front. Exception: Underflow if empty.
M

isEmpty() Check if queue is empty.


M

peek() View the front item without removing.


A

isFull() Check if queue is full (not required in Python list-based queue).


H
O

Visual Example (Queue of alphabets):


M

enqueue('Z') → Z
enqueue('X') → Z X
enqueue('C') → Z X C
dequeue() → X C
enqueue('V') → X C V

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
36
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

4.3 Implementation of Queue using Python

myQueue = list()

def enqueue(myQueue, element):


myQueue.append(element)

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

Program 4-1: Simulation of a Queue in a Bank


M

myQueue = list()
A

element = input("Enter person’s code to enter in queue: ")


enqueue(myQueue, element)
H

element = input("Enter person’s code for insertion in queue: ")


enqueue(myQueue, element)
O
M

print("Person removed from queue is:", dequeue(myQueue))


print("Number of people in the queue is:", size(myQueue))

for _ in range(3):
element = input("Enter person’s code to enter in queue: ")
enqueue(myQueue, element)

print("Now removing remaining people from queue:")

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
37
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

while not isEmpty(myQueue):


print("Person removed from queue is", dequeue(myQueue))

4.4 Introduction to Deque (Double-Ended Queue)

• 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

1. Re-entry at Ticket Counter

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.

2. Toll Booth Queue Redirection


ED

• Suppose multiple toll booths exist.


• If one booth clears early, vehicles from the rear of other queues might shift to the front of
M

the vacant booth’s queue.


• This needs both front and rear insertions/deletions, which is deque-like behavior.
M
A

Applications in Computer Science


H

1. Browser History Navigation


O

• URLs are added to a stack-like structure, but if the memory is limited, older entries (from
M

the rear) must be removed.


• Deque can store history and remove least-recently-used entries when full.

2. Undo/Redo in Text Editors

• 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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
38
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

• A string is inserted character by character into a deque.


• Then characters are compared from front and rear simultaneously.
• If they match all the way, the string is a palindrome.
• Deque allows accessing both ends easily.

4.4.2 Operations on Deque

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

1. Traverse string left to right.


ED

2. Insert each character at rear.


3. Repeat: delete character from both front and rear, compare.
4. If all pairs match → it’s a palindrome.
M

4.5 Implementation of Deque using Python


M
A

def insertFront(myDeque, element):


myDeque.insert(0, element)
H

def insertRear(myDeque, element):


O

myDeque.append(element)
M

def isEmpty(myDeque):
return len(myDeque) == 0

def deletionRear(myDeque):
if not isEmpty(myDeque):
return myDeque.pop()
else:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
39
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

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

Program 4-2: Menu-driven Deque Program


def main():
ED

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

element = input("Data for insertion at rear: ")


insertRear(dQu, element)
H

print("Removed:", deletionFront(dQu))
O

print("Removed:", deletionFront(dQu))
else:
M

element = input("Data for insertion at front: ")


insertFront(dQu, element)
print("Data at rear:", getRear(dQu))
element = input("Data for insertion at front: ")
insertFront(dQu, element)
print("Removed:", deletionRear(dQu))
print("Removed:", deletionRear(dQu))

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
40
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Summary Points

• Queue: FIFO, insertion at rear, deletion from front.

• Deque: Insertion & deletion possible from both ends.

• Python lists can implement both structures easily.

• Additional operations: isEmpty, peek, size, getFront, getRear.

R
L
N
EE
H
AT
M
ED
M
M
A
H
O
M

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
41
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

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.

5.2 Bubble Sort


H
AT
Concept
• Compares adjacent elements and swaps them if they are in the wrong order.
M

• 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

Diagram: Bubble Sort Passes We will sort:


[8, 7, 13, 1, -9, 4]
A

Each pass compares adjacent elements and swaps if needed.


H

Pass 1
O

[8, 7, 13, 1, -9, 4]


M

→ Swap 8 and 7 → [7, 8, 13, 1, -9, 4]


→ No Swap (8,13)
→ Swap 13 and 1 → [7, 8, 1, 13, -9, 4]
→ Swap 13 and -9 → [7, 8, 1, -9, 13, 4]
→ Swap 13 and 4 → [7, 8, 1, -9, 4, 13]

Pass 2

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
42
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

[7, 8, 1, -9, 4, 13]


→ No Swap (7,8)
→ Swap 8 and 1 → [7, 1, 8, -9, 4, 13]
→ Swap 8 and -9 → [7, 1, -9, 8, 4, 13]
→ Swap 8 and 4 → [7, 1, -9, 4, 8, 13]

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

[1, -9, 4, 7, 8, 13]


H
AT
→ Swap 1 and -9 → [-9, 1, 4, 7, 8, 13]
M

Pass 5

No swaps → Sorting complete.


ED

Final list: [-9, 1, 4, 7, 8, 13]


M

Algorithm 5.1: Bubble Sort


M

BUBBLESORT(numList, n)
1. Set i = 0
A

2. While i < n repeat:


3. Set j = 0
H

4. While j < n - i - 1 repeat:


O

5. If numList[j] > numList[j+1], then


6. Swap numList[j] and numList[j+1]
M

7. j = j + 1
8. i = i + 1

Python Program
def bubble_Sort(list1):
n = len(list1)
for i in range(n):

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
43
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

for j in range(0, n-i-1):


if list1[j] > list1[j+1]:
list1[j], list1[j+1] = list1[j+1], list1[j]

numList = [8, 7, 13, 1, -9, 4]


bubble_Sort(numList)
print("The sorted list is:")
for i in range(len(numList)):
print(numList[i], end=" ")

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

Pass 1 - Smallest is -9 → Swap with 8


[-9, 7, 13, 1, 8, 4]
ED

Pass 2 - Smallest in [7,13,1,8,4] is 1 → Swap with 7


[-9, 1, 13, 7, 8, 4]
M

Pass 3 - Smallest in [13,7,8,4] is 4 → Swap with 13


[-9, 1, 4, 7, 8, 13]
M

Pass 4 - Smallest in [7,8,13] is 7 (already in place)


A

[-9, 1, 4, 7, 8, 13]
H

Pass 5 - Already sorted


[-9, 1, 4, 7, 8, 13]
O
M

Algorithm 5.2: Selection Sort


SELECTIONSORT(numList, n)
1. Set i = 0
2. While i < n repeat:
3. Set min = i, flag = 0
4. Set j = i + 1
5. While j < n repeat:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
44
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

6. If numList[j] < numList[min]:


7. min = j
8. flag = 1
9. If flag == 1:
10. Swap numList[i], numList[min]
11. i = i + 1

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

5.4 Insertion Sort


M

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

Diagram: Insertion Sort Passes Initial List: [8, 7, 13, 1, -9, 4]


O

Pass 1 Insert 7 into sorted [8]


[7, 8, 13, 1, -9, 4]
M

Pass 2 Insert 13 into sorted [7,8]


[7, 8, 13, 1, -9, 4]
Pass 3 Insert 1 into sorted [7,8,13]
[1, 7, 8, 13, -9, 4]
Pass 4 Insert -9 into sorted [1,7,8,13]
[-9, 1, 7, 8, 13, 4]

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
45
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Pass 5 Insert 4 into sorted [-9,1,7,8,13]


[-9, 1, 4, 7, 8, 13]

Algorithm 5.3: Insertion Sort


INSERTIONSORT(numList, n)
1. Set i = 1
2. While i < n repeat:

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

while j >= 0 and temp < list3[j]:


list3[j+1] = list3[j]
j -= 1
M

list3[j+1] = temp
M

numList = [8, 7, 13, 1, -9, 4]


insertion_Sort(numList)
A

print("The sorted list is:")


for i in range(len(numList)):
H

print(numList[i], end=" ")


O
M

5.5 Time Complexity of Algorithms

Basic Complexity Concepts

• Constant Time (O(1)): No loops.


• Linear Time (O(n)): Single loop.
• Quadratic Time (O(n²)): Nested loops.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
46
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

All three sorting algorithms in this chapter (bubble, selection, insertion) have O(n²) complexity due to
nested loops.

Summary Points

• Sorting: Rearranging elements for efficient access.


• Bubble Sort: Repeated adjacent swaps, n-1 passes.

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
47
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

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

Algorithm 6.1: Linear Search


ED

LinearSearch(numList, key, n)
Step 1: SET index = 0
Step 2: WHILE index < n, REPEAT Step 3
M

Step 3: IF numList[index] = key THEN


PRINT “Element found at position”, index+1
M

STOP
A

ELSE
index = index + 1
H

Step 4: PRINT “Search unsuccessful”


O
M

Example

List: numList = [8, -4, 7, 17, 0, 2, 19], Key: 17

Index Comparison Result

0 8 == 17 not found

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
48
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Index Comparison Result

1 -4 == 17 not found
2 7 == 17 not found
3 17 == 17 Found at index 3

def linearSearch(list, key):

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)

key = int(input("Enter the number to be searched:"))


M

position = linearSearch(list1, key)

if position is None:
ED

print("Number", key, "is not present in the list")


else:
print("Number", key, "is present at position", position)
M
M

6.3 Binary Search


A

• Requires a sorted list.


H

• More efficient than linear search.


• Repeatedly divides list into halves and compares key with the middle element.
O
M

Algorithm 6.2: Binary Search

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
49
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

PRINT "Element found at position", mid + 1


STOP
ELSE IF numList[mid] > key THEN
last = mid - 1
ELSE
first = mid + 1
Step 4: PRINT "Search unsuccessful"

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

Minimum iterations: 1 (if key is in middle)


Maximum iterations: ⌊𝑙𝑜𝑔2 (𝑛)⌋
M
M

Program 6-2: Binary Search in Python


A

def binarySearch(list, key):


first = 0
H

last = len(list) - 1
O

while first <= last:


mid = (first + last)//2
M

if list[mid] == key:
return mid
elif key > list[mid]:
first = mid + 1
else:
last = mid - 1
return -1

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
50
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

numList = []
print("Enter elements in ascending order (-999 to stop):")
num = int(input())
while num != -999:
numList.append(num)
num = int(input())

key = int(input("Enter the number to be searched: "))


pos = binarySearch(numList, key)

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

• Dictionary/telephone directory search.


H
AT
• Database indexing.
• Data compression, routing tables, etc.
M

6.4 Search by Hashing


ED

• Direct access method using a hash function.


• Searches key in constant time O(1).
M

• Hash function computes index:


h(element) = element % size_of_table
M

Example
A
H

List: [34, 16, 2, 93, 80, 77, 51], Hash Table size = 10
O

Element Hash Value Index in Table


M

34 4 4
16 6 6
2 2 2
93 3 3
80 0 0

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
51
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Element Hash Value Index in Table

77 7 7
51 1 1

Final Hash Table:

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

Program 6-3: Hashing in Python


M

def hashFind(key, hashTable):


A

if hashTable[key % 10] == key:


H

return (key % 10) + 1


else:
O

return None
M

hashTable = [None]*10
L = [34, 16, 2, 93, 80, 77, 51]

for i in L:
hashTable[i % 10] = i

key = int(input("Enter the number to be searched: "))

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
52
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

position = hashFind(key, hashTable)


if position:
print("Number", key, "present at", position, "position")
else:
print("Number", key, "is not present in the hash table")

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

Hashing Fastest lookups Hash Function O(1) Needs collision handling


M
M
A
H
O
M

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
53
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

CHAPTER 7: UNDERSTANDING DATA

CHAPTER NOTES

7.1 Introduction to Data

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:

• Personal information: Name, Age, Gender, Contact


M

• Transactional data: Online or offline purchases


• Multimedia: Images, videos, graphics, audio
• Documents and web content
ED

• Social media posts


• Sensor signals (like IoT data)
M

• Satellite data (weather, earth observation, etc.)


M

7.1.1 Importance of Data


A

Humans and computers both rely heavily on data. Computers can process large volumes of data quickly
H

and reveal patterns or traits not easily visible.


O
M

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.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
54
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Other Scenarios:

• EVMs: Record and count votes digitally.


• Scientific research: Involves collecting experimental data.
• Pharmaceuticals: Analyze medicine effectiveness through trials.
• Libraries: Store book and membership data.
• Search Engines: Analyze web content to show relevant results.
• Weather Systems: Use satellite data to generate alerts.

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

ModelNo ProductName Unit Price


H Discount(%) Items_in_Inventory
AT
ABC1 Water Bottle 126 8 13
ABC2 Melamine Plates 320 5 45
M

ABC3 Dinner Set 4200 10 8


ED

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

Metadata: Data about data


E.g., For a photo → size, type (JPEG/PNG), resolution. For an email → subject, sender, attachments.

7.2 Data Collection

Before data processing, you must collect or identify relevant data.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
55
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

3 Scenarios:

1. Manual Records (e.g., diaries): Must be converted to digital format.


2. Digital Files: Like CSV files, can be directly processed.
3. No existing data: Need to create software (e.g., using Python) to store and retrieve new data.

Our daily digital activities constantly generate data (e.g., browsing, transactions, healthcare records).

R
Example Applications:

• Hospitals: Use patient data for service improvements.

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

Common Storage Devices:


ED

• Hard Disk Drive (HDD)


• Solid State Drive (SSD)
• CD/DVD
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

use a Database Management System (DBMS) instead of simple file storage.


O

7.4 Data Processing


M

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:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
56
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Figure 7.1: Data Processing Cycle

+------------------------+
| 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

| (fetching for use) |


H

+-----------+------------+
|
O

v
M

+------------------------+
| Data Processing |
| (classify, update, |
| analyze, compute) |
+-----------+------------+
|
v

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
57
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

+------------------------+
| Data Output |
| (Reports, results, |
| visualizations) |
+------------------------+

Explanation of Each Step:

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

Figure 7.2: Real-Life Data Processing Examples


M
A

Problem Statement Inputs Processing Output


H

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

7.5 Statistical Techniques for Data Processing

7.5.1 Measures of Central Tendency

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
58
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

(A) Mean (Average)


𝑥1 + 𝑥2 + ... + 𝑥𝑛
[Mean = ]
𝑛
- Gives the average value. - Not reliable if data has outliers (extreme values).

Example: [90, 102, 110, 115, 85, 90, 100, 110, 110]
→ Mean = 101.33

R
(B) Median

• Middle value in sorted data.

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

• Most frequent value.


M

• Can be used for both numeric and non-numeric data.


• May have one, multiple, or no mode.
ED

Example: Mode = 110 (occurs 3 times)


M

7.5.2 Measures of Variability


M

(A) Range
A

[Range = Max − Min]


H

- Shows spread of data. - Sensitive to outliers.


O

Example: Heights → Max = 115, Min = 85 → Range = 30 cm


M

(B) Standard Deviation (𝜎) Measures how values differ from the mean.

∑(𝑥𝑖 − 𝑥)̄ 2
[𝜎 = √ ]
𝑛
Table 7.3: SD Calculation for Heights

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
59
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

• Mean = 101.33

• 𝑆𝐷 ≈ √(938/9) = 𝑎𝑝𝑝𝑟𝑜𝑥.10.21

Lower SD → tightly clustered data


Higher SD → widely spread data

Important Statistical Technique Selection

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

Glossary of Key Terms


ED

Term Explanation
M

Data Raw, unorganised facts and figures


M

Information Processed data that is meaningful


A

Structured Data Tabular data with rows and columns


H

Unstructured Data Data without a predefined format


O

Metadata Data about other data


M

Data Collection Gathering data from various sources


Data Storage Saving data on physical/digital devices
Data Processing Converting raw data into useful output
Mean Average of numerical data
Median Middle value in sorted data

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
60
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Term Explanation

Mode Most frequently occurring value


Range Difference between max and min values
Standard Deviation (σ) Measures the spread of values around the mean
Outlier Data point that is far from other values

R
DBMS Software to manage large datasets efficiently

L
N
EE
H
AT
M
ED
M
M
A
H
O
M

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
61
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

CHAPTER 8 DATABASE CONCEPTS

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

1. Rewriting student details across records introduces chances of error.

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

• Easy copying and promotion of records.


• Efficient search, update, and deletion.
• Better management via computerised data files.
ED
M

8.2 File System


M
A

A file is a container on a computer to store data like text, code, images, videos, CSVs, etc.
H

Example: Two Data Files


O

• STUDENT
M

• ATTENDANCE

Table 8.1 — STUDENT File Maintained by Office Staff

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
62
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Roll
Number SName SDateofBirth GName GPhone GAddress

1 Atharv 2003-05- Amit Ahuja 5711492685 G-35, Ashok Vihar, Delhi


Ahuja 15
2 Daizy 2002-02- Baichung 7110047139 Flat no. 5, Darjeeling Appt.,
Bhutia 28 Bhutia Shimla

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

Table 8.2 — ATTENDANCE File Maintained by Class Teacher

AttendanceDate RollNumber SName AttendanceStatus


ED

2018-09-01 1 Atharv Ahuja P


M

2018-09-01 2 Daizy Bhutia P


2018-09-01 3 Taleem Shah A
M

2018-09-01 4 John Dsouza P


A

2018-09-01 5 Ali Shah A


H

2018-09-01 6 Manika P. P
O

2018-09-02 1 Atharv Ahuja P


M

2018-09-02 2 Daizy Bhutia P


2018-09-02 3 Taleem Shah A
2018-09-02 4 John Dsouza A
2018-09-02 5 Ali Shah P
2018-09-02 6 Manika P. P

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
63
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

8.2.1 Limitations of File System

Problem Description

Difficulty in Access Application programs required for


data retrieval.

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

8.3 Database Management System (DBMS)

A DBMS is software to store, manage, and retrieve logically related data efficiently.
M
M

Common DBMS Software:

• MySQL
A

• Oracle
H

• PostgreSQL
• SQL Server
O

• MS Access
M

• MongoDB

Table 8.3 — Use of Database in Real-Life Applications

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
64
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Application Database Maintains Information About

Banking Customer, Account, Loans, Transactions


Crop Loan Farmer info, land, credit card, repayment
Inventory Management Products, orders, customers
Organisation Resources Employee, salary, department, branches

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.

• Introduce GUID (Guardian ID).


H
AT
• Originally, the STUDENT file contained guardian information, which was repeated for students
having the same guardian (e.g., siblings).
M

• 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

Figure 8.1 — Record Structure in DBMS


M

STUDENT GUARDIAN ATTENDANCE


A

-------- -------- -----------


RollNumber GUID AttendanceDate
H

SName GName RollNumber


O

SDateofBirth GPhone AttendanceStatus


M

GUID GAddress

Table 8.4 — Snapshot of STUDENT Table

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
65
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

RollNumber SName SDateofBirth GUID

1 Atharv Ahuja 2003-05-15 444444444444


2 Daizy Bhutia 2002-02-28 111111111111
3 Taleem Shah 2002-02-28
4 John Dsouza 2003-08-18 333333333333

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

444444444444 Amit Ahuja 5711492685 H G-35, Ashok Vihar, Delhi


AT
111111111111 Baichung Bhutia 7110047139 Flat no. 5, Darjeeling Appt., Shimla
101010101010 Himanshu Shah 9818184855 26/77, West Patel Nagar, Ahmedabad
M

333333333333 Danny Dsouza — S -13, Ashok Village, Daman


ED

466444444666 Sujata P. 7802983674 HNO-13, B- block, Preet Vihar, Madurai


M

Table 8.6 — Snapshot of ATTENDANCE Table


M

Date RollNumber Status


A

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
66
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Date RollNumber Status

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

Student Guardian Attendance


^ ^ ^
+-----------+-----------+
M

|
M

Database Catalog
A

Key Concepts in DBMS


H
O

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
67
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Concept Description

Data Manipulation Operations such as insert, update, delete


Database Engine Internal component that processes queries and manages storage

8.4 Relational Data Model

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

Attribute A column in a relation


M

Tuple A row in a relation


A

Domain Set of permissible values for an attribute


H

Degree Number of attributes (columns) in a relation


O

Cardinality Number of tuples (rows) in a relation


M

Three Important Properties of a Relation

1. Properties of Attributes:

• Attribute names must be distinct.


• The order of attributes in a relation does not matter.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
68
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

2. Properties of Tuples:

• All tuples (rows) in a relation must be unique.


• The order of tuples in a relation does not matter.

3. Properties of Values:

• Every value in a tuple must be atomic (indivisible).


• Values may be NULL to represent missing or unknown information.

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

466444444666 Sujata P. 7802983674 HNO-13, B- block, Preet Vihar, Madurai


ED

Degree = 4 (columns), Cardinality = 5 (rows)


M
M

8.5 Keys in a Relational Database


A

Keys help uniquely identify records and maintain relationships.


H
O

8.5.1 Candidate Key


M

• Any attribute (or combination) that can uniquely identify a tuple.


• Example: GUID, GPhone in GUARDIAN.

8.5.2 Primary Key

• Chosen candidate key to uniquely identify rows.


• Example: GUID in GUARDIAN table.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
69
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

8.5.3 Composite Primary Key

• A key formed by combining two or more attributes.


• Example: {RollNumber, AttendanceDate} in ATTENDANCE.

8.5.4 Foreign Key

• Attribute that refers to a primary key in another table.


• Used to link two tables.

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) |

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
70
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

+-------------------------------+

Summary of Chapter 8

• Manual file systems are inefficient and lead to redundancy.

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

File Container to store digital data like text,


audio, code, etc.
ED

DBMS Software that manages storage, access,


manipulation, and retrieval of data.
M

Database Organized collection of logically related


data.
M

Schema Structure of a database including tables,


A

attributes, and constraints.


H

Instance Current snapshot or state of data in a


database.
O

Attribute A column in a table representing a data


M

field.
Tuple A row in a table representing a single
record.
Domain Permissible set of values for an attribute.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
71
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Term Explanation

Degree Number of attributes (columns) in a


table.
Cardinality Number of records (rows) in a table.
Primary Key Attribute(s) that uniquely identify each
tuple in a relation.

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

Constraint Condition or rule enforced on data to


maintain integrity.
ED

Meta-data Data that describes other data (e.g.,


schema, constraints).
M

Atomic Value Single indivisible value in a data field.


NULL Special value indicating missing or
M

unknown data.
A

Database Engine Core service that processes database


H

queries and manages storage.


Data Manipulation Operations such as INSERT, UPDATE,
O

DELETE performed on data.


M

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
72
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

CHAPTER 9 STRUCTURED QUERY LANGUAGE (SQL)

CHAPTER NOTES

Introduction

Overview of RDBMS and SQL

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

– Create a database using relations (tables).


– Store, retrieve, and manipulate data using queries.
ED

• The tool used to perform all these actions is called SQL (Structured Query Language).
M

9.2 Structured Query Language (SQL)


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

agement Systems (DBMS).


M

• SQL works with popular RDBMS like:

– MySQL
– ORACLE
– SQL Server

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
73
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Key Features of SQL

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

SQL with MySQL Example

• 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

9.2.1 Installing MySQL


M

What is MySQL?
A

• MySQL is a popular, open-source Relational Database Management System (RDBMS).


H

• It supports SQL and is widely used to create and manage databases.


O

How to Install MySQL?


M

• Download from the official site:


https://dev.mysql.com/downloads

• Install the software on your computer.

• Start MySQL service.

– Once started, the terminal (or command-line interface) will show the prompt:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
74
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

mysql>

– This indicates that MySQL is ready to accept SQL commands.

Key Points to Remember While Using SQL in 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:

• NoSQL databases (e.g., MongoDB, CouchDB)


M

• Hierarchical databases
• Object-oriented databases
ED

• Network databases
M

9.3 Data Types and Constraints in MySQL


M

What are Data Types and Constraints?

• Every table (relation) is made up of attributes (columns).


A

• Each attribute:
H

– Has a data type — defines the kind of values it can store.


O

– May have constraints — rules that restrict the values entered into that column.
M

9.3.1 Data Type of Attribute

Definition: The data type of an attribute defines:

• What kind of values can be stored.


• What kind of operations can be performed on them.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
75
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Data Type Description

CHAR(n) Fixed-length character string. - Length n can be


from 0 to 255. - e.g., CHAR(10) stores exactly
10 characters; unused space is padded with
spaces.
VARCHAR(n) Variable-length character string. - Length n up

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:

• BIGINT, DECIMAL, DOUBLE


M

• TEXT, TINYTEXT, BLOB


• DATETIME, TIMESTAMP, TIME, YEAR
M
A

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

NOT NULL Value must be provided; cannot be left empty


(NULL).
UNIQUE All values in the column must be different.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
76
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Constraint Description

DEFAULT Assigns a default value if no value is


entered.
PRIMARY KEY Uniquely identifies each row in a table. Must
be unique and not null.
FOREIGN KEY Refers to a primary key in another table.

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

• Create tables inside a database


• Define attributes, data types, and constraints
ED

• View or modify table structure

1. STUDENT Table Attributes & Description


M
M

Attribute Data Type Constraint Description


A

RollNumber INT PRIMARY KEY Unique roll number of student (1–100)


SName VARCHAR(20) NOT NULL Student name
H

SDateofBirth DATE NOT NULL Date of birth


O

GUID CHAR(12) FOREIGN KEY Guardian’s Aadhaar (linked to


M

GUARDIAN)

SQL Command

CREATE TABLE STUDENT (


RollNumber INT,
SName VARCHAR(20),

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
77
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

SDateofBirth DATE,
GUID CHAR(12),
PRIMARY KEY (RollNumber)
);

DESCRIBE Output

mysql> DESCRIBE STUDENT;

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

Attribute Data Type Constraint Description


ED

GUID CHAR(12) PRIMARY KEY Unique Aadhaar number of guardian


GName VARCHAR(20) NOT NULL Guardian name
M

GPhone CHAR(10) NULL, UNIQUE Phone number (optional but unique)


GAddress VARCHAR(30) NOT NULL Address of guardian
M
A

3. ATTENDANCE Table Attributes & Description


H
O

Attribute Data Type Constraint Description


M

AttendanceDate DATE Composite Primary Key Date of attendance


RollNumber INT Composite PK, FOREIGN Student’s roll number
KEY
AttendanceStatus CHAR(1) NOT NULL ‘P’ for present, ‘A’ for absent

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
78
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

SHOW TABLES Command in SQL Purpose:

The SHOW TABLES; command is used to list all tables present in the currently selected database.

Syntax:

SHOW TABLES;

Example:

Assume you’ve created and selected the database named StudentAttendance.

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

9.4.4 — ALTER TABLE


M

Purpose of ALTER TABLE Once a table is created, you might need to:
A
H

• Add or remove attributes (columns)


• Modify data types or constraints
O

• Add primary/foreign/unique keys


M

All these structural changes are done using the ALTER TABLE command.

General Syntax:
ALTER TABLE table_name
<alteration_action>;

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
79
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

(A) Add Primary Key to a Table

Example:
ALTER TABLE GUARDIAN
ADD PRIMARY KEY (GUID);

ALTER TABLE ATTENDANCE


ADD PRIMARY KEY (AttendanceDate, RollNumber);

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

ALTER TABLE table_name


ADD FOREIGN KEY (column_name)
ED

REFERENCES referenced_table (referenced_column);

Example:
M

ALTER TABLE STUDENT


M

ADD FOREIGN KEY (GUID) REFERENCES GUARDIAN(GUID);


A

(C) Add UNIQUE Constraint Ensures all values in a column are distinct.
H
O

Example:
M

ALTER TABLE GUARDIAN


ADD UNIQUE (GPhone);

(D) Add New Attribute

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
80
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

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

(F) Modify Constraint (e.g., Add NOT NULL)


ED

Example:
M

ALTER TABLE STUDENT


MODIFY SName VARCHAR(20) NOT NULL;
M

You must re-specify the datatype when changing constraints.


A
H

(G) Add DEFAULT Value


O

Syntax:
M

ALTER TABLE table_name


MODIFY column_name datatype DEFAULT default_value;

Example:
ALTER TABLE STUDENT
MODIFY SDateofBirth DATE DEFAULT '2000-05-15';

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
81
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

(H) Remove an Attribute

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

ALTER TABLE GUARDIAN


DROP PRIMARY KEY;
ED

Note: Each table should have a primary key for data integrity. You can re-add it using ADD PRIMARY
KEY.
M
M

ALTER TABLE — Summary Table


A

Operation Purpose Syntax / Example


H

Add Primary To define a column(s) as a ALTER TABLE table_name ADD PRIMARY KEY
O

Key primary key (column); ALTER TABLE GUARDIAN ADD


M

PRIMARY KEY (GUID);


Add Use multiple columns as a ALTER TABLE ATTENDANCE ADD PRIMARY KEY
Composite single primary key (AttendanceDate, RollNumber);
Primary Key
Add Foreign To create a relationship to ALTER TABLE STUDENT ADD FOREIGN KEY
Key another table’s primary key (GUID) REFERENCES GUARDIAN(GUID);

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
82
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Operation Purpose Syntax / Example

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

9.4.5 — DROP Statement

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

• The data cannot be recovered (use with caution).


O

• All associated data, structure, and constraints are lost permanently.


M

A. DROP a Table

Syntax:
DROP TABLE table_name;

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
83
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

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.

9.5 — SQL for Data Manipulation


M
M

What is Data Manipulation?

• After defining tables (DDL), we use Data Manipulation Language (DML) commands to:
A

– Insert
H

– Update
O

– Delete
M

9.5.1 INSERTION of Records Syntax 1: Insert into all columns

INSERT INTO table_name


VALUES (value1, value2, ..., valueN);

Use this when inserting values for all attributes in the same order as the table.

Syntax 2: Insert into selected columns

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
84
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

INSERT INTO table_name (column1, column2, ...)


VALUES (value1, value2, ...);

Use when skipping some columns (e.g., default or NULL values).

Example 1: Insert a Guardian Record

INSERT INTO GUARDIAN


VALUES (444444444444, 'Amit Ahuja', 5711492685, 'G-35, Ashok Vihar, Delhi');

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

| 444444444444 | Amit Ahuja | 5711492685| G-35, Ashok Vihar, Delhi |


+--------------+--------------+-----------+----------------------------+
ED

Example 2: Insert Guardian with NULL Phone

INSERT INTO GUARDIAN (GUID, GName, GAddress)


M

VALUES (333333333333, 'Danny Dsouza', 'S -13, Ashok Village, Daman');


M

Explanation: Skips GPhone. It will be stored as NULL.


A

Query OK, 1 row affected (0.03 sec)


H
O

Example 3: Insert into STUDENT with All Fields


M

INSERT INTO STUDENT


VALUES (1, 'Atharv Ahuja', '2003-05-15', 444444444444);

Or

INSERT INTO STUDENT (RollNumber, SName, SDateofBirth, GUID)


VALUES (1, 'Atharv Ahuja', '2003-05-15', 444444444444);

View Student Record:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
85
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

SELECT * FROM STUDENT;

+------------+--------------+--------------+--------------+
| 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:

INSERT INTO STUDENT (RollNumber, SName, SDateofBirth)


VALUES (3, 'Taleem Shah', '2002-02-28');
H
AT
GUID is a foreign key, so it can be NULL, but must match if present.
M

View Student Table:

SELECT * FROM STUDENT;


ED

+------------+--------------+--------------+--------------+
| RollNumber | SName | SDateofBirth | GUID |
M

+------------+--------------+--------------+--------------+
M

| 1 | Atharv Ahuja | 2003-05-15 | 444444444444 |


| 3 | Taleem Shah | 2002-02-28 | NULL |
A

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

Great! Let’s now explore the next major section.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
86
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

9.6 — SQL for Data Query

What is Data Querying? Once data is inserted into tables, we use SQL to retrieve specific infor-
mation. This process is called querying.

SQL provides the SELECT command to:

• Display entire tables


• Fetch specific columns

R
• Apply conditions to filter rows

L
N
EE
9.6.1 SELECT Statement Syntax:

SELECT column1, column2, ...


FROM table_name
WHERE condition;
H
AT
Example 1: Select All Columns
M

SELECT * FROM STUDENT;

Explanation:
ED

* selects all attributes from the table.

Output:
M

+------------+--------------+--------------+--------------+
M

| RollNumber | SName | SDateofBirth | GUID |


+------------+--------------+--------------+--------------+
A

| 1 | Atharv Ahuja | 2003-05-15 | 444444444444 |


H

| 3 | Taleem Shah | 2002-02-28 | NULL |


+------------+--------------+--------------+--------------+
O
M

Example 2: Select Specific Columns

SELECT RollNumber, SName FROM STUDENT;

Output:

+------------+--------------+
| RollNumber | SName |

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
87
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

+------------+--------------+
| 1 | Atharv Ahuja |
| 3 | Taleem Shah |
+------------+--------------+

Example 3: Apply a WHERE Clause

SELECT * FROM STUDENT

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

EMPLOYEE is a foreign key referencing DEPARTMENT.


M

EMPLOYEE Table (Sample Data — Table 9.8)


M

EmpNo Ename Salary Bonus DeptId


A

101 Aaliya 10000 234 D02


H

102 Kritika 60000 123 D01


O

103 Shabbir 45000 566 D01


M

104 Gurpreet 19000 565 D04


105 Joseph 34000 875 D03
106 Sanya 48000 695 D02
107 Vergese 15000 NULL D01
108 Nachaobi 29000 NULL D05

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
88
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

EmpNo Ename Salary Bonus DeptId

109 Daribha 42000 NULL D04


110 Tanya 50000 467 D05

(A) Retrieve Selected Columns Query 1:

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

SELECT EmpNo, Ename FROM EMPLOYEE;


O

Output:
M

+-------+----------+
| EmpNo | Ename |
+-------+----------+
| 101 | Aaliya |
| 102 | Kritika |
| 103 | Shabbir |

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
89
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

| 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

(C) Calculated Columns (Annual Income) Query:


M

SELECT Ename AS Name, Salary*12 FROM EMPLOYEE;

Output:

+----------+-----------+
| Name | Salary*12 |
+----------+-----------+

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
90
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

| 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

| Name | Annual Income |


+----------+---------------+
ED

| 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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
91
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

SELECT DISTINCT DeptId FROM EMPLOYEE;

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

Query 1: Employees from Department D01

SELECT * FROM EMPLOYEE


ED

WHERE DeptId = 'D01';

Output:
M

+-------+----------+--------+-------+--------+
M

| EmpNo | Ename | Salary | Bonus | DeptId |


A

+-------+----------+--------+-------+--------+
| 102 | Kritika | 60000 | 123 | D01 |
H

| 103 | Shabbir | 45000 | 566 | D01 |


O

| 107 | Vergese | 15000 | NULL | D01 |


+-------+----------+--------+-------+--------+
M

Query 2: Employees from Department D02

SELECT * FROM EMPLOYEE


WHERE DeptId = 'D02';

Output:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
92
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

+-------+--------+--------+-------+--------+
| EmpNo | Ename | Salary | Bonus | DeptId |
+-------+--------+--------+-------+--------+
| 101 | Aaliya | 10000 | 234 | D02 |
| 106 | Sanya | 48000 | 695 | D02 |
+-------+--------+--------+-------+--------+

R
Query 3: Employees with Salary > 25000

SELECT EmpNo, Ename, Salary

L
FROM EMPLOYEE
WHERE Salary > 25000;

N
Output:

EE
+-------+----------+--------+
| EmpNo | Ename | Salary |
H
AT
+-------+----------+--------+
| 102 | Kritika | 60000 |
| 103 | Shabbir | 45000 |
M

| 105 | Joseph | 34000 |


| 106 | Sanya | 48000 |
ED

| 108 | Nachaobi | 29000 |


| 109 | Daribha | 42000 |
M

| 110 | Tanya | 50000 |


+-------+----------+--------+
M

Query 4 Query: Display all details of employees from department D04 who earn more than 5000.
A

SELECT * FROM EMPLOYEE


H

WHERE Salary > 5000 AND DeptId = 'D04';


O

Output:
M

+-------+----------+--------+-------+--------+
| EmpNo | Ename | Salary | Bonus | DeptId |
+-------+----------+--------+-------+--------+
| 104 | Gurpreet | 19000 | 565 | D04 |
| 109 | Daribha | 42000 | NULL | D04 |
+-------+----------+--------+-------+--------+

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
93
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Query 5
Query: Display all employee records except Aaliya.

SELECT * FROM EMPLOYEE


WHERE NOT Ename = '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

Query 6 Query: Employees earning salary between 20000 and 50000.

SELECT Ename, DeptId


M

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 |
+----------+--------+

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
94
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

You can also write:

WHERE Salary >= 20000 AND Salary <= 50000;

Query 7 Query: Employees from departments D01, D02, or D04 using OR:

SELECT * FROM EMPLOYEE


WHERE DeptId = 'D01' OR DeptId = 'D02' OR DeptId = 'D04';

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

Query: Employees from departments D01, D02, D04


M

SELECT * FROM EMPLOYEE


WHERE DeptId IN ('D01', 'D02', 'D04');
A

Output:
H
O

+-------+----------+--------+-------+--------+
M

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
95
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

| 107 | Vergese | 15000 | NULL | D01 |


| 109 | Daribha | 42000 | NULL | D04 |
+-------+----------+--------+-------+--------+

IN is more concise than using multiple OR conditions.

Query: Select all employees except those working in departments D01 or D02.

SELECT * FROM EMPLOYEE

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

| 110 | Tanya | 50000 | 467 | D05 |


+-------+----------+--------+-------+--------+
ED

(G) Using IS NULL — Check for Missing Data Purpose: To check whether a column contains a
NULL (empty) value.
M

Query: Employees with no bonus


M

SELECT EmpNo, Ename, Bonus


FROM EMPLOYEE
A

WHERE Bonus IS NULL;


H

Output:
O

+-------+----------+-------+
M

| EmpNo | Ename | Bonus |


+-------+----------+-------+
| 107 | Vergese | NULL |
| 108 | Nachaobi | NULL |
| 109 | Daribha | NULL |
+-------+----------+-------+

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
96
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

You cannot use = NULL. Always use IS NULL or IS NOT NULL.

Query: Select names of employees with bonus and working in department D01.

SELECT EName FROM EMPLOYEE


WHERE Bonus IS NOT NULL
AND DeptId = '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

• % → zero or more characters


• _ → exactly one character
ED

Query: Names that start with ‘S’


M

SELECT Ename FROM EMPLOYEE


WHERE Ename LIKE 'S%';
M

Output:
A

+----------+
H

| Ename |
O

+----------+
| Shabbir |
M

| Sanya |
+----------+

Query: Names that end with ‘a’

SELECT Ename FROM EMPLOYEE


WHERE Ename LIKE '%a';

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
97
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Output:

+----------+
| Ename |
+----------+
| Aaliya |
| Kritika |
| Sanya |

R
| Daribha |

L
| Tanya |
+----------+

N
EE
Query: Names containing ‘ya’

SELECT Ename FROM EMPLOYEE


WHERE Ename LIKE '%ya%';
H
AT
Output:

+--------+
M

| Ename |
+--------+
ED

| Sanya |
| Tanya |
M

+--------+
M

Query: Select employees whose name starts with ‘K’.


A

SELECT * FROM EMPLOYEE


WHERE Ename LIKE 'K%';
H

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.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
98
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

SELECT * FROM EMPLOYEE


WHERE Ename LIKE '%a'
AND 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

| 106 | Sanya | 48000 | 695 | D02 |


| 110 | Tanya | 50000 | 467 | D05 |
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

• One or more columns


• In ascending (ASC) or descending (DESC) order
M

If no order is specified, it defaults to ascending.

Basic Syntax:

SELECT column1, column2, ...


FROM table_name
ORDER BY column_name [ASC|DESC];

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
99
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Query – Sort by Salary (Ascending)

SELECT Ename, Salary


FROM EMPLOYEE
ORDER BY Salary;

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

ORDER BY Salary sorts rows by salary increasingly.


M

Query – Sort by Salary (Descending)


M

SELECT Ename, Salary


FROM EMPLOYEE
A

ORDER BY Salary DESC;


H

Output:
O

+----------+--------+
M

| Ename | Salary |
+----------+--------+
| Kritika | 60000 |
| Tanya | 50000 |
| Sanya | 48000 |
| Shabbir | 45000 |
| Daribha | 42000 |

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
100
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

| Joseph | 34000 |
| Nachaobi | 29000 |
| Gurpreet | 19000 |
| Vergese | 15000 |
| Aaliya | 10000 |
+----------+--------+

DESC keyword sorts values from highest to lowest.

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.

Query — Update GUID for Roll Number 3


M

The student with roll number 3 is a sibling of student 5, so assign same GUID.
ED

mysql> UPDATE STUDENT


-> SET GUID = 101010101010
-> WHERE RollNumber = 3;
M

Output:
M

Query OK, 1 row affected (0.06 sec)


A

Rows matched: 1 Changed: 1 Warnings: 0


H

You can verify with:


O

SELECT * FROM STUDENT;


M

Query — Update Multiple Columns in GUARDIAN Table

Change address and phone of guardian with GUID = 466444444666.

mysql> UPDATE GUARDIAN


-> SET GAddress = 'WZ - 68, Azad Avenue, Bijnour, MP',
-> GPhone = 9010810547
-> WHERE GUID = 466444444666;

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
101
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Output:

Query OK, 1 row affected (0.06 sec)


Rows matched: 1 Changed: 1 Warnings: 0

After Update:

mysql> SELECT * FROM GUARDIAN;

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

9.7.2 Data Deletion Syntax:


ED

DELETE FROM table_name


WHERE condition;
M

Caution: Omitting WHERE will delete all records from the table.
M

Query — Delete Student with Roll Number 2


A

mysql> DELETE FROM STUDENT


-> WHERE RollNumber = 2;
H

Output:
O
M

Query OK, 1 row affected (0.06 sec)

After Deletion:

SELECT * FROM STUDENT;

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
102
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

+------------+--------------+--------------+--------------+
| 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

SQL functions are categorized into:


ED

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

Differences Between Single Row and Multiple Row Functions


A
H

Multiple Row Functions


Feature Single Row Functions (Aggregate)
O

Operate On Individual rows Groups of rows


M

Return One result per row One result per group


Used In SELECT, WHERE, ORDER BY SELECT, HAVING
Examples UCASE(), POWER(), ROUND(), COUNT(), SUM(), AVG(), MAX(),
DAY() MIN()

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
103
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Database Used: CARSHOWROOM Tables:

• CUSTOMER
• EMPLOYEE
• INVENTORY
• SALE

R
L
1. Single Row (Scalar) Functions

N
A. Math Functions

EE
Function Description Example Output

POWER(x,y) x raised to the power y


H
SELECT POWER(2,3); 8
AT
ROUND(n,d) Rounds n to d decimals SELECT ROUND(2912.564,1); 2912.6
MOD(a,b) Remainder of a ÷ b SELECT MOD(21, 2); 1
M

Examples with INVENTORY table:


ED

1. GST Calculation:
M

SELECT ROUND(12/100 * Price, 1) AS GST FROM INVENTORY;


M

2. EMI and Remaining Amount:

SELECT CarId, FinalPrice,


A

ROUND(FinalPrice - MOD(FinalPrice,1000)/10, 0) AS EMI,


H

MOD(FinalPrice, 10000) AS "Remaining Amount"


FROM INVENTORY;
O

3. Rounded Commission:
M

SELECT InvoiceNo, SalePrice, ROUND(Commission, 0)


FROM SALE;

B. String Functions

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
104
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Function Description Example Output

LCASE() Converts to lowercase SELECT LCASE(‘SQL’); sql


UCASE() Converts to uppercase SELECT UCASE(‘sql’); SQL
MID(str,p,n) Extract substring from position p, SELECT MID(‘Informatics’, 3, form
length n 4);
LENGTH(str)Returns string length SELECT LENGTH(‘SQL’); 3

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]’);

Examples with CUSTOMER table: H


AT
1. Convert name and email:
M

SELECT LOWER(CustName), UPPER(Email) FROM CUSTOMER;

2. Extract name from email:


ED

SELECT LENGTH(Email), LEFT(Email, INSTR(Email,"@") - 1) FROM CUSTOMER;


M

3. MID() to extract area code:


M

SELECT MID(Phone, 3, 4) FROM CUSTOMER WHERE CustAdd LIKE '%Rohini%';

4. TRIM domain suffix:


A

SELECT TRIM('.com' FROM Email) FROM CUSTOMER;


H
O

C. Date Functions
M

Function Description Example Output

NOW() Returns system date and time SELECT NOW(); 2019-07-11


DATE() Extracts date from datetime SELECT DATE(NOW()); 2019-07-11
DAY(date) Returns day of month SELECT DAY(‘2003-03-24’); 24

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
105
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Function Description Example Output

MONTH(date) Returns numeric month SELECT MONTH(‘2003-11-28’); 11


MONTHNAME()
Returns name of the month SELECT November
MONTHNAME(‘2003-11-28’);
YEAR(date) Returns year SELECT YEAR(‘2003-11-28’); 2003
DAYNAME(date)
Returns weekday name SELECT Thursday

R
DAYNAME(‘2019-07-11’);

L
N
Examples with EMPLOYEE table:

EE
1. DOJ components:

SELECT DAY(DOJ), MONTH(DOJ), YEAR(DOJ) FROM EMPLOYEE;

2. Formatted joining date: H


AT
SELECT DAYNAME(DOJ), DAY(DOJ), MONTHNAME(DOJ), YEAR(DOJ)
FROM EMPLOYEE WHERE DAYNAME(DOJ) != 'Sunday';
M

3. Day of birth:
ED

SELECT EmpName, DAYNAME(DOB) FROM EMPLOYEE WHERE Salary > 25000;

2. Multiple Row (Aggregate) Functions


M
M

Function Description Example Output


A

COUNT(*) Total row count SELECT COUNT(*) FROM 4


MANAGER;
H

COUNT(col) Count of non-NULL values SELECT COUNT(MEMNAME) 3


O

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;

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
106
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Function Description Example Output

MAX() Highest value in column SELECT MAX(Price) FROM 673112.00


INVENTORY;
MIN() Lowest value in column SELECT MIN(Price) FROM 355205.00
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:

SELECT COUNT(DISTINCT Model) FROM INVENTORY;

3. Average price for LXI: H


AT
SELECT AVG(Price) FROM INVENTORY WHERE Model = 'LXI';
M

9.9 — GROUP BY Clause in SQL


ED

Purpose of GROUP BY The GROUP BY clause is used to:

• Aggregate rows with the same values in specified columns


M

• Perform operations like COUNT, SUM, AVG, etc. on groups


M

Basic Syntax:
A

SELECT column_name, AGGREGATE_FUNCTION(column_name)


H

FROM table_name
O

GROUP BY column_name;
M

Each column in the SELECT clause must either:

• Appear in the GROUP BY clause, or


• Be used inside an aggregate function

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
107
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

9.9.1 Examples Using GROUP BY Count Cars Sold Per Customer

SELECT CustID, COUNT(*) AS "Number of Cars"


FROM SALE
GROUP BY CustID;

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

Count Distinct Employees Handling Sales Per Model


M

SELECT Model, COUNT(DISTINCT EmpID)


FROM SALE, INVENTORY
ED

WHERE SALE.CarID = INVENTORY.CarID


GROUP BY Model;
M

Output:
M

+----------+---------------------------+
| Model | COUNT(DISTINCT EmpID) |
A

+----------+---------------------------+
H

| LXI | 2 |
| VXI | 1 |
O

+----------+---------------------------+
M

Combines two tables using JOIN condition (implicit syntax), then groups

Count Customers by Payment Mode

SELECT PaymentMode, COUNT(*)


FROM SALE
GROUP BY PaymentMode;

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
108
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

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

Payment Modes Used More Than Once


H

SELECT PaymentMode, COUNT(PaymentMode)


O

FROM SALE
M

GROUP BY PaymentMode
HAVING COUNT(*) > 1
ORDER BY PaymentMode;

Output:

+--------------+--------------------+
| PaymentMode | Count(PaymentMode) |

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
109
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

+--------------+--------------------+
| 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)

Types of Relational Operations H


AT
Operation Description
M

UNION ( �) Combines rows from two tables, removing duplicates


ED

INTERSECT ( ∩ ) Returns rows common to both tables


MINUS ( - ) Returns rows in the first table that are not in the second
M

CARTESIAN All combinations of rows from two tables


PRODUCT ( × )
M
A

Tables Used for Examples Table: DANCE


H

SNo Name Class


O
M

1 Aastha 7A
2 Mahira 6A
3 Mohit 7B
4 Sanjay 7A

Table: MUSIC

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
110
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

SNo Name Class

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;

Output (DANCE ∪ MUSIC):


H
AT
SNo Name Class
M

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

Combines students from both events without repeating common rows


M

9.10.2 – INTERSECT ( ∩ ) Query:

SELECT * FROM DANCE


INTERSECT
SELECT * FROM MUSIC;

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
111
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Output (DANCE ∩ MUSIC):

SNo Name Class

2 Mahira 6A
4 Sanjay 7A

R
Finds students common to both DANCE and MUSIC

L
N
EE
9.10.3 – MINUS ( - ) Query:

SELECT * FROM MUSIC


MINUS
SELECT * FROM DANCE; H
AT
Output (MUSIC - DANCE):
M

SNo Name Class


ED

1 Mehak 8A
3 Lavanya 7A
M

5 Abhay 8A
M

Shows students participating only in MUSIC


A
H

9.10.4 – CARTESIAN PRODUCT ( × ) Query:


O

SELECT * FROM DANCE, MUSIC;


M

Output (DANCE × MUSIC):

• Degree (columns): 6
• Cardinality (rows): 4 × 5 = 20 rows

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
112
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

SNo Name Class SNo Name Class

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
113
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

CHAPTER 10 COMPUTER NETWORKS

CHAPTER NOTES

10.1: Introduction to Computer Networks

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

• Small networks may connect just a few computers in one room.

H
• Large networks can span buildings, cities, or countries.
AT
What Makes Up a Network?
M

• Hosts (nodes): Computers, laptops, mobile phones, servers, etc.


• Networking Devices: Switches, routers, modems, etc.
ED

• Communication Media:

– Wired (like cables)


M

– Wireless (like air/waves)


M

Data Transfer
A

• Data is broken into packets for transmission.


• Devices that send, receive, store, or forward data are called nodes.
H

• Examples of nodes include:


O

– Modem, hub, switch, router


M

– Computers, printers, phones

Benefits of Networks

• Information exchange through emails, calls, websites


• Resource sharing: Printers, files, and storage
• Personal Networks: Hotspots on mobile phones forming PANs (Personal Area Networks)

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
114
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

10.2: Evolution of Networking

Origin of Networking: ARPANET

• 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

introduced **@** symbol.


1974 Telenet launched as the first commercial version of
ED

ARPANET.
1982 The term “Internet” was coined.
M

1983 TCP/IP protocol introduced as the standard on


ARPANET.
M

1986 NSFNET (National Science Foundation Network)


A

extended Internet access to more users.


H

1990 WWW (World Wide Web) invented by Tim


Berners-Lee using HTML, URL.
O

1997 First version of Wi-Fi (802.11 standard) introduced.


M

Try It Yourself Activity Suggestion:


Create a hotspot using a smartphone and connect other devices to experience a Personal Area Network.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
115
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

10.3: Types of Networks

Computer networks vary in size, coverage area, and data transfer speed. Based on these characteristics,
networks are broadly categorized as:

10.3.1 Personal Area Network (PAN)

• A smallest-sized network used for connecting personal devices.

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.

10.3.2 Local Area Network (LAN)


H
AT
• Connects devices like computers, phones, tablets, and printers within a limited area.
• Common in homes, schools, labs, offices, or campuses.
M

• Uses Ethernet cables, fiber optics, or Wi-Fi.

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

10.3.3 Metropolitan Area Network (MAN)


M

• Covers a city or a town.


• Data transfer speed: Comparable to LAN but slightly lower.
A

• Connects multiple LANs together.


H

Examples: - Cable TV networks - Broadband services in a city


O

Range: Up to 30–40 km
M

10.3.4 Wide Area Network (WAN)

• Largest network that spans countries and continents.


• Connects multiple LANs and MANs using wired/wireless media.

Examples: - The Internet: Largest example of a WAN - Large business or government networks linking
offices globally

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
116
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

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.

10.4: Network Devices

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)

Used in: Internet connections via telephone lines


M

10.4.2 Ethernet Card (NIC – Network Interface Card)


ED

• Installed in computers to enable wired networking.


• Each NIC has a unique MAC address to identify the device on the network.
M

• Supports data transfer from 10 Mbps to 1 Gbps.


• Connected to the network using an Ethernet cable.
M
A

10.4.3 RJ-45 Connector


H

• Full Form: Registered Jack 45


O

• An 8-pin connector used with Ethernet cables.


• Standard interface used to plug network cables into devices.
M

10.4.4 Repeater

• A device used to regenerate weak or lost signals.


• Signals weaken after traveling ~100 meters.
• Repeaters amplify and resend these signals to extend the transmission range.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
117
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

10.4.5 Hub

• A basic device used to connect multiple computers in a network.


• Broadcasts incoming data to all connected devices.
• Limitation: If multiple data packets arrive simultaneously, they collide.

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

• May be implemented using software, hardware, or both.


• Often combined with firewalls for security.
M

Example: Your home Internet provider acts as the gateway to the Internet.
A
H

10.5: Networking Topologies


O

What is a Topology?
M

• A topology is the arrangement or layout of computers and devices in a network.


• It determines how devices are interconnected and how data flows.

There are five common types of network topologies:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
118
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

10.5.1 Mesh Topology

• Every device is connected to every other device in the network.


• High reliability and security.
• Multiple devices can communicate simultaneously.
• Disadvantage: Complex and expensive due to the high number of cables and connections.
𝑛(𝑛−1)
To connect n devices fully: [Number of connections = 2 ]

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

• Limitation: If the bus fails, the entire network goes down.


• Less secure and less reliable compared to mesh or star.
ED

10.5.4 Star Topology

• Each device is connected to a central hub or switch.


M

• Data is routed through the central node.


M

• Advantages:

– Easy to troubleshoot and expand.


A

– Failure of one device does not affect others.


H

• Limitation: If the central hub fails, the whole network is down.


O
M

10.5.5 Tree or Hybrid Topology

• A hierarchical structure combining two or more topologies (e.g., star + bus).


• Common in WANs where multiple LANs are connected.
• Suitable for large and scalable networks.
• Data reaches the centralized device first, then travels to branches and nodes.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
119
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

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.

10.6: Identifying Nodes in a Networked Communication

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

• First 6 digits: Organisational Unique Identifier (OUI) – identifies the manufacturer.


• Last 6 digits: Serial Number – uniquely identifies the device.
• Example: 00:A0:C9:14:C8:29
ED

Use: Physically identifies a device within a local network.


M

10.6.2 IP Address (Internet Protocol Address)


M

• Definition: A logical address assigned to a device on a network that uses the Internet Protocol.
A

• Can change if the device connects to a different network (unlike MAC).


• Used globally to identify devices over the Internet.
H

Versions:
O
M

1. IPv4 (Internet Protocol Version 4)

• 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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
120
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

2. IPv6 (Internet Protocol Version 6)

• 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

How the Internet is Structured


ED

1. Your device connects to a modem/router.


2. The modem connects to a local ISP (Internet Service Provider).
3. The ISP connects to a national or regional network.
M

4. These regional networks connect together to form the Internet backbone.


M

So, the Internet is a multi-layered structure of interconnected networks.


A

10.7.2 The World Wide Web (WWW)


H

• The WWW is a collection of interlinked web pages and resources, stored on web servers and
O

accessed over the Internet.


M

• Invented by Sir Tim Berners-Lee in 1990.


• It allows users to access, share, and view content globally.

Key Technologies Behind the Web:

1. HTML (HyperText Markup Language):

• Language used to create webpages.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
121
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

• Ensures standard formatting and readability across systems.

2. URI (Uniform Resource Identifier):

• A unique address for each web resource.


• Often called URL (Uniform Resource Locator).
• Example: https://www.ncert.nic.in/textbook/textbook.htm

3. HTTP/HTTPS (HyperText Transfer Protocol):

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

But IP addresses are strings of numbers, which are difficult to remember.


ED

Problem: Would you rather type 164.100.60.233 or ncert.nic.in?

That’s where Domain Names come in!


M
M

What is a Domain Name?

• A user-friendly name assigned to an IP address.


A

• Makes it easier to access websites.


H

• Works like a phonebook:


O

– Instead of remembering phone numbers, we remember names.


M

Example:

Domain Name IP Address

ncert.nic.in 164.100.60.233
cbse.nic.in 164.100.107.32

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
122
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Domain Name IP Address

mhrd.gov.in 164.100.163.45
wikipedia.org 198.35.26.96

10.8.1 DNS Server What it does:

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

User → HTTP request to DNS Server → Receives IP address → Connects to server


ED

DNS Server Hierarchy

• The DNS system is hierarchical.


M

• At the top are 13 root servers named A to M.


• These root servers are distributed globally:
M

– 10 in the US
A

– 1 in London
H

– 1 in Stockholm
– 1 in Japan
O

Maintained by: Internet Assigned Numbers Authority (IANA)


M

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
123
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

CHAPTER 11 DATA COMMUNICATION

CHAPTER NOTES

11.1 Concept of Communication

What is Data Communication?

• Data Communication = Data + Communication.

R
• Data can be:

L
– Text

N
– Image

EE
– Audio

– Video H
AT
– Multimedia
M

• Communication refers to the act of sending or receiving this data.


• Therefore, Data Communication means the exchange of data between two or more devices that
ED

are connected via a network.


M

Requirements for Data Communication


M

• Devices must be:

– Networked/Connected
A

– Capable of sending and receiving data


H

• Data is transferred over a communication medium (wired or wireless).


O
M

Examples of Devices

• Personal computers
• Laptops
• Mobile phones
• Printers
• Servers
• Switches

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
124
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

11.2: Components of Data Communication

Any successful data communication involves the following five essential components:

1. Sender

• Device that sends data.


• Can be: Computer, mobile phone, smartwatch, walkie-talkie, video camera, etc.

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

• The path through which the message travels.


H

• Also known as transmission media.


• Can be:
O

– Wired: Ethernet cable, TV cable, telephone cable


M

– Wireless: Satellite, microwaves, etc.

5. Protocol

• A set of rules followed during communication.


• Ensures successful and reliable data transmission.
• Examples: Ethernet, HTTP

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
125
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

11.3: Measuring Capacity of Communication Media

In data communication, the transmission medium (also called a channel) has a capacity, which deter-
mines how much data it can carry.

This capacity is measured using two important concepts:

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:

• 1 Kilohertz (KHz) = 1,000 Hz H


AT
• 1 Megahertz (MHz) = 1,000 KHz = 1,000,000 Hz
M
ED

11.3.2 Data Transfer Rate


M

• Definition: Data Transfer Rate (also called bit rate) is the number of bits transmitted per second
between the source and destination.
M

• Measured in: Bits per second (bps)


A

Common Units:
H
O

Unit Value
M

1 Kbps 2¹0 bps = 1,024 bps


1 Mbps 2²0 bps = 1,024 Kbps
1 Gbps 2³0 bps = 1,024 Mbps
1 Tbps 2�0 bps = 1,024 Gbps

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
126
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

NOTE: - MBps (Megabytes per second) ≠ Mbps (Megabits per second)


- 1 Byte = 8 bits
- MBps is 8 times larger than Mbps.

Example 11.1 Q: A user uploads 10 pages in 20 seconds.


Each page has 1600 characters, and each character = 8 bits.
What is the required data rate?

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

• One-way (Unidirectional) communication.


ED

• Only the sender transmits; the receiver only receives.


• The channel is fully used by the sender only.
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

• IoT remote control of home appliances (e.g. turning on AC from office)

11.4.2 Half-Duplex Communication


• Two-way (Bidirectional) communication — but not at the same time.
• Both devices can send and receive data, but one at a time.
• The direction alternates — like a narrow one-way bridge used by vehicles from both sides one
at a time.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
127
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Examples:
• Walkie-talkie: Press-to-talk — while one speaks, others listen.

11.4.3 Full-Duplex Communication


• Two-way (Bidirectional) communication where both devices can send and receive simultane-
ously.
• Channel capacity is shared or duplicated.

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

11.5: Switching Techniques


A

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

There are two major types:

11.5.1 Circuit Switching


• A dedicated path is created before communication starts.
• The entire communication session uses this same path.
• Once the call or data transfer ends, the path is released.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
128
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Real-life Example:

• Old landline phone systems


When you make a call, a physical path is set from your phone to the receiver’s phone.

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

• Data/message is divided into small packets. H


AT
• Each packet may take different routes to the destination.
• At the destination, packets are reassembled in the correct order.
M

Packet Structure:
ED

• Header: Contains destination address and other control information


• Payload: The actual data/message
M

Features:
M

• Efficient — channel used only during transmission


A

• Flexible — can reroute packets if a path is busy


H

• Suitable for data-heavy applications like the Internet


O

Examples:
M

• Internet
• Email
• Streaming services

Comparison: Circuit vs Packet Switching

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
129
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Feature Circuit Switching Packet Switching

Path Setup Before communication Not required


Data Path Fixed Variable
Resource Usage Reserved throughout session Shared, released after use
Delay Low after setup Can vary per packet

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

Types of Transmission Media Transmission media are broadly classified into:

1. Guided (Wired) Media


ED

2. Unguided (Wireless) Media


M

11.6.1 Wired (Guided) Transmission Media


M

In guided media, data travels through a physical path like wires or cables.
A
H

(A) Twisted Pair Cable


O

• Made of two insulated copper wires twisted together like a DNA helix.
• Often bundled into larger cables with many such pairs.
M

• Twisting reduces electrical interference from nearby cables.


• Used in telephones and LANs.

Types:
• UTP (Unshielded Twisted Pair)
• STP (Shielded Twisted Pair) — has extra shielding for noise protection

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
130
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

(B) Coaxial Cable

• Has a central copper conductor surrounded by:

– Insulating material
– Outer conductor (copper mesh) for shielding
– Plastic covering

• More bandwidth and better shielding than twisted pair

R
• Used in:

– Cable TV

L
– High-frequency signals over longer distances

N
EE
(C) Optical Fiber Cable

• Transmits data using light signals.


• Structure:
H
AT
– Core: Thin glass strand that carries light
– Cladding: Less dense glass to reflect light
– Outer jacket: PVC or Teflon
M

• Uses refraction to guide light through the fiber


ED

Advantages:
M

• High bandwidth
• Long-distance transmission
M

• Immune to electromagnetic interference


A

Disadvantages:
H

• Expensive
O

• Unidirectional (requires two cables for full-duplex communication)


M

11.6.2 Wireless (Unguided) Transmission Media

Here, data is transmitted using electromagnetic waves through the air via antennas.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
131
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

Frequency Range:

• 3 KHz to 900 THz

• 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

Microwaves (1 GHz – 300 GHz)

• Unidirectional
M

• Needs line-of-sight
M

• Used in:

– Satellite communication
A

– Radar
H

– Mobile phones
O

Infrared Waves (300 GHz – 400 THz)


M

• Very high frequency


• Can’t pass through walls
• Used in:

– TV remotes
– Bluetooth devices
– Mobile-to-printer or mobile-to-mobile connections

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
132
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

11.6.3: Wireless Technologies

Wireless technologies enable devices to communicate without physical cables, using electromagnetic
waves over the air. Here are the major types discussed:

(A) Bluetooth

• Short-range wireless technology.

R
• Connects devices like:

L
– Mobile phones
– Headphones

N
– Printers

EE
– Keyboards
– Mice
– Computers

H
AT
Key Features:

• Uses 2.4 GHz unlicensed frequency band.


M

• Speed: 1 to 2 Mbps
• Range: Up to 10 meters
ED

• Devices must have a Bluetooth transceiver chip.


M

Network Type:

• Bluetooth devices form a Personal Area Network (PAN) called a Piconet.


M

• Works in master-slave configuration:


A

– 1 Master + up to 7 active slave devices.


H

– Total up to 255 devices can be part of a piconet, but only 8 are active at a time.
O

(B) Wireless LAN (Wi-Fi)


M

• A Local Area Network (LAN) that operates wirelessly.


• Based on IEEE standard 802.11 (commonly called Wi-Fi).

Key Components:

• Access Point (AP): Connects wireless devices to a wired network.


• Devices (laptops, phones, tablets, etc.) connect to the AP to:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
133
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

– Access the Internet


– Communicate with each other wirelessly

Advantages:

• Mobility: Users can move around while staying connected.


• Can be used to extend or replace wired networks.
• Popular in homes, schools, offices, and public areas (cafes, libraries).

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:

• Provides high-speed broadband over large areas.


H
AT
• Suitable for connecting multiple locations across a city or town.
• Covers distances beyond the range of Wi-Fi.
M

11.7: Mobile Telecommunication Technologies


ED

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

various generations (G).


M

1G (First Generation) – 1982


A

• Analog signals used to transmit only voice calls.


H

• Very basic — poor voice quality and no data transmission.


• Limited capacity and security.
O
M

2G (Second Generation) – 1991

• Switched from analog to digital signal transmission.


• Improved call quality and better security.
• Introduced SMS (Short Message Service) and MMS (Multimedia Messaging Service).
• More users could communicate simultaneously.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
134
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

3G (Third Generation) – Introduced ~2001

• Supported both voice and data services.


• Enabled:

– 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

• Introduced technologies like VoIP, VoLTE, and WiMAX.


M

• Revolutionized mobile Internet by offering broadband-like speeds.


ED

5G (Fifth Generation) – Current / Emerging

• Under development and being rolled out in stages.


M

• Aimed at ultra-fast Internet: speeds in Gbps.


M

• Will support:

– IoT (Internet of Things)


A

– M2M (Machine-to-Machine) communication


H

– Smart cities
– Connected vehicles
O
M

• Designed to connect billions of smart devices with minimal latency.

Key Concepts:

• IoT: Enables devices (like smart bulbs, ACs, cars) to communicate over the Internet.
• M2M: Direct device-to-device communication without human intervention.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
135
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

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

In essence, without protocols, communication would be chaotic and unreliable.

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:

* Sender: 1024 Mbps


H
AT
* Receiver: 512 Mbps
M

* Receiver needs to inform sender to adjust speed.


ED

Access Control

• Decides which device gets to send data on a shared medium to avoid data collisions.
M
M

Addressing

• Ensures that data reaches the correct device (node) on a network.


A
H

Error Checking & Packet Handling


O

• Ensures complete and correct data reaches the receiver.


M

• Helps with:

– Packet order
– Missing data
– Data reassembly

11.8.2 Common Protocols in Use

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
136
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

(A) HTTP – HyperText Transfer Protocol

• Used for accessing web pages on the Internet.


• Client-server model:

– Browser (client) sends request


– Web server responds

• Developed by Tim Berners-Lee at CERN in 1989.

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

– File naming convention


ED

(C) PPP – Point-to-Point Protocol

• Used for direct link between two devices (like routers or modems).
M

• Establishes a duplex connection (two-way).


• Handles:
M

– Device authentication
A

– Packet order
– Error reporting and recovery
H
O

(D) SMTP – Simple Mail Transfer Protocol


M

• Used for sending emails.


• Uses email headers to identify recipients.
• Adds outgoing emails to a queue, sends them, and removes recipients as delivery is confirmed.
• Delivers emails to receiver’s mailbox via an SMTP receiver program.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
137
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

(E) TCP/IP – Transmission Control Protocol / Internet Protocol

• The backbone protocol of the Internet.


• Uses client-server communication model.

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

• PPP: Direct device link


H
AT
• SMTP: Email sending
M

• TCP/IP: General internet communication (all types)


ED
M
M
A
H
O
M

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
138
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

CHAPTER 12 SECURITY ASPECTS

CHAPTER NOTES

12.1 - Threats and Prevention

1. Ideal vs. Practical Security

R
• Isolation as Ideal

– A computer with no external links cannot suffer network threats.

L
N
• Connectedness as Reality

EE
– Modern computing requires connectivity; complete isolation is not feasible.

2. Definition of Network Security


H
AT
• Goal: Protect devices and data from illegitimate access or misuse.
M

• Threats: Any method exploiting vulnerabilities or weaknesses in a network or communication


system to cause harm or damage one’s reputation.
ED

3. Key Terminology
M

• Threat: Ways to exploit network weaknesses.


M

• Vulnerability: A weakness in a system that can be exploited.


A

• Prevention: Measures taken to guard against threats.


H
O

4. Why Prevention Matters


M

• Connected devices introduce risk.

• Threats exploit vulnerabilities to damage hardware, steal data, or harm reputation.

• Prevention focuses on identifying and mitigating these threats before they succeed.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
139
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

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

• Remains dormant until the infected file is executed.


M

• Hampering resources: CPU time, memory, files, sensitive data.


M

• Common motives: steal passwords/data, corrupt files, spam contacts, control machines.
A

• Examples: CryptoLocker, ILOVEYOU, MyDoom, Sasser, Netsky, Slammer, Stuxnet.


H
O

12.2.2 Worms
M

• Standalone programs; no host program needed.

• Replicates and spreads automatically through networks (no human triggering).

• Causes unexpected or damaging behavior on infected systems.

• Examples: Storm Worm, Sobig, MSBlast, Code Red, Nimda, Morris Worm.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
140
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

12.2.3 Ransomware

• Targets user data by blocking access or threatening publication.

• May encrypt data, demanding ransom (often in Bitcoin).

• 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

• Spies on users/organizations by gathering information without knowledge.


ED

• Records and sends data (e.g., browsing habits, credentials) to external entities.
M

• Used by advertisers or attackers to capture sensitive information (credit cards, passwords).


M

12.2.6 Adware
A

• Designed to generate revenue via online advertisements.


H
O

• Displays pop-ups, webpages, or installation-screen ads.


M

• Uses pay-per-click or impression models.

• Generally annoying but can pave the way for more dangerous malware via unsafe links.

12.2.7 Keyloggers

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
141
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

• Can be software or hardware.

• Records keystrokes to create logs of keyboard usage.

• Sends logs externally, exposing passwords, emails, private conversations.

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

12.2.9 Combating Malware Common Infection Signs:


M

- Frequent pop-ups prompting downloads.


- Changed browser homepage.
A

- Mass emails sent from your account.


- Slow performance, crashes.
H

- Unknown startup programs.


O

- Programs opening/closing automatically.


M

- Sudden storage-space loss, random messages or sounds.


- Files appearing/disappearing without knowledge.

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.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
142
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

- Apply manufacturer updates/patches.


- Regularly back up important data.
- Enforce firewall protection.
- Avoid entering sensitive data on unknown/public computers or networks.
- Don’t click links or download attachments from unsolicited emails.
- Scan removable media with antivirus before use.
- Never share passwords/PINs.
- Remove unrecognized programs.

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

tify malicious software:

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

• Limitations: Cannot detect polymorphic malware (changes its signature) or code-encrypted


malware.
H

2. Sandbox Detection
O

• Executes suspect applications/files in a virtual “sandbox” environment.


M

• Observes behavioral “fingerprint” for malicious actions.

• Safer but slower, as it isolates unknown code from actual system resources.

3. Data Mining Techniques

• Applies data mining and machine learning to classify files as benign or malicious.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
143
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

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.

– Most recognized form is email spam.


M

• How It Works:
ED

– Individuals or organizations compile or purchase mailing lists.


M

– Send unsolicited advertisement links or invitations en masse.


M

– Fills recipients’ inboxes with junk, aiming to trick users into purchases or malware down-
loads.
A

• Countermeasures in Email Services:


H

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

12.5 - HTTP vs HTTPS

• HTTP (Hyper Text Transfer Protocol):

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
144
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

– Protocol governing data transmission over the World Wide Web.

– Sends information “in the clear” (unencrypted), making it vulnerable to interception by at-
tackers.

• HTTPS (Hyper Text Transfer Protocol Secure):

– Variant of HTTP that encrypts data before transmission.

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

– Can be hardware, software, or a combination of both.


H

• Function:
O

– Acts as a barrier between networks (e.g., LAN and WAN).


M

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
145
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

12.6.1 Types of Firewall

1. Network Firewall

• Placed between two or more networks.

• Monitors and filters traffic flowing between networks.

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

– A small file or data packet stored by a website on the client’s computer.


ED

– Edited only by the creating website; stored on the client’s device.


M

– Used to store browsing information to enhance user experience.

• Common Uses:
M

– Shopping carts: Remember items added to cart.


A
H

– Login credentials: Authentication cookies to keep users logged in across pages.


O

– Preferences: Language choice, search queries, recently viewed pages, autofill data (name,
M

address, D.O.B., etc.).

12.7.1 Threats due to Cookies

• Supercookies/Zombie Cookies:

– Malware disguised as cookies; zombie cookies get recreated after deletion.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
146
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

• 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

– Use skills to find and help fix security flaws.

– Employed by organizations to secure systems.


ED

2. Black Hats (Crackers)


– Use knowledge unethically to break laws, exploit flaws, and disrupt security.
M

3. Grey Hats
M

– Sit between white and black hats.


A

– Hack for challenge or curiosity, without clear monetary or political motives.


H

12.9 - Network Security Threats


O
M

12.9.1 Denial of Service (DoS)

• 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:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
147
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

– Simple DoS: Restarting the server/resource may restore service.

– Flooding DoS: Harder to recover, as malicious and legitimate traffic mix.

• Distributed Denial of Service (DDoS):

– Uses a network of compromised “zombie” machines (Bot-net) worldwide.

– 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

– Overwrites memory areas with malicious code that executes on overflow.


ED

3. Traffic Flooding:
– Overwhelms intrusion detection systems with packets, preventing proper monitoring.
M

12.9.3 Snooping (Sniffing)


M

• Definition: Secretly capturing and analyzing network traffic.


A

• Method:
H
O

– Taps into communication channel, reads packets, then re-injects them so network appears
normal.
M

• Use Cases:

– Malicious data theft if traffic is unencrypted.

– Legitimate network troubleshooting by administrators.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
148
STUDENT NOTES || SECOND PUC COMPUTER SCIENCE April 25, 2025

• Tools:

– Dedicated sniffing software or SPAN (Sniffer Port Analyzer) on hubs/switches.

12.9.4 Eavesdropping

• Definition: Real-time interception or monitoring of private communication (e.g., VoIP, instant


messages, video calls).

R
• Difference from Snooping:

L
– Eavesdropping: Live interception; doesn’t store for later.

N
– Snooping: Captures traffic for later analysis.

EE
• Examples:

– Wiretapping traditional phone lines. H


AT
– Hacking devices with rootkits to access built-in microphones/cameras.
M

For more information Visit:


ED

https://matheenhere.blogspot.com
M
M
A
H
O
M

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
149

You might also like