Ncert CS
Ncert CS
Exercise
Question 1(a)
Answer
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.
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)
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)
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
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:
Answer
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)
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
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
Python programming
Question 9
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
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
Output
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
(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)
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)
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
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
Output
Question 4
((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.
( ↑ — top
( Push
↑
((
( Push
↑
2 ..........
+ ..........
3 ..........
(
) Pop
↑
* ..........
((
( Push
↑
4 ..........
/ ..........
2 ..........
(
) Pop
↑
) #Empty Pop
+ ..........
2 #Empty ..........
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 *
Intermediate
Symbol Action Stack
output
3
3 Push
↑
53
5 Push
↑
#Empty
18
1 Push
↑
#Empty
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 *
Intermediate
Symbol Action Stack
output
3 Push 3
53
5 Push
↑
#Empty
1 15
1 Push
↑
4 15
4 Push
↑
#Empty
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
Postfix
Symbol Action Stack
Expression
+ A
+ Push in stack
↑
B AB
*- AB+C
* Higher precedence than (-), hence Push
↑
D AB+CD
End of
Pop all and add to expression #Empty AB+CD*-
expression
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)
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
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
Output
Sorting
Class 12 - NCERT Computer Science Solutions
Exercise
Question 1
Display the partially sorted list after three complete passes of Bubble sort.
Answer
Output
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
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
Output
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.
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.
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]
Output
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.
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)
Output
Searching
Class 12 - NCERT Computer Science Solutions
Exercise
Question 1
Answer
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
0 0 < 10 ? Yes 1 = 8 ? No 1
1 1 < 10 ? Yes -2 = 8 ? No 2
2 2 < 10 ? Yes 32 = 8 ? No 3
index 0 1 2 3 4 5 6 7 8 9
elements 1 -2 32 8 17 19 42 13 0 44
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
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
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
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
if result != -1:
print("The position of key", key, "in the list is",
result)
else:
print("Key", key, "not found in the list.")
Output
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
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
if list1[mid] == key:
return mid
elif key < list1[mid]:
last = mid - 1
else:
first = mid + 1
return -1
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
[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.
if arr[mid] == key:
return mid, comparisons
elif key < arr[mid]:
last = mid - 1
else:
first = mid + 1
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]
original_list.sort()
print("\nSorted List:", original_list)
Output
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]
Write a program that takes as input the following unsorted list of English words:
Answer
if arr[mid] == key:
return mid, comparisons
elif key < arr[mid]:
last = mid - 1
else:
first = mid + 1
original_list.sort()
print("\nSorted List:", original_list)
Output
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
for i in range(0,len(L)):
hashTable[L[i]%10] = L[i]
Output
Question 9
Write a Python program by considering a mapping of list of countries and their capital cities such as:
0 None None
1 UK London
2 None None
3 Cuba Havana
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
def calculate_hash_index(key):
return len(key) - 1
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
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
(b) DBMS creates a file that contains description about the data stored in the database.
(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
(d) NULL
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)
Answer
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)
Answer
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.
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)
Answer
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
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:
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:
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)
Sports Roll_no
Badminton 17
Cricket 9
Cricket 24
Football 13
Hockey 21
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:
(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
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
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.
(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.
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
Table: UNIFORM
Attribute UCode UName UColor
Table: COST
Table: UNIFORM
1 Shirt White
2 Pant Grey
3 Skirt Grey
4 Tie Blue
5 Socks Blue
6 Belt Blue
Table: COST
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 :
(b) Is it correct to assign AudiNo as the primary key in the AUDI relation ? If no, then suggest appropriate
primary key.
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
(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
11 Mohan XI 1 IP-101-15
12 Sohan XI 2 IP-104-15
Table: PROJECT
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
(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?
(d) Insert a record with registration ID IP-101-19 and ProjectNo 206 in table PROJECT-ASSIGNED.
Table: STUDENT
11 Mohan XI 1 IP-101-15
12 Sohan XI 2 IP-104-15
Roll No Name Class Section Registration_ID
Table: PROJECT
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
Question 1(a)
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)
(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 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.
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)
Answer
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
Question 1(f)
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
(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.
English_Movi
003 Horror 2017-08-06 245000 360000
e
Bengali_Movi Adventur
004 2017-01-04 72000 100000
e e
Punjabi_Movi
006 Comedy - 30500 -
e
(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.
(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)
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)
Output
+---------+---------------+---------------+
| MovieID | MovieName | Total_Earning |
+---------+---------------+---------------+
| 1 | Hindi_Movie | 254500 |
| 2 | Tamil_Movie | 230000 |
| 3 | English_Movie | 605000 |
| 4 | Bengali_Movie | 172000 |
+---------+---------------+---------------+
(c)
Output
+-----------+
| Category |
+-----------+
| Musical |
| Action |
| Horror |
| Adventure |
| Comedy |
+-----------+
(d)
Output
+---------+---------------+-----------+
| MovieID | MovieName | NetProfit |
+---------+---------------+-----------+
| 1 | Hindi_Movie | 5500 |
| 2 | Tamil_Movie | 6000 |
| 3 | English_Movie | 115000 |
| 4 | Bengali_Movie | 28000 |
+---------+---------------+-----------+
(e)
Output
+---------+---------------+-------+
| MovieID | MovieName | Cost |
+---------+---------------+-------+
| 4 | Bengali_Movie | 72000 |
| 6 | Punjabi_Movie | 30500 |
+---------+---------------+-------+
(f)
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)
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:
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:
(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
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)
DESCRIBE TEAM;
Output
+----------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+----------+------+-----+---------+-------+
| TeamID | int | NO | PRI | NULL | |
| TeamName | char(20) | YES | | NULL | |
+----------+----------+------+-----+---------+-------+
(e)
Output
+--------+----------------+
| TeamID | TeamName |
+--------+----------------+
| 1 | Team Titan |
| 2 | Team Rockers |
| 3 | Team Magnet |
| 4 | Team Hurricane |
+--------+----------------+
(g)
Output
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)
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)
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)
Question 7
Consider the following table named "Product", showing details of products being sold in a grocery shop.
(a) Create the table Product with appropriate data types and constraints.
(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.
(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.
Write the output(s) produced by executing the following queries on the basis of the information given above in
the table Product:
Answer
(a)
(c)
Output
+-------+----------------+--------+
| PCode | PName | UPrice |
+-------+----------------+--------+
| P01 | WASHING POWDER | 120 |
| P02 | TOOTHPASTE | 54 |
| P04 | TOOTHPASTE | 65 |
| P03 | SOAP | 25 |
| P05 | SOAP | 38 |
| P06 | SHAMPOO | 245 |
+-------+----------------+--------+
(d)
UPDATE Product
SET Discount = IF(UPrice > 100, (UPrice * (10/100)) +
UPrice, 0);
Output
+-------+----------------+--------+--------------
+----------+
| 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
+-------+----------------+--------+--------------
+----------+
| 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)
Output
+--------------+---------------+
| Manufacturer | TotalProducts |
+--------------+---------------+
| SURF | 1 |
| COLGATE | 1 |
| LUX | 1 |
| PEPSODENT | 1 |
| DOVE | 2 |
+--------------+---------------+
(h)
Output
+----------------+-------------+
| PName | avg(UPrice) |
+----------------+-------------+
| WASHING POWDER | 120.0000 |
| TOOTHPASTE | 59.5000 |
| SOAP | 34.0000 |
| SHAMPOO | 274.0000 |
+----------------+-------------+
(i)
Output
+--------------+
| Manufacturer |
+--------------+
| SURF |
| COLGATE |
| LUX |
| PEPSODENT |
| DOVE |
+--------------+
(j)
Output
+-----------------------+
| COUNT(DISTINCT PName) |
+-----------------------+
| 4 |
+-----------------------+
(k)
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:
(b) Set appropriate discount values for all cars keeping in mind the following:
(c) Display the name of the costliest car with fuel type "Petrol".
(d) Calculate the average discount and total discount available on Baleno cars.
Answer
Table inventory
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)
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)
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
(a) ARPANET
(b) MAC
(c) ISP
(d) URI
Answer
Question 2
Answer
A network is an interconnected collection of autonomous computing devices that can share and exchange
information and resources.
Question 3
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
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.
LANs facilitate information sharing, enhanced WANs facilitate information sharing and
communication and resource sharing. enhanced communication primarily.
Question 5
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
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
(b) Each node is connected with central switching through independent cables.
Answer
Question 10
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
(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
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
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
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
Answer
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
Answer
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
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
Answer
Question 7
Answer
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
Answer
The range of frequency for radio waves is between 3 KHz to 1 GHz.
Question 9
Answer
1 Gbps is equal to 1000000000 bits per second. Therefore, to convert 18 Gbps to bits per second:
Question 10
Answer
Question 11
(a) HTTP
(b) Bandwidth
(c) Bluetooth
(d) DNS
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.
(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
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