0% found this document useful (0 votes)
31 views92 pages

Ncert CS

The document provides a comprehensive overview of file handling in Python, including the differences between text and binary files, various file operations, and methods for reading and writing data. It also covers concepts such as pickling, serialization, and deserialization of Python objects, along with practical examples and exercises related to stacks and postfix expressions. Additionally, it emphasizes the importance of closing files after operations to prevent memory issues.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views92 pages

Ncert CS

The document provides a comprehensive overview of file handling in Python, including the differences between text and binary files, various file operations, and methods for reading and writing data. It also covers concepts such as pickling, serialization, and deserialization of Python objects, along with practical examples and exercises related to stacks and postfix expressions. Additionally, it emphasizes the importance of closing files after operations to prevent memory issues.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 92

File Handling in Python

Class 12 - NCERT Computer Science Solutions

Exercise

Question 1(a)

Differentiate between text file and binary file.

Answer

Text File Binary File

A text file consists of human readable A binary file is made up of non-human readable
characters, which can be opened by any text characters and symbols, which require specific
editor. programs to access its contents.

A text file is a file that stores information in


A binary file is a file that stores the information in
the form of a stream of ASCII or Unicode
the form of a stream of bytes.
characters.

In text files, each line of text is terminated


In a binary file, there is no delimiter for a line and
with a special character known as EOL
no character translations occur here.
(End of Line) character.

Files with extensions like .txt, .py, .csv etc Files with extensions like .jpg, .pdf etc are some
are some examples of text files. examples of binary files.

Question 1(b)

Differentiate between readline() and readlines().

Answer

readline() readlines()

The readline() function reads from a file in read The readlines() function, also reads from a
mode and returns the next line in the file or a blank file in read mode and returns a list of all
string if there are no more lines. lines in the file.

The returned data is of string type. The returned data is of list type.
readline() readlines()

Question 1(c)

Differentiate between write() and writelines().

Answer

write() writelines()

The write() method is used to write a The writelines() method is used to write multiple
single string to a file. strings to a file.

The write() method takes a string as an The writelines() method takes an iterable object like
argument. lists, tuple, etc. containing strings as an argument.

The write() method returns the number The writelines() method does not return the number of
of characters written on to the file. characters written in the file.

Question 2

Write the use and syntax for the following methods:

1. open()
2. read()
3. seek()
4. dump()

Answer

1. open() — The open() method opens the given file in the given mode and associates it with a file handle.
Its syntax is file_object = open(file_name, access_mode).
2. read() — The read() method is used to read data from a file object. It reads at most 'n' bytes from the
file, where 'n' is an optional parameter. If no 'n' is specified, the read() method reads the entire contents
of the file. Its syntax is: file_object.read(n).
3. seek() — This method is used to position the file object at a particular position in a file. Its syntax
is: file_object.seek(offset [, reference_point]).
4. dump() — This method is used to convert (pickling) Python objects for writing data in a binary file. Its
syntax is : dump(data_object, file_object).

Question 3
Write the file mode that will be used for opening the following files. Also, write the Python statements to open
the following files:

1. a text file “example.txt” in both read and write mode.


2. a binary file “bfile.dat” in write mode.
3. a text file “try.txt” in append and read mode.
4. a binary file “btry.dat” in read only mode.

Answer

1. File Mode: 'r+'

fh = open("example.txt", "r+")
2. File Mode: 'wb'

fh = open("bfile.dat", "wb")
3. File Mode: 'a+'

fh = open("try.txt", "a+")
4. File Mode: 'rb'

fh = open("btry.dat", "rb")

Question 4

Why is it advised to close a file after we are done with the read and write operations? What will happen if we
do not close it ? Will some error message be flashed ?

Answer

It is a good practice to close a file once we are done with the read and write operations. When we close a file,
the system frees the memory allocated to it. Python ensures that any unwritten or unsaved data is flushed
(written) to the file before it is closed. Therefore, it is always advised to close the file once our work is done. If
we do not close file explicitly it will close automatically later when it's no longer in use or when the program
terminates, without displaying any error message.

Question 5

What is the difference between the following set of statements (a) and (b):

(a)

P = open("practice.txt", "r")
P.read(10)
(b)

with open("practice.txt", "r") as P:


x = P.read()
Answer

The code given in (a) will open file "practice.txt" in read mode and will read 10 bytes from it. Also, it will not
close the file explicitly. On the other hand, the code given in (b) will open file "practice.txt" in read mode and
will read the entire content of the file. Furthermore, it will automatically close the file after executing the code
due to the with clause.

Question 6

Write a command(s) to write the following lines to the text file named hello.txt. Assume that the file is opened
in append mode.

“ Welcome my class”
“It is a fun place”
“You will learn and play”
Answer

file = open("hello.txt", "a")


lines = [
"Welcome my class\n",
"It is a fun place\n",
"You will learn and play"
]
file.writelines(lines)
file.close()

Question 7

Write a Python program to open the file hello.txt used in question no 6 in read mode to display its contents.
What will be the difference if the file was opened in write mode instead of append mode?

Answer

f = open("hello.txt", "r")
st = " "
while st:
st = f.readlines()
print(st)
f.close()
If the file "hello.txt" was opened in write mode instead of append mode, it would have overwritten the existing
content of the file. In write mode ("w"), opening the file truncates its content if it already exists and starts
writing from the beginning. Therefore, the previous contents of the file would have been replaced with the new
lines provided in the write mode code snippet.

Question 8

Write a program to accept string/sentences from the user till the user enters “END” to. Save the data in a text
file and then display only those sentences which begin with an uppercase alphabet.
Answer

f = open("new.txt", "w")
while True:
st = input("Enter next line:")
if st == "END":
break
f.write(st + '\n')
f.close()

f = open("new.txt", "r")
while True:
st = f.readline()
if not st:
break
if st[0].isupper():
print(st)
f.close()

Output

Enter next line:Hello world


Enter next line:welcome to
Enter next line:Python programming
Enter next line:END
Hello world

Python programming

Question 9

Define pickling in Python. Explain serialization and deserialization of Python object.

Answer

The pickling process serializes objects and converts them into a byte stream so that they can be stored in binary
files.

Serialization is the process of transforming data or an object in memory (RAM) into a stream of bytes called
byte streams. These byte streams, in a binary file, can then be stored on a disk, in a database, or sent through a
network. The serialization process is also called pickling. Deserialization or unpickling is the inverse of the
pickling process, where a byte stream is converted back into a Python object.

Question 10

Write a program to enter the following records in a binary file :


Item No — integer
Item_Name — string
Qty — integer
Price — float

Number of records to be entered should be accepted from the user. Read the file to display the records in the
following format:

Item No :
Item Name :
Quantity :
Price per item :
Amount : ( to be calculated as Price * Qty)

Answer

import pickle

with open("item.dat", 'wb') as itemfile:


n = int(input("How many records to be entered? "))
for i in range(n):
ino = int(input("Enter item no: "))
iname = input("Enter item name: ")
qty = int(input("Enter quantity: "))
price = float(input("Enter price: "))
item = {"Item no": ino, "Item Name": iname, "Qty":
qty, "Price": price}
pickle.dump(item, itemfile)
print("Successfully written item data")

with open("item.dat", "rb") as file:


try:
while True:
item = pickle.load(file)
print("\nItem No:", item["Item no"])
print("Item Name:", item["Item Name"])
print("Quantity:", item["Qty"])
print("Price per item:", item["Price"])
print("Amount:", item["Qty"] * item["Price"])
except EOFError:
pass

Output

How many records to be entered? 5


Enter item no: 11
Enter item name: Mobile
Enter quantity: 4
Enter price: 20000
Enter item no: 12
Enter item name: Laptop
Enter quantity: 2
Enter price: 35000
Enter item no: 13
Enter item name: Computer
Enter quantity: 1
Enter price: 50000
Enter item no: 14
Enter item name: Television
Enter quantity: 4
Enter price: 25000

Item No: 11
Item Name: Mobile
Quantity: 4
Price per item: 20000.0
Amount: 80000.0

Item No: 12
Item Name: Laptop
Quantity: 2
Price per item: 35000.0
Amount: 70000.0

Item No: 13
Item Name: Computer
Quantity: 1
Price per item: 50000.0
Amount: 50000.0

Item No: 14
Item Name: Television
Quantity: 4
Price per item: 25000.0
Amount: 100000.0
Chapter 3

Stack
Class 12 - NCERT Computer Science Solutions

Exercise

Question 1

State TRUE or FALSE for the following cases:

(a) Stack is a linear data structure.

(b) Stack does not follow LIFO rule.

(c) PUSH operation may result into underflow condition.

(d) In POSTFIX notation for expression, operators are placed after operands.

Answer

(a) True
Reason — A stack is a linear data structure following the Last In, First Out (LIFO) principle, where elements
are arranged sequentially.

(b) False
Reason — A stack follows the Last In, First Out (LIFO) rule. In a stack, the last element added is the first one
to be removed from the stack.

(c) False
Reason — When attempting to remove an element (POP operation) from an empty stack, it leads to an
underflow condition, resulting in an exception being raised.

(d) True
Reason — In POSTFIX notation for expression, operators are placed after the corresponding operands.

Question 2(a)

Find the output of the following code:

result = 0
numberList = [10, 20, 30]
numberList.append(40)
result = result + numberList.pop()
result = result + numberList.pop()
print("Result=", result)
Answer

Output

Result= 70

Explanation

The code initializes result to 0 and creates a list [10, 20, 30]. It appends 40 to the list and then performs
two pop() operations on the list, which removes and returns the last element (40 and 30). These values are
added to result, resulting in result being 70. Finally, the code prints "Result=" followed by the value
of result, which is 70.

Question 2(b)

Find the output of the following code:

answer = []; output = ''


answer.append('T')
answer.append('A')
answer.append('M')
ch = answer.pop()
output = output + ch
ch = answer.pop()
output = output + ch
ch = answer.pop()
output = output + ch
print("Result=", output)
Answer

Output

Result= MAT

Explanation

The code initializes an empty list answer and an empty string output. It appends the characters 'T', 'A',
and 'M' to the answer list. After appending, answer list becomes ['T', 'A', 'M'].
After that, three pop() operations are performed on answer, removing and returning the last element each
time ('M', 'A', and 'T' respectively). These characters are concatenated to the output string.
So, output string becomes MAT which is printed as the final output.

Question 3

Write a program to reverse a string using stack.


Answer

def push(stack, item):


stack.append(item)

def pop(stack):
if stack == []:
return
return stack.pop()

def reverse(string):
n = len(string)
stack = []
for i in range(n):
push(stack, string[i])
string = ""
for i in range(n):
string += pop(stack)
return string

string = input("Enter a string: ")


print("String:", string)
reversedStr = reverse(string)
print("Reversed String:", reversedStr)

Output

Enter a string: Hello world


String: Hello world
Reversed String: dlrow olleH

Question 4

For the following arithmetic expression:

((2 + 3) * (4 / 2)) + 2

Show step-by-step process for matching parentheses using stack data structure.

Answer

For matching parentheses, we can push in the stack for each opening parenthesis of the expression and pop
from the stack for each closing parenthesis.

Scanning from left to right:


Symbol Stack Action

( ↑ — top
( Push

((
( Push

2 ..........

+ ..........

3 ..........

(
) Pop

* ..........

((
( Push

4 ..........

/ ..........

2 ..........

(
) Pop

) #Empty Pop
+ ..........

2 #Empty ..........

Empty stack => Balanced Parentheses

Question 5(a)

Evaluate following postfix expression while showing status of stack after each operation given A = 3, B = 5, C
= 1, D = 4.

AB + C *

Answer

AB + C * = 35 + 1 *

Scanning from left to right :

Intermediate
Symbol Action Stack
output

3
3 Push

53
5 Push

#Empty

+ Pop twice and Evaluate and Push back 8 3+5=8

18
1 Push

#Empty

* Pop twice, Evaluate Push back 8 1*8=8

Hence, AB + C * = 35 + 1 * = 8

Question 5(b)

Evaluate following postfix expression while showing status of stack after each operation given A = 3, B = 5, C
= 1, D = 4.

AB * C / D *

Answer

AB * C / D * = 35 * / 4 *

Scanning from left to right :

Intermediate
Symbol Action Stack
output

3 Push 3

53
5 Push

#Empty

* Pop twice, Evaluate and Push back 15 3 * 5 = 15

1 15
1 Push

/ Pop twice, Evaluate and Push back #Empty 15/1 = 15


15

4 15
4 Push

#Empty

* Pop twice, Evaluate and Push back 60 15 * 4 = 60

Hence, AB * C / D * = 35 * / 4 * = 60

Question 6(a)

Convert the following infix notation to postfix notation, showing stack and string contents at each step.

A+B-C*D

Answer

Given,

A+B-C*D

Scanning from left to right :

Postfix
Symbol Action Stack
Expression

+ A
+ Push in stack

B AB

- Equal precedence to +. Pop from stack, add in - AB+


expression then push this operator(-)

*- AB+C
* Higher precedence than (-), hence Push

D AB+CD

End of
Pop all and add to expression #Empty AB+CD*-
expression

Postfix notation of A + B - C * D = AB+CD*-

Question 6(b)

Convert the following infix notation to postfix notation, showing stack and string contents at each step.

A * (( C + D)/E)

Answer

Given,

A * (( C + D)/E)

Scanning from left to right:

Postfix
Symbol Action Stack
Expression

A A

*
* Push

( Push (*

((*
( Push

+((* AC
+ Push

D ACD

(*
Pop till one opening bracket is popped and add
)
popped operator to expression

ACD+
/(*
/ Push

E ACD+E

*
Pop till one opening bracket is popped and add
) ACD+E/
popped operator to expression

End of #Empt
Pop all and add to expression ACD+E/*
expression y

Postfix notation of A * (( C + D)/E) = ACD+E/*

Question 7

Write a program to create a Stack for storing only odd numbers out of all the numbers entered by the user.
Display the content of the Stack along with the largest odd number in the Stack. (Hint. Keep popping out the
elements from stack and maintain the largest element retrieved so far in a variable. Repeat till Stack is empty)

Answer
def push(stack, item):
stack.append(item)

def pop(stack):
if stack == []:
return
return stack.pop()

def oddStack(num):
if num % 2 == 1:
push(stack, num)

def GetLargest(stack):
elem = pop(stack)
large = elem
while elem != None:
if large < elem:
large = elem
elem = pop(stack)
return large

n = int(input("How many numbers?"))


stack = []
for i in range(n):
number = int(input("Enter number:"))
oddStack(number)
print("Stack created is", stack)
bigNum = GetLargest(stack)
print("Largest number in stack", bigNum)

Output

How many numbers?8


Enter number:1
Enter number:2
Enter number:3
Enter number:4
Enter number:5
Enter number:6
Enter number:7
Enter number:8
Stack created is [1, 3, 5, 7]
Largest number in stack 7
Chapter 5

Sorting
Class 12 - NCERT Computer Science Solutions

Exercise

Question 1

Consider a list of 10 elements:

numList = [7, 11, 3, 10, 17, 23, 1, 4, 21, 5].

Display the partially sorted list after three complete passes of Bubble sort.

Answer

numList = [7, 11, 3, 10, 17, 23, 1, 4, 21, 5]


n = len(numList)
for i in range(3):
for j in range(0, n - i - 1):
if numList[j] > numList[j + 1]:
numList[j], numList[j + 1] = numList[j + 1],
numList[j]
print("Partially sorted list after three passes of Bubble
sort:")
print(numList)

Output

Partially sorted list after three passes of Bubble sort:


[3, 7, 10, 1, 4, 11, 5, 17, 21, 23]

Question 2

Identify the number of swaps required for sorting the following list using selection sort and bubble sort and
identify which is the better sorting technique with respect to the number of comparisons.

List 1 :

63 42 21 9

Answer
Selection Sort
Bubble Sort
As we can see from the diagrammatic representation above, selection sort performs 2 swaps whereas bubble
sort performs 6 swaps. Hence, selection sort is a better sorting technique with respect to the number of
comparisons.

Question 3

Consider the following lists:

List 1:

2 3 5 7 11

List 2:

11 7 5 3 2

If the lists are sorted using Insertion sort then which of the lists List 1 or List 2 will make the minimum number
of comparisons ? Justify using diagrammatic representation.

Answer

Diagrammatic representation of the sorting of List 1 and List 2 using Insertion sort is shown below:
From the diagrams, we can clearly see that List 1 requires no swaps, while List 2 requires multiple (10) swaps
during the insertion sort process. Therefore, List 1 makes the minimum number of comparisons and swaps
when sorted using insertion sort.

Question 4

Write a program using user defined functions that accepts a List of numbers as an argument and finds its
median. (Hint : Use bubble sort to sort the accepted list. If there are odd number of terms, the median is the
center term. If there are even number of terms, add the two middle terms and divide by 2 get median)

Answer

def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]

def find_median(arr):
n = len(arr)
bubble_sort(arr)

if n % 2 == 0:
mid1 = arr[n // 2 - 1]
mid2 = arr[n // 2]
median = (mid1 + mid2) / 2
else:
median = arr[n // 2]

return median

numbers = eval(input("Enter a list of numbers: "))


median = find_median(numbers)
print("Median of the list is:", median)

Output

Enter a list of numbers: [20, 2, 31, 4, 10]


Median of the list is: 10

Enter a list of numbers: [22, 11, 16, 7, 8, 12]


Median of the list is: 11.5

Question 5

All the branches of XYZ school conducted an aptitude test for all the students in the age group 14 - 16. There
were a total of n students. The marks of n students are stored in a list. Write a program using a user defined
function that accepts a list of marks as an argument and calculates the 'xth' percentile (where x is any number
between 0 and 100). You are required to perform the following steps to be able to calculate the 'xth' percentile.

Note: Percentile is a measure of relative performance i.e. It is calculated based on a candidate's performance
with respect to others. For example : If a candidate's score is in the 90th percentile, that means she/he scored
better than 90% of people who took the test.

Steps to calculate the xth percentile:

1. Order all the values in the data set from smallest to largest using Selection Sort. In general any of the
sorting methods can be used.
2. Calculate index by multiplying x percent by the total number of values, n. For example: to find 90th
percentile for 120 students: 0.90 * 120 = 108.
3. Ensure that the index is a whole number by using math.round().
4. Display the value at the index obtained in Step 3.

The corresponding value in the list is the xth percentile.

Answer

def selection_sort(arr):
n = len(arr)
for i in range(n - 1):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]

def calculate_percentile(marks_list, percentile):


selection_sort(marks_list)
n = len(marks_list)
index = round(percentile * n / 100) - 1
if index >= 0 and index < n:
return marks_list[index]
else:
return None

marks = eval(input("Enter list of marks"))


xth_percentile = int(input("Enter percentile to be
calculated: "))
result = calculate_percentile(marks, xth_percentile)

if result is not None:


print("The", xth_percentile, "th percentile is:",
result)
else:
print("Invalid percentile.")

Output

Enter list of marks[35, 25, 45, 50, 60, 75, 80]


Enter percentile to be calculated: 70
The 70 th percentile is: 60

Question 6

During admission in a course, the names of the students are inserted in ascending order. Thus, performing the
sorting operation at the time of inserting elements in a list. Identify the type of sorting technique being used and
write a program using a user defined function that is invoked every time a name is input and stores the name in
ascending order of names in the list.

Answer

The sorting technique being used in the program is Insertion Sort. In Insertion Sort, elements are sorted by
inserting each element into its correct position in the sorted part of the list.

def insert_name(names_list, new_name):


index = len(names_list)
for i in range(index):
if new_name < names_list[i]:
index = i
break
names_list.insert(index, new_name)

names_list = []

while True:
new_name = input("Enter a name (or 'exit' to stop): ")
if new_name.lower() == 'exit':
break
insert_name(names_list, new_name)

print("Sorted list of names:")


for name in names_list:
print(name)

Output

Enter a name (or 'exit' to stop): Amruth


Enter a name (or 'exit' to stop): Parth
Enter a name (or 'exit' to stop): Sanket
Enter a name (or 'exit' to stop): Shrestha
Enter a name (or 'exit' to stop): Nikita
Enter a name (or 'exit' to stop): exit
Sorted list of names:
Amruth
Nikita
Parth
Sanket
Shrestha
Chapter 6

Searching
Class 12 - NCERT Computer Science Solutions

Exercise

Question 1

Using linear search determine the position of 8, 1, 99 and 44 in the list:

[1, -2, 32, 8, 17, 19, 42, 13, 0, 44]


Draw a detailed table showing the values of the variables and the decisions taken in each pass of linear search.

Answer

list1 = [1, -2, 32, 8, 17, 19, 42, 13, 0, 44]


n = 10

1. Item = 8

index 0 1 2 3 4 5 6 7 8 9

elements 1 -2 32 8 17 19 42 13 0 44

The step-by-step process of linear search is as follows:

index index < n list1[index] = key index = index + 1

0 0 < 10 ? Yes 1 = 8 ? No 1

1 1 < 10 ? Yes -2 = 8 ? No 2

2 2 < 10 ? Yes 32 = 8 ? No 3

3 3 < 10 ? Yes 8 = 8 ? Yes

Therefore, for item 8, linear search returns 3 (index).


2. Item = 1

index 0 1 2 3 4 5 6 7 8 9

elements 1 -2 32 8 17 19 42 13 0 44

The step-by-step process of linear search is as follows:

index index < n list1[index] = key index = index + 1

0 0 < 10 ? Yes 1 = 1 ? Yes

Therefore, for item 1, linear search returns 0 (index).

3. Item = 99

index 0 1 2 3 4 5 6 7 8 9

elements 1 -2 32 8 17 19 42 13 0 44

The step-by-step process of linear search is as follows:

index index < n list1[index] = key index = index + 1

0 0 < 10 ? Yes 1 = 99 ? No 1

1 1 < 10 ? Yes -2 = 99 ? No 2

2 2 < 10 ? Yes 32 = 99 ? No 3

3 3 < 10 ? Yes 8 = 99 ? No 4

4 4 < 10 ? Yes 17 = 99 ? No 5

5 5 < 10 ? Yes 19 = 99 ? No 6

6 6 < 10 ? Yes 42 = 99 ? No 7

7 7 < 10 ? Yes 13 = 99 ? No 8
index index < n list1[index] = key index = index + 1

8 8 < 10 ? Yes 0 = 99 ? No 9

9 9 < 10 ? Yes 44 = ? No 10

10 10 < 10 ? No

Since the item 99 is not found in the list, the linear search algorithm returns -1.

4. Item = 44

index 0 1 2 3 4 5 6 7 8 9

elements 1 -2 32 8 17 19 42 13 0 44

The step-by-step process of linear search is as follows:

index index < n list1[index] = key index = index + 1

0 0 < 10 ? Yes 1 = 44 ? No 1

1 1 < 10 ? Yes -2 = 44 ? No 2

2 2 < 10 ? Yes 32 = 44 ? No 3

3 3 < 10 ? Yes 8 = 44 ? No 4

4 4 < 10 ? Yes 17 = 44 ? No 5

5 5 < 10 ? Yes 19 = 44 ? No 6

6 6 < 10 ? Yes 42 = 44 ? No 7

7 7 < 10 ? Yes 13 = 44 ? No 8

8 8 < 10 ? Yes 0 = 44 ? No 9
index index < n list1[index] = key index = index + 1

9 9 < 10 ? Yes 44 = 44 ? yes

Therefore, for item 44, linear search returns 9 (index).

Question 2

Use the linear search program to search the key with value 8 in the list having duplicate values such as [42, -2,
32, 8, 17, 19, 42, 13, 8, 44]. What is the position returned? What does this mean?

Answer

def linear_search(lst, key):


position = -1
for i in range(len(lst)):
if lst[i] == key:
position = i
break
return position

lst = [42, -2, 32, 8, 17, 19, 42, 13, 8, 44]


key = 8
result = linear_search(lst, key)

if result != -1:
print("The position of key", key, "in the list is",
result)
else:
print("Key", key, "not found in the list.")

Output

The position of key 8 in the list is 3


It will return the index 3 (position 4) for the value 8, because at this index first 8 is encountered. Simple linear
search returns the index of first successful match.

Question 3

Write a program that takes as input a list having a mix of 10 negative and positive numbers and a key value.
Apply linear search to find whether the key is present in the list or not. If the key is present it should display the
position of the key in the list otherwise it should print an appropriate message. Run the program for at least 3
different keys and note the result.

Answer

def lsearch(list1, key):


for k in range(0, len(list1)):
if key == list1[k]:
return k
return -1
list1 = eval(input("Enter the list: "))
for i in range(3):
item = int(input("Enter item to be searched for: "))
pos = lsearch(list1, item)
if pos == -1:
print(item, "not found")
else:
print(item, "found at index", pos)

Output

Enter the list: [32, -5, 34, 45, -6, 78, 87, 12, -9, 10]
Enter item to be searched for: -5
-5 found at index 1
Enter item to be searched for: 10
10 found at index 9
Enter item to be searched for: 100
100 not found

Question 4

Write a program that takes as input a list of 10 integers and a key value and applies binary search to find
whether the key is present in the list or not. If the key is present it should display the position of the key in the
list otherwise it should print an appropriate message. Run the program for at least 3 different key values and
note the results.

Answer

def binarysearch(list1, key):


first = 0
last = len(list1) - 1

while first <= last:


mid = (first + last) // 2

if list1[mid] == key:
return mid
elif key < list1[mid]:
last = mid - 1
else:
first = mid + 1
return -1

list1 = eval(input("Enter the list: "))

for i in range(3):
key = int(input("Enter the key to be searched: "))
pos = binarysearch(list1, key)
if pos == -1:
print(key, "not found")
else:
print(key, "found at index", pos)

Output

Enter the list: [1, 33, 55, -77, 45, 23, -56, 23, 46, -89]
Enter the key to be searched: 33
33 found at index 1
Enter the key to be searched: 45
45 found at index 4
Enter the key to be searched: 99
99 not found

Question 5

Following is a list of unsorted/unordered numbers:

[50, 31, 21, 28, 72, 41, 73, 93, 68, 43,
45, 78, 5, 17, 97, 71, 69, 61, 88, 75,
99, 44, 55, 9]
1. Use linear search to determine the position of 1, 5, 55 and 99 in the list. Also note the number of key
comparisons required to find each of these numbers in the list.
2. Use a Python function to sort/arrange the list in ascending order.
3. Again, use linear search to determine the position of 1, 5, 55 and 99 in the list and note the number of
key comparisons required to find these numbers in the list.
4. Use binary search to determine the position of 1, 5, 55 and 99 in the sorted list. Record the number of
iterations required in each case.

Answer

1.

def linear_search(arr, key):


comparisons = 0
for k in range(len(arr)):
comparisons += 1
if key == arr[k]:
return k, comparisons
return -1, comparisons

def binary_search(arr, key):


comparisons = 0
first = 0
last = len(arr) - 1

while first <= last:


mid = (first + last) // 2
comparisons += 1

if arr[mid] == key:
return mid, comparisons
elif key < arr[mid]:
last = mid - 1
else:
first = mid + 1

return -1, comparisons

original_list = [50, 31, 21, 28, 72, 41, 73, 93, 68, 43,
45, 78, 5, 17, 97, 71, 69, 61, 88, 75, 99, 44, 55, 9]
keys = [1, 5, 55, 99]

print("Linear Search on Unsorted List:")


for key in keys:
pos, comparisons = linear_search(original_list, key)
if pos == -1:
print(key, "not found")
else:
print(key, "found at index", pos)
print("Number of comparisons:", comparisons)

original_list.sort()
print("\nSorted List:", original_list)

print("\nLinear Search on Sorted List:")


for key in keys:
pos, comparisons = linear_search(original_list, key)
if pos == -1:
print(key, "not found")
else:
print(key, "found at index", pos)
print("Number of comparisons:", comparisons)

print("\nBinary Search on Sorted List:")


for key in keys:
pos, comparisons = binary_search(original_list, key)
if pos == -1:
print(key, "not found")
else:
print(key, "found at index", pos)
print("Number of comparisons:", comparisons)

Output

Linear Search on Unsorted List:


1 not found
5 found at index 12
Number of comparisons: 13
55 found at index 22
Number of comparisons: 23
99 found at index 20
Number of comparisons: 21

Sorted List: [5, 9, 17, 21, 28, 31, 41, 43, 44, 45, 50, 55,
61, 68, 69, 71, 72, 73, 75, 78, 88, 93, 97, 99]

Linear Search on Sorted List:


1 not found
5 found at index 0
Number of comparisons: 1
55 found at index 11
Number of comparisons: 12
99 found at index 23
Number of comparisons: 24

Binary Search on Sorted List:


1 not found
5 found at index 0
Number of comparisons: 4
55 found at index 11
Number of comparisons: 1
99 found at index 23
Number of comparisons: 5
Question 6

Write a program that takes as input the following unsorted list of English words:

[Perfect, Stupendous, Wondrous, Gorgeous, Awesome,


Mirthful, Fabulous, Splendid, Incredible,
Outstanding, Propitious, Remarkable, Stellar,
Unbelievable, Super, Amazing].
1. Use linear search to find the position of Amazing, Perfect, Great and Wondrous in the list. Also note the
number of key comparisons required to find these words in the list.
2. Use a Python function to sort the list.
3. Again, use linear search to determine the position of Amazing, Perfect, Great and Wondrous in the list
and note the number of key comparisons required to find these words in the list.
4. Use binary search to determine the position of Amazing, Perfect, Great and Wondrous in the sorted list.
Record the number of iterations required in each case.

Answer

def linear_search(arr, key):


comparisons = 0
for k in range(len(arr)):
comparisons += 1
if key == arr[k]:
return k, comparisons
return -1, comparisons

def binary_search(arr, key):


comparisons = 0
first = 0
last = len(arr) - 1

while first <= last:


mid = (first + last) // 2
comparisons += 1

if arr[mid] == key:
return mid, comparisons
elif key < arr[mid]:
last = mid - 1
else:
first = mid + 1

return -1, comparisons

original_list = ['Perfect', 'Stupendous', 'Wondrous',


'Gorgeous', 'Awesome', 'Mirthful', 'Fabulous', 'Splendid',
'Incredible', 'Outstanding', 'Propitious', 'Remarkable',
'Stellar', 'Unbelievable', 'Super', 'Amazing']

keys = ['Amazing', 'Perfect', 'Great', 'Wondrous']

print("Linear Search on Unsorted List:")


for key in keys:
pos, comparisons = linear_search(original_list, key)
if pos == -1:
print(key, "not found")
else:
print(key, "found at index", pos)
print("Number of comparisons:", comparisons)

original_list.sort()
print("\nSorted List:", original_list)

print("\nLinear Search on Sorted List:")


for key in keys:
pos, comparisons = linear_search(original_list, key)
if pos == -1:
print(key, "not found")
else:
print(key, "found at index", pos)
print("Number of comparisons:", comparisons)

print("\nBinary Search on Sorted List:")


for key in keys:
pos, comparisons = binary_search(original_list, key)
if pos == -1:
print(key, "not found")
else:
print(key, "found at index", pos)
print("Number of comparisons:", comparisons)

Output

Linear Search on Unsorted List:


Amazing found at index 15
Number of comparisons: 16
Perfect found at index 0
Number of comparisons: 1
Great not found
Wondrous found at index 2
Number of comparisons: 3

Sorted List: ['Amazing', 'Awesome', 'Fabulous', 'Gorgeous',


'Incredible', 'Mirthful', 'Outstanding', 'Perfect',
'Propitious', 'Remarkable', 'Splendid', 'Stellar',
'Stupendous', 'Super', 'Unbelievable', 'Wondrous']

Linear Search on Sorted List:


Amazing found at index 0
Number of comparisons: 1
Perfect found at index 7
Number of comparisons: 8
Great not found
Wondrous found at index 15
Number of comparisons: 16

Binary Search on Sorted List:


Amazing found at index 0
Number of comparisons: 4
Perfect found at index 7
Number of comparisons: 1
Great not found
Wondrous found at index 15
Number of comparisons: 5

Question 7

Estimate the number of key comparisons required in binary search and linear search if we need to find the
details of a person in a sorted database having 230 (1,073,741,824) records when details of the person being
searched lies at the middle position in the database. What do you interpret from your findings?

Answer

For binary search it will be just 1 comparison, as binary search starts with comparing the element at middle and
the search will be successful with the first comparison as the desired element lies at the middle of the database.

For linear search it will be 115 comparisons, as linear search starts with comparing the first element and keeps
on comparing the successive elements and thus it will take 115 comparisons to reach at the middle element,
which is the desired element.

Therefore, for a sorted list, binary search is much more efficient choice for searching compared to linear search.

Question 8
Use the hash function: h(element) = element % 10 to store the collection of numbers: [44, 121, 55, 33, 110, 77,
22, 66] in a hash table. Display the hash table created. Search if the values 11, 44, 88 and 121 are present in the
hash table, and display the search results.

Answer

def h(element, hashTable):


if (hashTable[element % 10] == key):
return ((element % 10) + 1)
else:
return -1

hashTable = [None, None, None, None, None, None, None,


None, None, None]

print("We have created a hashTable of 10 positions:")


print(hashTable)
L = [44, 121, 55, 33, 110, 77, 22, 66]
print("The given list is", L[::] )

for i in range(0,len(L)):
hashTable[L[i]%10] = L[i]

print("The hash table contents are: " )


for i in range(0,len(hashTable)):
print("hashindex=", i," , value =", hashTable[i])

keys = [11, 44, 88, 121]


for key in keys:
position = h(key,hashTable)
if position == -1:
print("Number",key,"is not present in the hash
table")
else:
print("Number ",key," present at ",position, "
position")

Output

We have created a hashTable of 10 positions:


[None, None, None, None, None, None, None, None, None,
None]
The given list is [44, 121, 55, 33, 110, 77, 22, 66]
The hash table contents are:
hashindex= 0 , value = 110
hashindex= 1 , value = 121
hashindex= 2 , value = 22
hashindex= 3 , value = 33
hashindex= 4 , value = 44
hashindex= 5 , value = 55
hashindex= 6 , value = 66
hashindex= 7 , value = 77
hashindex= 8 , value = None
hashindex= 9 , value = None
Number 11 is not present in the hash table
Number 44 present at 5 position
Number 88 is not present in the hash table
Number 121 present at 2 position

Question 9

Write a Python program by considering a mapping of list of countries and their capital cities such as:

CountryCapital= {'India':'New Delhi','UK':


'London','France':'Paris',
'Switzerland': 'Berne',
'Australia': 'Canberra'}
Let us presume that our hash function is the length of the Country Name. Take two lists of appropriate size: one
for keys (Country) and one for values (Capital). To put an element in the hash table, compute its hash code by
counting the number of characters in Country, then put the key and value in both the lists at the corresponding
indices. For example, India has a hash code of 5. So, we store India at the 5th position (index 4) in the keys list,
and New Delhi at the 5th position (index 4) in the values list and so on. So that we end up with:

hash index = length of key - 1 List of Keys List of Values

0 None None

1 UK London

2 None None

3 Cuba Havana

4 India New Delhi

5 France Paris

6 None None
hash index = length of key - 1 List of Keys List of Values

7 None None

8 Australia Canberra

9 None None

10 Switzerland Berne

Now search the capital of India, France and the USA in the hash table and display your result.

Answer

CountryCapital = {'India': 'New Delhi', 'UK': 'London',


'France': 'Paris',
'Switzerland': 'Berne', 'Australia':
'Canberra'}

keys = [None, None, None, None, None, None, None, None,


None, None, None]
values = [None, None, None, None, None, None, None, None,
None, None, None]

def calculate_hash_index(key):
return len(key) - 1

for country, capital in CountryCapital.items():


index = calculate_hash_index(country)
keys[index] = country
values[index] = capital

print("hash index = length of key - 1 | List of Keys | List


of Values")

for i in range(len(keys)):
print(str(i) + "| " + str(keys[i]) + "| " +
str(values[i]))
search_keys = ['India', 'France', 'USA']
print("\nSearch Results:")
for key in search_keys:
index = calculate_hash_index(key)
if keys[index] == key:
print("Capital of", key, ":", values[index])
else:
print("Capital of ", key, ": Not found")

Output

hash index = length of key - 1 | List of Keys | List of


Values
0| None| None
1| UK| London
2| None| None
3| None| None
4| India| New Delhi
5| France| Paris
6| None| None
7| None| None
8| Australia| Canberra
9| None| None
10| Switzerland| Berne

Search Results:
Capital of India : New Delhi
Capital of France : Paris
Capital of USA : Not found
Chapter 8

Database Concepts
Class 12 - NCERT Computer Science Solutions

Exercise

Question 1

Give the terms for each of the following:

(a) Collection of logically related records.

(b) DBMS creates a file that contains description about the data stored in the database.

(c) Attribute that can uniquely identify the tuples in a relation.

(d) Special value that is stored when actual data value is unknown for an attribute.

(e) An attribute which can uniquely identify tuples of the table but is not defined as primary key of the table.

(f) Software that is used to create, manipulate and maintain a relational database.

Answer

(a) Table

(b) Data dictionary

(c) Primary key

(d) NULL

(e) Alternate Key

(f) Database Management System (DBMS)

Question 2
Why foreign keys are allowed to have NULL values? Explain with an example.

Answer

A null value can be entered in a foreign key, indicating that the records are not related. In certain situations, a
foreign key may accept a NULL value if it's not a part of the primary key of the foreign table.

For example, consider an Orders table in a database. Each order may or may not be associated with a customer.
If an order is placed by a guest or a new customer who hasn't been added to the system yet, the CustomerID
foreign key in the Orders table can be NULL to indicate that there is no associated customer record for that
order.

Question 3(a)

Differentiate between database state and database schema.

Answer

Database state Database schema

The data stored in database at a particular The database schema defines the design, structure,
moment of time (i.e., the state of the and organization of the database, serving as the
database at a particular instance of time) is blueprint or skeleton that determines how data is
called database state or instance of database. organized and related within the database.

Question 3(b)

Differentiate between primary key and foreign key.

Answer

Primary Key Foreign Key

Primary Key is a column or group of A foreign key is an attribute whose value is derived from
columns in a table that uniquely the primary key of another table. A foreign key is used
identify every row in that table. to represent the relationship between two tables.

Primary key cannot have Null values. Foreign key can have Null values.

There can be only one primary key in


Multiple foreign keys can exist in a table.
a table.

It is used to enforce entity integrity It is used to enforce referential integrity and maintain
and ensure data uniqueness. data consistency across related tables.
Question 3(c)

Differentiate between degree and cardinality of a relation.

Answer

Degree of a relation Cardinality of a relation

The number of attributes in a relation is called The number of tuples in a relation is called
the Degree of the relation. the Cardinality of the relation.

For example, if a relation has attributes like For example, if a relation contains 10 records
Name, Age, and Address, then its degree is 3. or tuples, then its cardinality is 10.

Question 4

Compared to a file system, how does a database management system avoid redundancy in data through a
database?

Answer

A database stores the data at a central location wherefrom all application programs can access data. This
removes the need of saving own data by application program and thus it reduces data redundancy.

Question 5

What are the limitations of file system that can be overcome by a relational DBMS?

Answer

The limitations of file system overcome by a relational DBMS are as follows:

1. Data Redundancy
2. Data Inconsistency
3. Data Isolation
4. Data Dependence
5. Difficulty in data access
6. Controlled data sharing

Question 6

A school has a rule that each student must participate in a sports activity. So each one should give only one
preference for sports activity. Suppose there are five students in a class, each having a unique roll number. The
class representative has prepared a list of sports preferences as shown below. Answer the following:

Table: Sports Preferences


Roll_no Preference

9 Cricket

13 Football

17 Badminton

17 Football

21 Hockey

24 NULL

NULL Kabaddi

1. Roll no 24 may not be interested in sports. Can a NULL value be assigned to that student’s preference
field ?
2. Roll no 17 has given two preferences in sports. Which property of relational DBMS is violated here ?
Can we use any constraint or key in the relational DBMS to check against such violation, if any?
3. Kabaddi was not chosen by any student. Is it possible to have this tuple in the Sports Preferences
relation ?

Answer

1. In a relational database model where each student is required to have exactly one preference for a sports
activity, assigning a NULL value to Roll no 24's preference field is not permitted.
2. The primary key constraint ensures uniqueness in a relational database table. If Roll no 17 has two
sports preferences, it violates this rule because a primary key constraint on "Roll_no" would not allow
different values for the same roll number. By using a primary key constraint on "Roll_no," the relational
database management system (DBMS) can prevent such violations by rejecting attempts to insert rows
with duplicate roll numbers.
3. No, since no student has selected Kabaddi as their preferred sport, there should not be an entry for
Kabaddi in the Sports Preferences table.

Question 7

In another class having 2 sections, the two respective class representatives have prepared 2 separate Sports
Preferences tables, as shown below:

Sports preference of section 1 (arranged on roll number column)

Table: Sports Preferences


Roll_no Sports

9 Cricket

13 Football

17 Badminton

21 Hockey

24 Cricket

Sports preference of section 2 (arranged on Sports name column, and column order is also different)

Table: Sports Preferences

Sports Roll_no

Badminton 17

Cricket 9

Cricket 24

Football 13

Hockey 21

Are the states of both the relations equivalent? Justify.

Answer

Yes, the states of both the relations are equivalent as the order of rows and columns does not matter and data is
just the same in both the relations.

Question 8

The school canteen wants to maintain records of items available in the school canteen and generate bills when
students purchase any item from the canteen. The school wants to create a canteen database to keep track of
items in the canteen and the items purchased by students. Design a database by answering the following
questions:
(a) To store each item name along with its price, what relation should be used? Decide appropriate attribute
names along with their data type. Each item and its price should be stored only once. What restriction should be
used while defining the relation ?

(b) In order to generate bill, we should know the quantity of an item purchased. Should this information be in a
new relation or a part of the previous relation ? If a new relation is required, decide appropriate name and data
type for attributes. Also, identify appropriate primary key and foreign key so that the following two restrictions
are satisfied:

1. The same bill cannot be generated for different orders.


2. Bill can be generated only for available items in the canteen.

(c) The school wants to find out how many calories students intake when they order an item. In which relation
should the attribute 'calories' be stored?

Answer

(a) To store each item name along with its price in the canteen database, we can create a relation (table) called
"Items" with the following attributes:

Items table

Attributes Datatype Constraints

ItemNo Integer Primary Key, Unique, non-null value

ItemName VARCHAR Non-null value

Price Float Non-null value

The restriction that should be used while defining the "Items" relation is to set the "ItemNo" attribute as the
primary key. This ensures that each item number is unique and that each item and its price are stored only once
in the database.

(b) Yes, the item sale information should be stored in a separate relation, say "SaleOrders".

SaleOrders table

Attributes Datatype Constraints

orderno integer Primary Key Unique, Non-null value

ItemNo integer Foreign key,Unique, Non-null value

Quantity integer Non-null value


Attributes Datatype Constraints

Price Float Non-null value

With this design, we satisfy both restrictions:

Each order has a unique OrderNo, ensuring that the same bill cannot be generated for different orders. The
foreign key constraint on ItemNo ensures that bills can only be generated for available items in the canteen.

(c) 'Calories' should be stored in the "Items" table because they are directly associated with specific items.

Question 9

An organisation wants to create a database EMPDEPENDENT to maintain following details about its
employees and their dependent.

EMPLOYEE(AadharNumber, Name, Address, Department,


EmployeeID)
DEPENDENT(EmployeeID, DependentName, Relationship)
(a) Name the attributes of EMPLOYEE, which can be used as candidate keys.

(b) The company wants to retrieve details of dependent of a particular employee. Name the tables and the key
which are required to retrieve this detail.

(c) What is the degree of EMPLOYEE and DEPENDENT relation?

Answer

(a) In the EMPLOYEE table, the attributes AadharNumber and EmployeeID can be used as candidate keys.
This means that either AadharNumber or EmployeeID can uniquely identify each record in the EMPLOYEE
table.

(b) The EMPLOYEE and DEPENDENT tables are linked using the EmployeeID key, which is utilized to
retrieve details of dependents associated with a specific employee.

(c) In the EMPLOYEE relation, there are five attributes, resulting in a degree of 5. Similarly, the DEPENDENT
relation has three attributes, making its degree 3.

Question 10

School uniform is available at M/s Sheetal Private Limited. They have


maintained SCHOOL_UNIFORM Database with two relations viz. UNIFORM and COST. The following
figure shows database schema and its state.

School Uniform Database

Attributes and Constraints

Table: UNIFORM
Attribute UCode UName UColor

Constraints Primary Key Not Null -

Table: COST

Attribute UCode Size Price

Constraints Composite Primary Key >0

Table: UNIFORM

UCode UName UColor

1 Shirt White

2 Pant Grey

3 Skirt Grey

4 Tie Blue

5 Socks Blue

6 Belt Blue

Table: COST

UCode Size COST Price

1 M 500

1 L 580

1 XL 620

2 M 810

2 L 890
UCode Size COST Price

2 XL 940

3 M 770

3 L 830

3 XL 910

4 S 150

4 L 170

5 S 180

5 L 210

6 M 110

6 L 140

6 XL 160

(a) Can they insert the following tuples to the UNIFORM Relation ? Give reasons in support of your answer.

1. 7, Handkerchief, NULL
2. 4, Ribbon, Red
3. 8, NULL, White

(b) Can they insert the following tuples to the COST Relation ? Give reasons in support of your answer.

1. 7, S, 0
2. 9, XL, 100

Answer

(a)

1. Tuple (7, Handkerchief, NULL): This tuple can be inserted because there is no constraint mentioned in the
schema that prohibits NULL values for the UColor attribute.
2. Tuple (4, Ribbon, Red): This tuple can be inserted as all attributes have valid non-null values.

3. Tuple (8, NULL, White): This tuple cannot be inserted because UName attribute cannot be NULL as per the
schema constraints.

(b)

1. Tuple (7, S, 0): This tuple cannot be inserted because the COST Price attribute must be greater than 0 as per
the schema constraints.

2. Tuple (9, XL, 100): This tuple can be inserted as all attributes have valid values and the COST Price is
greater than 0.

Question 11

In a multiplex, movies are screened in different auditoriums. One movie can be shown in more than one
auditorium. In order to maintain the record of movies, the multiplex maintains a relational database consisting
of two relations viz. MOVIE and AUDI respectively as shown below :

Movie(Movie_ID, MovieName, ReleaseDate)


Audi(AudiNo, Movie_ID, Seats, ScreenType, TicketPrice)
(a) Is it correct to assign Movie_ID as the primary key in the MOVIE relation ? If no, then suggest an
appropriate primary key.

(b) Is it correct to assign AudiNo as the primary key in the AUDI relation ? If no, then suggest appropriate
primary key.

(c) Is there any foreign key in any of these relations ?

Answer

(a) Yes, assigning Movie_ID as the primary key in the MOVIE relation is correct because each movie has a
unique Movie_ID.

(b) It is not correct to assign AudiNo as the primary key in the AUDI relation because an AudiNo can be
repeated for different movies screened in different auditoriums. To uniquely identify each record in the AUDI
relation, a composite primary key consisting of AudiNo and Movie_ID should be used.

(c) Yes, there is a foreign key in the AUDI relation. The Movie_ID attribute in the AUDI relation is a foreign
key that references the Movie_ID primary key in the MOVIE relation.

Question 12

For the below given database STUDENT-PROJECT, answer the following:

(a) Name primary key of each table.

(b) Find foreign key(s) in table PROJECT-ASSIGNED.

(c) Is there any alternate key in table STUDENT? Give justification for your answer.

(d) Can a user assign duplicate value to the field RollNo of STUDENT table? Justify.
Student Project Database

Table: STUDENT

Roll No Name Class Section Registration_ID

11 Mohan XI 1 IP-101-15

12 Sohan XI 2 IP-104-15

21 John XII 1 CS-103-14

22 Meena XII 2 CS-101-14

23 Juhi XII 2 CS-101-10

Table: PROJECT

ProjectNo PName SubmissionDate

101 Airline Database 12/01/2018

102 Library Database 12/01/2018

103 Employee Database 15/01/2018

104 Student Database 12/01/2018

105 Inventory Database 15/01/2018

106 Railway Database 15/01/2018

Table: PROJECT ASSIGNED

Registration_ID ProjectNo

IP-101-15 101

IP-104-15 103
Registration_ID ProjectNo

CS-103-14 102

CS-101-14 105

CS-101-10 104

Answer

(a) Primary key of each table:

STUDENT: Roll No.


PROJECT: ProjectNo.
PROJECT ASSIGNED: Registration_ID.

(b) The ProjectNo column in the PROJECT ASSIGNED table is a foreign key that references the ProjectNo
column in the PROJECT table.

(c) In the STUDENT table, the Registration_ID column serves as an alternate key since it uniquely identifies
each student.

(d) No, a user cannot assign a duplicate value to the Roll No field of the STUDENT table because Roll No is
the primary key of the table and it must be unique.

Question 13

For the below given database STUDENT-PROJECT, can we perform the following operations?

(a) Insert a student record with missing roll number value.

(b) Insert a student record with missing registration number value.

(c) Insert a project detail without submission-date.

(d) Insert a record with registration ID IP-101-19 and ProjectNo 206 in table PROJECT-ASSIGNED.

Student Project Database

Table: STUDENT

Roll No Name Class Section Registration_ID

11 Mohan XI 1 IP-101-15

12 Sohan XI 2 IP-104-15
Roll No Name Class Section Registration_ID

21 John XII 1 CS-103-14

22 Meena XII 2 CS-101-14

23 Juhi XII 2 CS-101-10

Table: PROJECT

ProjectNo PName SubmissionDate

101 Airline Database 12/01/2018

102 Library Database 12/01/2018

103 Employee Database 15/01/2018

104 Student Database 12/01/2018

105 Inventory Database 15/01/2018

106 Railway Database 15/01/2018

Table: PROJECT ASSIGNED

Registration_ID ProjectNo

IP-101-15 101

IP-104-15 103

CS-103-14 102

CS-101-14 105

CS-101-10 104

Answer
(a) No. the Roll No attribute in the STUDENT table is marked as primary key and NOT NULL. Therefore,
inserting a student record with a missing Roll No value would violate the NOT NULL constraint and is not
allowed.

(b) Yes, the registration_ID attribute in the STUDENT table does not have a NOT NULL constraint specified in
the schema. Therefore, it is possible to insert a student record without registration number value.

(c) Yes, the SubmissionDate attribute in the PROJECT table does not have a NOT NULL constraint specified
in the schema. Therefore, it is possible to insert a project detail without a SubmissionDate value.

(d) No, we cannot perform this operation. ProjectNo in PROJECT ASSIGNED table serves as a foreign key
that references the primary key in the PROJECT table. Since ProjectNo "206" is not present in the PROJECT
table, it cannot be inserted into the PROJECT ASSIGNED table.

Chapter 9

Structured Query Language (SQL)


Class 12 - NCERT Computer Science Solutions
Exercise

Question 1(a)

Define RDBMS. Name any two RDBMS software.

Answer

An RDBMS is a database management system based on the relational model, storing data in tables of rows and
columns, enabling data retrieval, manipulation, and relationships through SQL queries. Two examples of
RDBMS software are MySQL and Oracle Database.

Question 1(b)

What is the purpose of the following clauses in a select statement?

(i) ORDER BY

(ii) GROUP BY

Answer

(i) ORDER BY clause is used to sort the result set of a SELECT statement either in ascending (default) or
descending order based on one or more columns. The ASC keyword is used for ascending order, and the DESC
keyword is used for descending order.

(ii) GROUP BY clause is used to group rows that have the same values in specified columns into summary
rows. It is commonly used with aggregate functions (e.g., SUM, COUNT, AVG) to perform calculations on
grouped data.

Question 1(c)

Site any two differences between Single Row Functions and Aggregate Functions.

Answer

Two differences between Single Row Functions and Aggregate Functions are:

Single Row Functions Aggregate Functions

Single row functions operate on individual Aggregate functions operate on groups of rows
rows and return a single value per row. and return a single result for each group.

It can be used in SELECT, WHERE, and


It can be used in the SELECT clause only.
ORDER BY clause.
Question 1(d)

What do you understand by Cartesian Product?

Answer

The Cartesian Product is an operation that combines tuples from two relations. It results in all possible pairs of
rows from the two input relations, regardless of whether they have matching values on common attributes. This
operation is denoted by the cross join symbol (×) in SQL.

Question 1(e)

Differentiate between the following statements:

(i) ALTER and UPDATE

(ii) DELETE and DROP

Answer

(i) Differences between ALTER and UPDATE statements:

ALTER statement UPDATE statement

The ALTER statement is used to


modify the structure of database The UPDATE statement is used to modify the existing
objects, such as tables, views, or data in a table.
schemas.

It can be used to add, modify, or drop


It is used to change the values of one or more columns in
columns, constraints, or indexes in a
a table based on specified conditions.
table.

For example: ALTER


TABLE For example: UPDATE
Employees SET
Employees ADD Email Email = '[email protected]'
VARCHAR(255); WHERE EmployeeID = 101;
(ii) Differences between DELETE and DROP statements:

DELETE statement DROP statement

The DELETE statement is used to remove The DROP statement is used to remove entire
one or more rows from a table based on database objects, such as tables, views, indexes,
specified conditions. or schemas, from the database.

It deletes specific rows of data while keeping It deletes the entire object along with its structure
the table structure intact. and data.
DELETE statement DROP statement

For example, DELETE


FROM
Employees WHERE For example, DROP TABLE
Department = Products;
'Marketing';

Question 1(f)

Write the name of the functions to perform the following operations:

1. To display the day like 'Monday', 'Tuesday', from the date when India got independence.
2. To display the specified number of characters from a particular position of the given string.
3. To display the name of the month in which you were born.
4. To display your name in capital letters.

Answer

1. DAYNAME("1947-08-15")
2. SUBSTRING(string, pos, n)
3. MONTHNAME("yyyy-mm-dd")
4. UPPER('YourName')

Question 2

Write the output produced by the following SQL statements:

(a) SELECT POW(2, 3);


(b) SELECT ROUND(342.9234, -1);
(c) SELECT LENGTH("Informatics Practices");
(d) SELECT YEAR("1979/11/26"), MONTH("1979/11/26"),
DAY("1979/11/26"), MONTHNAME("1979/11/26");
(e) SELECT LEFT("INDIA", 3), RIGHT("ComputerScience", 4),
MID("Informatics", 3, 4), SUBSTR("Practices", 3);
Answer

(a)

Output

+-----------+
| POW(2, 3) |
+-----------+
| 8 |
+-----------+
(b)
Output

+---------------------+
| ROUND(342.9234, -1) |
+---------------------+
| 340 |
+---------------------+
(c)

Output

+---------------------------------+
| LENGTH("Informatics Practices") |
+---------------------------------+
| 21 |
+---------------------------------+
(d)

Output

+--------------------+---------------------
+-------------------+-------------------------+
| YEAR("1979/11/26") | MONTH("1979/11/26") |
DAY("1979/11/26") | MONTHNAME("1979/11/26") |
+--------------------+---------------------
+-------------------+-------------------------+
| 1979 | 11 |
26 | November |
+--------------------+---------------------
+-------------------+-------------------------+
(e)

Output

+------------------+-----------------------------
+--------------------------+------------------------+
| LEFT("INDIA", 3) | RIGHT("ComputerScience", 4) |
MID("Informatics", 3, 4) | SUBSTR("Practices", 3) |
+------------------+-----------------------------
+--------------------------+------------------------+
| IND | ence | form
| actices |
+------------------+-----------------------------
+--------------------------+------------------------+

Question 3
Consider the following MOVIE table and write the SQL queries based on it.

MovieI ReleaseDat ProductionCos BusinessCos


MovieName Category
D e t t

001 Hindi_Movie Musical 2018-04-23 124500 130000

002 Tamil_Movie Action 2016-05-17 112000 118000

English_Movi
003 Horror 2017-08-06 245000 360000
e

Bengali_Movi Adventur
004 2017-01-04 72000 100000
e e

005 Telugu_Movie Action - 100000 -

Punjabi_Movi
006 Comedy - 30500 -
e

(a) Display all the information from the Movie table.

(b) List business done by the movies showing only MovieID, MovieName and Total_Earning. Total_Earning to
be calculated as the sum of ProductionCost and BusinessCost.

(c) List the different categories of movies.

(d) Find the net profit of each movie showing its MovieID, MovieName and NetProfit. Net Profit is to be
calculated as the difference between Business Cost and Production Cost.

(e) List MovieID, MovieName and Cost for all movies with ProductionCost greater than 10,000 and less than
1,00,000.

(f) List details of all movies which fall in the category of comedy or action.

(g) List details of all movies which have not been released yet.

Answer

(a)

SELECT * FROM Movie;

Output

+---------+---------------+-----------+-------------
+----------------+--------------+
| MOVIEID | MOVIENAME | CATEGORY | RELEASEDATE |
PRODUCTIONCOST | BUSINESSCOST |
+---------+---------------+-----------+-------------
+----------------+--------------+
| 1 | Hindi_Movie | Musical | 2018-04-23 |
124500 | 130000 |
| 2 | Tamil_Movie | Action | 2016-05-17 |
112000 | 118000 |
| 3 | English_Movie | Horror | 2017-08-06 |
245000 | 360000 |
| 4 | Bengali_Movie | Adventure | 2017-01-04 |
72000 | 100000 |
| 5 | Telugu_Movie | Action | NULL |
100000 | NULL |
| 6 | Punjabi_Movie | Comedy | NULL |
30500 | NULL |
+---------+---------------+-----------+-------------
+----------------+--------------+
(b)

SELECT MovieID, MovieName, (ProductionCost + BusinessCost)


AS Total_Earning
FROM Movie
WHERE ReleaseDate IS NOT NULL;

Output

+---------+---------------+---------------+
| MovieID | MovieName | Total_Earning |
+---------+---------------+---------------+
| 1 | Hindi_Movie | 254500 |
| 2 | Tamil_Movie | 230000 |
| 3 | English_Movie | 605000 |
| 4 | Bengali_Movie | 172000 |
+---------+---------------+---------------+
(c)

SELECT DISTINCT Category FROM MOVIE;

Output

+-----------+
| Category |
+-----------+
| Musical |
| Action |
| Horror |
| Adventure |
| Comedy |
+-----------+
(d)

SELECT MovieID, MovieName, BusinessCost - ProductionCost AS


NetProfit
FROM Movie
WHERE ReleaseDate IS NOT NULL;

Output

+---------+---------------+-----------+
| MovieID | MovieName | NetProfit |
+---------+---------------+-----------+
| 1 | Hindi_Movie | 5500 |
| 2 | Tamil_Movie | 6000 |
| 3 | English_Movie | 115000 |
| 4 | Bengali_Movie | 28000 |
+---------+---------------+-----------+
(e)

SELECT MovieID, MovieName, ProductionCost AS Cost


FROM MOVIE
WHERE ProductionCost > 10000 AND ProductionCost < 100000;

Output

+---------+---------------+-------+
| MovieID | MovieName | Cost |
+---------+---------------+-------+
| 4 | Bengali_Movie | 72000 |
| 6 | Punjabi_Movie | 30500 |
+---------+---------------+-------+
(f)

SELECT * FROM MOVIE


WHERE Category = 'Comedy' OR Category = 'Action';

Output

+---------+---------------+----------+-------------
+----------------+--------------+
| MOVIEID | MOVIENAME | CATEGORY | RELEASEDATE |
PRODUCTIONCOST | BUSINESSCOST |
+---------+---------------+----------+-------------
+----------------+--------------+
| 2 | Tamil_Movie | Action | 2016-05-17 |
112000 | 118000 |
| 5 | Telugu_Movie | Action | NULL |
100000 | NULL |
| 6 | Punjabi_Movie | Comedy | NULL |
30500 | NULL |
+---------+---------------+----------+-------------
+----------------+--------------+
(g)

SELECT * FROM MOVIE


WHERE ReleaseDate IS NULL;

Output

+---------+---------------+----------+-------------
+----------------+--------------+
| MOVIEID | MOVIENAME | CATEGORY | RELEASEDATE |
PRODUCTIONCOST | BUSINESSCOST |
+---------+---------------+----------+-------------
+----------------+--------------+
| 5 | Telugu_Movie | Action | NULL |
100000 | NULL |
| 6 | Punjabi_Movie | Comedy | NULL |
30500 | NULL |
+---------+---------------+----------+-------------
+----------------+--------------+

Question 4

Suppose your school management has decided to conduct cricket matches between students of Class XI and
Class XII. Students of each class are asked to join any one of the four teams – Team Titan, Team Rockers,
Team Magnet and Team Hurricane. During summer vacations, various matches will be conducted between
these teams. Help your sports teacher to do the following:

(a) Create a database "Sports".

(b) Create a table "TEAM" with following considerations:

1. It should have a column TeamID for storing an integer value between 1 to 9, which refers to unique
identification of a team.
2. Each TeamID should have its associated name (TeamName), which should be a string of length not less
than 10 characters.
(c) Using table level constraint, make TeamID as the primary key.

(d) Show the structure of the table TEAM using a SQL statement.

(e) As per the preferences of the students four teams were formed as given below. Insert these four rows in
TEAM table:

Row 1: (1, Team Titan)


Row 2: (2, Team Rockers)
Row 3: (3, Team Magnet)
Row 4: (4, Team Hurricane)

(f) Show the contents of the table TEAM using a DML statement.

(g) Now create another table MATCH_DETAILS and insert data as shown below. Choose appropriate data
types and constraints for each attribute.

Table: MATCH_DETAILS

MatchI MatchDa FirstTeam SecondTeam FirstTeamSc SecondTeamSc


D te ID ID ore ore

2018-07-
M1 1 2 90 86
17

2018-07-
M2 3 4 45 48
18

2018-07-
M3 1 3 78 56
19

2018-07-
M4 2 4 56 67
19

2018-07-
M5 1 4 32 87
18

2018-07-
M6 2 3 67 51
17

Answer

(a)

CREATE DATABASE Sports;


(b)
CREATE TABLE TEAM (
TeamID INT,
TeamName VARCHAR(20));
(c)

ALTER TABLE TEAM


ADD PRIMARY KEY(TeamID);
(d)

DESCRIBE TEAM;

Output

+----------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+----------+------+-----+---------+-------+
| TeamID | int | NO | PRI | NULL | |
| TeamName | char(20) | YES | | NULL | |
+----------+----------+------+-----+---------+-------+
(e)

INSERT INTO TEAM (TeamID, TeamName) VALUES


(1, 'Team Titan'),
(2, 'Team Rockers'),
(3, 'Team Magnet'),
(4, 'Team Hurricane');
(f)

SELECT * FROM TEAM;

Output

+--------+----------------+
| TeamID | TeamName |
+--------+----------------+
| 1 | Team Titan |
| 2 | Team Rockers |
| 3 | Team Magnet |
| 4 | Team Hurricane |
+--------+----------------+
(g)

CREATE TABLE MATCH_DETAILS (


MatchID VARCHAR(10),
MatchDate DATE,
FirstTeamID INT,
SecondTeamID INT,
FirstTeamScore INT,
SecondTeamScore INT,
CONSTRAINT PK_MatchID PRIMARY KEY (MatchID),
);
INSERT INTO MATCH_DETAILS (MatchID, MatchDate, FirstTeamID,
SecondTeamID, FirstTeamScore, SecondTeamScore) VALUES
('M1', '2018-07-17', 1, 2, 90, 86),
('M2', '2018-07-18', 3, 4, 45, 48),
('M3', '2018-07-19', 1, 3, 78, 56),
('M4', '2018-07-19', 2, 4, 56, 67),
('M5', '2018-07-18', 1, 4, 32, 87),
('M6', '2018-07-17', 2, 3, 67, 51);

Output

SELECT * FROM MATCH_DETAILS;


+---------+------------+-------------+--------------
+----------------+-----------------+
| MatchID | MatchDate | FirstTeamID | SecondTeamID |
FirstTeamScore | SecondTeamScore |
+---------+------------+-------------+--------------
+----------------+-----------------+
| M1 | 2018-07-17 | 1 | 2 |
90 | 86 |
| M2 | 2018-07-18 | 3 | 4 |
45 | 48 |
| M3 | 2018-07-19 | 1 | 3 |
78 | 56 |
| M4 | 2018-07-19 | 2 | 4 |
56 | 67 |
| M5 | 2018-07-18 | 1 | 4 |
32 | 87 |
| M6 | 2018-07-17 | 2 | 3 |
67 | 51 |
+---------+------------+-------------+--------------
+----------------+-----------------+

Question 5

Using the sports database containing two relations (TEAM, MATCH_DETAILS) and write the queries for the
following:
(a) Display the MatchID of all those matches where both the teams have scored more than 70.

(b) Display the MatchID of all those matches where FirstTeam has scored less than 70 but SecondTeam has
scored more than 70.

(c) Display the MatchID and date of matches played by Team 1 and won by it.

(d) Display the MatchID of matches played by Team 2 and not won by it.

(e) Change the name of the relation TEAM to T_DATA. Also change the attributes TeamID and TeamName to
T_ID and T_NAME respectively.

Answer

(a)

SELECT MatchID
FROM MATCH_DETAILS
WHERE FirstTeamScore > 70 AND SecondTeamScore > 70;

Output

+---------+
| MatchID |
+---------+
| M1 |
+---------+
(b)

SELECT MatchID
FROM MATCH_DETAILS
WHERE FirstTeamScore < 70 AND SecondTeamScore > 70;

Output

+---------+
| MatchID |
+---------+
| M5 |
+---------+
(c)

SELECT MatchID, MatchDate


FROM MATCH_DETAILS
WHERE FirstTeamID = 1 AND FirstTeamScore > SecondTeamScore;

Output
+---------+------------+
| MatchID | MatchDate |
+---------+------------+
| M1 | 2018-07-17 |
| M3 | 2018-07-19 |
+---------+------------+
(d)

SELECT MatchID
FROM MATCH_DETAILS
WHERE SecondTeamID = 2 AND SecondTeamScore <=
FirstTeamScore;

Output

+---------+
| MatchID |
+---------+
| M1 |
+---------+
(e)

ALTER TABLE TEAM RENAME TO T_DATA;


ALTER TABLE T_DATA CHANGE COLUMN TeamID T_ID int;
ALTER TABLE T_DATA CHANGE COLUMN TeamName T_NAME CHAR(20);

Question 6

A shop called Wonderful Garments who sells school uniforms maintains a database SCHOOLUNIFORM as
shown below. It consisted of two relations - UNIFORM and COST. They made UniformCode as the primary
key for UNIFORM relations. Further, they used UniformCode and Size to be composite keys for COST
relation. By analysing the database schema and database state, specify SQL queries to rectify the following
anomalies.

(a) M/S Wonderful Garments also keeps handkerchiefs of red colour, medium size of Rs. 100 each.

(b) INSERT INTO COST (UCode, Size, Price) values (7, 'M', 100);

When the above query is used to insert data, the values for the handkerchief without entering its details in the
UNIFORM relation is entered. Make a provision so that the data can be entered in the COST table only if it is
already there in the UNIFORM table.

(c) Further, they should be able to assign a new UCode to an item only if it has a valid UName. Write a query to
add appropriate constraints to the SCHOOLUNIFORM database.

(d) Add the constraint so that the price of an item is always greater than zero.

Answer
(b)

ALTER TABLE COST ADD CONSTRAINT fk_uniform_ucode_size


FOREIGN KEY (UCode) REFERENCES UNIFORM (UCode);
(c)

ALTER TABLE UNIFORM ADD CONSTRAINT CK_UName_UCode


CHECK (UName IS NOT NULL);
(d)

ALTER TABLE COST ADD CONSTRAINT CK_Price_Positive CHECK


(Price > 0);

Question 7

Consider the following table named "Product", showing details of products being sold in a grocery shop.

PCode PName UPrice Manufacturer

P01 Washing Powder 120 Surf

P02 Toothpaste 54 Colgate

P03 Soap 25 Lux

P04 Toothpaste 65 Pepsodent

P05 Soap 38 Dove

P06 Shampoo 245 Dove

Write SQL queries for the following:

(a) Create the table Product with appropriate data types and constraints.

(b) Identify the primary key in Product.

(c) List the Product Code, Product name and price in descending order of their product name. If PName is the
same, then display the data in ascending order of price.

(d) Add a new column Discount to the table Product.

(e) Calculate the value of the discount in the table Product as 10 per cent of the UPrice for all those products
where the UPrice is more than 100, otherwise the discount will be 0.
(f) Increase the price by 12 per cent for all the products manufactured by Dove.

(g) Display the total number of products manufactured by each manufacturer.

Write the output(s) produced by executing the following queries on the basis of the information given above in
the table Product:

(h) SELECT PName, avg(UPrice) FROM Product GROUP BY Pname;

(i) SELECT DISTINCT Manufacturer FROM Product;

(j) SELECT COUNT (DISTINCT PName) FROM Product;

(k) SELECT PName, MAX(UPrice), MIN(UPrice) FROM Product GROUP BY PName;

Answer

(a)

CREATE TABLE Product (


PCode VARCHAR(10) PRIMARY KEY,
PName VARCHAR(50),
UPrice int,
Manufacturer VARCHAR(50)
);
(b) The primary key in the table "Product" is PCode.

(c)

SELECT PCode, PName, UPrice


FROM Product
ORDER BY PName DESC, UPrice ASC;

Output

+-------+----------------+--------+
| PCode | PName | UPrice |
+-------+----------------+--------+
| P01 | WASHING POWDER | 120 |
| P02 | TOOTHPASTE | 54 |
| P04 | TOOTHPASTE | 65 |
| P03 | SOAP | 25 |
| P05 | SOAP | 38 |
| P06 | SHAMPOO | 245 |
+-------+----------------+--------+
(d)

ALTER TABLE Product


ADD COLUMN Discount float;
(e)

UPDATE Product
SET Discount = IF(UPrice > 100, (UPrice * (10/100)) +
UPrice, 0);

Output

SELECT * FROM Product;

+-------+----------------+--------+--------------
+----------+
| PCode | PName | UPrice | Manufacturer | Discount
|
+-------+----------------+--------+--------------
+----------+
| P01 | WASHING POWDER | 120 | SURF | 12
|
| P02 | TOOTHPASTE | 54 | COLGATE | 0
|
| P03 | SOAP | 25 | LUX | 0
|
| P04 | TOOTHPASTE | 65 | PEPSODENT | 0
|
| P05 | SOAP | 38 | DOVE | 0
|
| P06 | SHAMPOO | 245 | DOVE | 24.5
|
+-------+----------------+--------+--------------
+----------+
(f)

UPDATE Product
SET UPrice = (UPrice * (12/100)) + UPrice
WHERE Manufacturer = 'Dove';

Output

SELECT * from Product;

+-------+----------------+--------+--------------
+----------+
| PCode | PName | UPrice | Manufacturer | Discount
|
+-------+----------------+--------+--------------
+----------+
| P01 | WASHING POWDER | 120 | SURF | 12
|
| P02 | TOOTHPASTE | 54 | COLGATE | 0
|
| P03 | SOAP | 25 | LUX | 0
|
| P04 | TOOTHPASTE | 65 | PEPSODENT | 0
|
| P05 | SOAP | 43 | DOVE | 0
|
| P06 | SHAMPOO | 274 | DOVE | 24.5
|
+-------+----------------+--------+--------------
+----------+
(g)

SELECT Manufacturer, COUNT(*) AS TotalProducts


FROM Product
GROUP BY Manufacturer;

Output

+--------------+---------------+
| Manufacturer | TotalProducts |
+--------------+---------------+
| SURF | 1 |
| COLGATE | 1 |
| LUX | 1 |
| PEPSODENT | 1 |
| DOVE | 2 |
+--------------+---------------+
(h)

SELECT PName, avg(UPrice) FROM Product GROUP


BY Pname;

Output

+----------------+-------------+
| PName | avg(UPrice) |
+----------------+-------------+
| WASHING POWDER | 120.0000 |
| TOOTHPASTE | 59.5000 |
| SOAP | 34.0000 |
| SHAMPOO | 274.0000 |
+----------------+-------------+
(i)

SELECT DISTINCT Manufacturer FROM Product;

Output

+--------------+
| Manufacturer |
+--------------+
| SURF |
| COLGATE |
| LUX |
| PEPSODENT |
| DOVE |
+--------------+
(j)

SELECT COUNT(DISTINCT PName) FROM Product;

Output

+-----------------------+
| COUNT(DISTINCT PName) |
+-----------------------+
| 4 |
+-----------------------+
(k)

SELECT PName, MAX(UPrice), MIN(UPrice) FROM


Product GROUP BY PName;

Output

+----------------+-------------+-------------+
| PName | MAX(UPrice) | MIN(UPrice) |
+----------------+-------------+-------------+
| WASHING POWDER | 120 | 120 |
| TOOTHPASTE | 65 | 54 |
| SOAP | 43 | 25 |
| SHAMPOO | 274 | 274 |
+----------------+-------------+-------------+
Question 8

Using the CARSHOWROOM database given in the chapter, write the SQL queries for the following:

(a) Add a new column Discount in the INVENTORY table.

(b) Set appropriate discount values for all cars keeping in mind the following:

1. No discount is available on the LXI model.


2. VXI model gives a 10 per cent discount.
3. A 12 per cent discount is given on cars other than LXI model and VXI model.

(c) Display the name of the costliest car with fuel type "Petrol".

(d) Calculate the average discount and total discount available on Baleno cars.

(e) List the total number of cars having no discount.

Answer

Table inventory

CarI CarNam YearManufactu FuelTyp FinalPric


Price Model
d e re e e

582613.0
D001 Dzire LXI 2017 Petrol 652526.6
0

673112.0
D002 Dzire VXI 2018 Petrol 753885.4
0

567031.0 Sigma1.
B001 Baleno 2019 Petrol 635074.7
0 2

647858.0
B002 Baleno Delta1.2 2018 Petrol 725601.0
0

355205.0 5 STR
E001 EECO 2017 CNG 397829.6
0 STD

654914.0
E002 EECO CARE 2018 CNG 733503.7
0

514000.0
S001 SWIFT LXI 2017 Petrol 575680.0
0
CarI CarNam YearManufactu FuelTyp FinalPric
Price Model
d e re e e

614000.0
S002 SWIFT VXI 2018 Petrol 687680.0
0

(a)

ALTER TABLE INVENTORY


ADD COLUMN Discount FLOAT;
(b)

UPDATE INVENTORY
SET Discount = 0
WHERE Model = 'LXI';

UPDATE INVENTORY
SET Discount = Price * 0.10
WHERE Model = 'VXI';

UPDATE INVENTORY
SET Discount = Price * 0.12
WHERE Model NOT IN ('LXI', 'VXI');

Output

+-------+---------+-----------+-----------
+-----------------+----------+------------+----------+
| CarId | CarName | Price | Model | YearManufacture
| FuelType | FinalPrice | Discount |
+-------+---------+-----------+-----------
+-----------------+----------+------------+----------+
| D001 | Dzire | 582613.00 | LXI | 2017
| Petrol | 652526.60 | 0 |
| D002 | Dzire | 673112.00 | VXI | 2018
| Petrol | 753885.40 | 67311.2 |
| B001 | Baleno | 567031.00 | Sigma1.2 | 2019
| Petrol | 635074.70 | 68043.7 |
| B002 | Baleno | 647858.00 | Delta1.2 | 2018
| Petrol | 725601.00 | 77743 |
| E001 | EECO | 355205.00 | 5 STR STD | 2017
| CNG | 397829.60 | 42624.6 |
| E002 | EECO | 654914.00 | CARE | 2018
| CNG | 733503.70 | 78589.7 |
| S001 | SWIFT | 514000.00 | LXI | 2017
| Petrol | 575680.00 | 0 |
| S002 | SWIFT | 614000.00 | VXI | 2018
| Petrol | 687680.00 | 61400 |
+-------+---------+-----------+-----------
+-----------------+----------+------------+----------+
(c)

SELECT CarName
FROM INVENTORY
WHERE FuelType = 'Petrol'
AND Price = (SELECT MAX(Price) FROM INVENTORY WHERE
FuelType = 'Petrol');

Output

+---------+
| CarName |
+---------+
| Dzire |
+---------+
(d)

SELECT AVG(Discount) AS AverageDiscount,


SUM(Discount) AS TotalDiscount
FROM INVENTORY
WHERE CarName = 'Baleno';

Output

+-----------------+----------------+
| AverageDiscount | TotalDiscount |
+-----------------+----------------+
| 72893.33984375 | 145786.6796875 |
+-----------------+----------------+
(e)

SELECT COUNT(*)
FROM INVENTORY
WHERE Discount = 0;

Output

+----------+
| COUNT(*) |
+----------+
| 2 |
+----------+

Chapter 10

Computer Networks
Class 12 - NCERT Computer Science Solutions

Exercise

Question 1

Expand the following:

(a) ARPANET
(b) MAC

(c) ISP

(d) URI

Answer

(a) ARPANET — Advanced Research Project Agency Network

(b) MAC — Media Access Control

(c) ISP — Internet Service Provider

(d) URI — Uniform Resource Indicator

Question 2

What do you understand by the term network?

Answer

A network is an interconnected collection of autonomous computing devices that can share and exchange
information and resources.

Question 3

Mention any two main advantages of using a network of computing devices.

Answer

The two main advantages of using a network of computing devices are as follows:

1. Resource Sharing — Through a network, data, software and hardware resources can be shared
irrespective of the physical location of the resources and the user.

2. Reliability — A file can have its copies on two or more computers of the network, so if one of them is
unavailable, the other copies could be used. That makes a network more reliable.

Question 4

Differentiate between LAN and WAN.

Answer

LAN WAN

LAN stands for Local Area Network. WAN stands for Wide Area Network.

Small computer networks that are confined to a The networks spread across countries or on a
LAN WAN

localized area up to 1km are known as Local very big geographical area are known as Wide
Area Network. Area Network.

It usually costs less to set it up. It costs higher to set it up.

It is usually a single network. It is usually a network of many networks.

LANs facilitate information sharing, enhanced WANs facilitate information sharing and
communication and resource sharing. enhanced communication primarily.

Question 5

Write down the names of few commonly used networking devices.

Answer

A few commonly used networking devices are modem, hub, switch, router etc.

Question 6

Two universities in different States want to transfer information. Which type of network they need to use for
this?

Answer

When two universities located in different states want to transfer information between them, they would use a
Wide Area Network (WAN). WANs are designed to connect devices over long distances, such as between
different cities, states, or countries.

Question 7

Define the term topology. What are the popular network topologies?

Answer

The arrangement of computers and other peripherals in a network is called topology. The popular network
topologies are Mesh, Ring, Bus, Star and Tree.

Question 8

How is tree topology different from bus topology?

Answer
Tree topology is a hierarchical structure where multiple branches can each have one or more basic topologies,
such as ring, bus, or star. In this type of network, data transmitted from the source first reaches the centralized
device, and from there, the data passes through every branch where each branch can have links for more nodes.

In bus topology, each communicating device connects to a transmission medium known as a bus. Data sent
from a node are transmitted along the length of the bus in both directions. As a result, data can be received by
any of the nodes connected to the bus.

Question 9

Identify the type of topology from the following:

(a) Each node is connected with the help of a single cable.

(b) Each node is connected with central switching through independent cables.

Answer

(a) Bus Topology

(b) Star Topology

Question 10

What do you mean by a modem ? Why is it used ?

Answer

A modem is a computer peripheral that allows us to connect and communicate with other computers via
telephone lines. Modem stands for 'Modulator Demodulator'. The modem at the sender’s end acts as a
modulator that converts the digital data into analog signals. The modem at the receiver’s end acts as a
demodulator that converts the analog signals into digital data that the destination node can understand.

Question 11

Explain the following devices:

(a) Switch

(b) Repeater

(c) Router

(d) Gateway

(e) NIC

Answer

(a) Switch — A switch is a networking device that connects various computing/network devices on a computer
network using packet switching to receive and forward data to the destination. When data arrives, the switch
extracts the destination address from the data packet and stores it in a table to determine where to send the
packet. This allows the switch to send signals to only selected devices instead of broadcasting to all devices.
Additionally, a switch can forward multiple packets simultaneously. One of the key features of a switch is that
it does not forward noisy or corrupted signals. Instead, it drops such signals and requests the sender to resend
them.

(b) Repeater — A repeater is a device that amplifies a signal being transmitted on the network. It is used in
long network lines, which exceed the maximum rated distance for a single run. Over distance, the cables
connecting a network lose the signal transmitted. If the signal degrades too much, it fails to reach the
destination. Or if it does arrive, the degradation of the message makes it useless. Repeaters can be installed
along the way to ensure that data packets reach their destination.

(c) Router — A router is a network device that forwards data from one network to another. A router works like
a bridge but can handle different protocols. Based on a network road map called a routing table, routers can
help ensure that packets are travelling the most efficient paths to their destinations. If a link between two
routers fails, the sending router can determine an alternate route to keep traffic moving.

(d) Gateway — A gateway is a network device that connects dissimilar computer networks following different
protocols. The gateways act as entry and exit point for a network as they translate communications from one
network protocol to the other.

(e) NIC — The network interface card (NIC) is a device that is attached to each of the workstations and the
server. It helps the workstation establish the all-important connection with the network and has a unique
number identifying it, known as the node address.

Question 12

Draw a network layout of star topology and bus topology connecting five computers.

Answer

Star Topology

Bus Topology

Question 13

What is the significance of MAC address?


Answer

The MAC (Media Access Control) address is the physical address, which is assigned to the hardware network
card (Network Interface Card), of the host computer and remains fixed. The machine on which the NIC is
attached, can be physically identified on the network using its MAC address. The NIC manufacturer assigns a
MAC address which is a 6 byte address (48 bits) with each byte separated by a colon. The first three bytes (24
bits) of MAC address are the manufacturer-id or the organizational unique identifier (OUI) and the last three
bytes (24 bits) are the card-number.

Question 14

How is IP address different from MAC address? Discuss briefly.

Answer

IP address, also known as Internet Protocol address, is a unique address that can be used to uniquely identify
each node in a network. However, unlike MAC address, IP address can change if a node is removed from one
network and connected to another network. A sample IP address looks like: 192.168.0.178.
The MAC (Media Access Control) address is the physical address, which is assigned to the hardware network
card (Network Interface Card), of the host computer and remains fixed. The machine on which the NIC is
attached, can be physically identified on the network using its MAC address. A sample MAC address looks
like: FC:F8:AE:CE:7B:16.

Question 15

What is DNS ? What is a DNS server ?

Answer

The character based naming system by which servers are identified is known as domain name system (DNS).
DNS helps to translate domain names into IP addresses that computers can understand. It acts as a directory that
matches human-readable domain names to their corresponding numerical IP addresses, allowing users to access
websites without needing to remember or type in the IP addresses directly.
A DNS server is a specialised server responsible for finding the correct IP address for a given domain name.
Domain Name Servers are the phone book of the Internet.

Question 16

Sahil, a class X student, has just started understanding the basics of Internet and web technologies. He is a bit
confused in between the terms "World Wide Web" and "Internet". Help him in understanding both the terms
with the help of suitable examples of each.

Answer

The World Wide Web (WWW) is a set of protocols that allows us to access any document on the Net through a
naming system based on URLs. The WWW also specifies a way, known as the Hypertext Transfer Protocol
(HTTP), to request and send hypermedia documents over the Internet.

The Internet is a worldwide network of computer networks that allows all computers to exchange information
with each other. They follow protocols like TCP/IP (Transmission Control Protocol/Internet Protocol) for
communication.
The WWW is a small part of the Internet. We can say that the Internet is a highway that offers many services
and features, and the WWW is a vehicle (like a truck) that uses this highway to transport information.

Chapter 11

Data Communication
Class 12 - NCERT Computer Science Solutions

Exercise

Question 1

What is data communication? What are the main components of data communication?

Answer

Data communication refers to the exchange of data between two or more networked or connected devices. The
main components of data communication are sender, receiver, communication medium, the message to be
communicated, and certain rules called protocols to be followed during communication.
Question 2

Which communication mode allows communication in both directions simultaneously?

Answer

Full-duplex communication mode allows communication in both directions simultaneously.

Question 3

Among LAN, MAN, and WAN, which has the highest speed and which one can cover the largest area?

Answer

LAN (Local Area Network) offers the highest speed and WAN (Wide Area Network) covers the largest area.

Question 4

What are three categories of wired media ? Explain them.

Answer

The three categories of wired media are as follows :

1. Twisted Pair Cable — A twisted-pair cable consists of two copper wires twisted like a DNA helical
structure. Both the copper wires are insulated with plastic covers. Usually, a number of such pairs are
combined together and covered with a protective outer wrapping. Each of the twisted pairs act as a
single communication link. The use of twisted configuration minimizes the effect of electrical
interference from similar pairs close by. Twisted pairs are less expensive and most commonly used in
telephone lines and LANs. These cables are of two types: Unshielded twisted-pair (UTP) and Shielded
twisted-pair (STP).

2. Co-axial Cable — Coaxial cable has a copper wire at the core of the cable which is surrounded with
insulating material. The insulator is further surrounded with an outer conductor (usually a copper mesh).
This outer conductor is wrapped in a plastic cover. The key to success of coaxial cable is its shielded
design that allows the cable's copper core to transmit data quickly, without interference of
environmental factors. These types of cables are used to carry signals of higher frequencies to a longer
distance.

3. Fiber-Optic Cable — The optical fiber cable carries data as light, which travels inside a thin fiber of
glass. Optic fiber uses refraction to direct the light through the media. A thin transparent strand of glass
at the centre is covered with a layer of less dense glass called cladding. This whole arrangement is
covered with an outer jacket made of PVC or Teflon. Such types of cables are usually used in backbone
networks. These cables are of light weight and have higher bandwidth which means higher data transfer
rate. Signals can travel longer distances and electromagnetic noise cannot affect the cable. However,
optic fibers are expensive and unidirectional. Two cables are required for full duplex communication.

Question 5

Compare wired and wireless media.

Answer
Wired Media Wireless Media

Wired Media is also called as Guided transmission Wireless Media is also called as
media. Unguided transmission media.

In guided transmission, there is a physical link made In unguided transmission, data travels in
of wire/cable through which data in terms of signals air in terms of electromagnetic waves
are propagated between the nodes. using an antenna.

The types of wired media are twisted pair cable, co- The types of wireless media are radio
axial cable, fiber-optic cable. waves, micro waves, infrared waves.

Question 6

Which transmission media carries signals in the form of light?

Answer

Optical Fiber transmission media carries signals in the form of light.

Question 7

List out the advantages and disadvantages of optical fiber cable.

Answer

The advantages of optical fiber cable are as follows :

1. It is immune to electrical and magnetic interference.


2. It is highly suitable for harsh industrial environment.
3. It guarantees secure transmission and has a very high transmission capacity.
4. Fiber optic cables can be used for broadband transmission.

The disadvantages of optical fiber cable are as follows :

1. Connecting either two fibers together or a light source to a fiber is a difficult process.
2. In order to incept the signal, the fiber must be cut and a detector inserted.
3. Light can reach the receiver out of phase.
4. Connection losses are common problems.
5. Fiber optics cables are more difficult to solder.
6. They are the most expensive of all the cables.

Question 8

What is the range of frequency for radio waves?

Answer
The range of frequency for radio waves is between 3 KHz to 1 GHz.

Question 9

18 Gbps is equal to how many Bits per second?

Answer

1 Gbps is equal to 1000000000 bits per second. Therefore, to convert 18 Gbps to bits per second:

18 Gbps = 18 * 1000000000 = 18000000000 bits per second

So, 18 Gbps is equal to 18,000,000,000 bits per second.

Question 10

HTTP stands for?

Answer

HTTP stands for Hyper Text Transfer Protocol.

Question 11

Write short note on the following:

(a) HTTP

(b) Bandwidth

(c) Bluetooth

(d) DNS

(e) Data transfer rate

Answer

(a) HTTP — HTTP stands for HyperText Transfer Protocol, which is the primary protocol used to access the
World Wide Web. It is a request-response protocol (also called client-server) that runs over TCP. HTTP
facilitates access to hypertext from the World Wide Web by defining how information is formatted and
transmitted, and how web servers and browsers should respond to various commands.

For example, whenever we enter the URL http://www.ncert.nic.in in a browser, it sends an


HTTP request to the web server where ncert.nic.in is hosted. The HTTP response from the web
server fetches and sends the requested web page, which is then displayed on the browser.
(b) Bandwidth — Bandwidth of a channel is the range of frequencies available for the transmission of data
through that channel. The higher the bandwidth, the higher the data transfer rate. Bandwidth is calculated as the
difference between the maximum and minimum frequencies contained in the composite signals, and it is
measured in Hertz (Hz).
(c) Bluetooth — Bluetooth is a short-range wireless technology used to connect devices like mobile phones,
mouse, headphones, keyboards, and computers wirelessly over short distances. It enables tasks such as printing
documents with Bluetooth-enabled printers without the need for physical connections. These devices utilize a
low-cost transceiver chip that operates within the unlicensed frequency band of 2.4 GHz for data transmission
and reception. Bluetooth devices can communicate within a range of 10 meters, achieving speeds of 1-2 Mbps.
The technology allows up to 255 devices to form a network, with 8 devices capable of simultaneous
communication while others remain inactive until prompted by the master device.

(d) DNS — DNS, known as the Domain Name System, serves as the phonebook of the Internet. It provides a
character-based naming system for servers, allowing users to access websites using easy-to-remember domain
names like google.com instead of numeric IP addresses such as 8.8.8.8. DNS is essential for internet navigation
as it translates domain names into IP addresses, enabling seamless communication and resource access across
the web.

(e) Data transfer rate — Data transfer rate is the number of bits transmitted between source and destination in
one second. It is also known as bit rate. It is measured in terms of bits per second (bps). The higher units for
data transfer rates are:
1 Kbps = 210 bps = 1024 bps
1 Mbps = 220 bps = 1024 Kbps
1 Gbps = 230 bps = 1024 Mbps
1 Tbps = 240 bps = 1024 Gbps

Question 12

What is protocol in data communication? Explain with an example.

Answer

In data communication, protocol is a set of standard rules that the communicating parties — the sender, the
receiver, and all other intermediate devices need to follow in order to have successful and reliable data
communication.

For example, let's consider the Transmission Control Protocol/Internet Protocol (TCP/IP) suite, which is widely
used for communication over the Internet. TCP/IP defines a set of protocols that govern how data is transmitted
over networks. TCP (Transmission Control Protocol) ensures reliable, ordered, and error-checked delivery of
data packets between devices. IP (Internet Protocol), on the other hand, handles the routing and addressing of
data packets across networks.

When a user sends an email using a client like Outlook or Gmail, TCP/IP protocols come into play. TCP breaks
the email message into packets, adds sequence numbers for reassembly, and ensures each packet arrives
without errors. IP handles the routing of these packets over the Internet to reach the recipient's email server,
where the packets are reassembled and the email is delivered to the recipient. This entire process relies on
adherence to the TCP/IP protocol suite, demonstrating the role of protocols in data communication.

Question 13

A composite signal contains frequencies between 500 MHz and 1GHz. What is the bandwidth of a signal?

Answer

Bandwidth is the difference of maximum and minimum frequency contained in the composite signals.
Bandwidth = Maximum Frequency - Minimum Frequency
Bandwidth = 1000000000 Hz - 500000000 Hz
Bandwidth = 500000000 Hz

Therefore, the bandwidth of the composite signal is 500 MHz.

You might also like