Thanks to visit codestin.com
Credit goes to www.scribd.com

100% found this document useful (2 votes)
624 views102 pages

Boolean Algebra Qand Answer

The document discusses Boolean algebra and logical operations. It defines K-maps, truth tables, and Boolean algebra. George Boole invented Boolean algebra and identified the concepts of "AND, OR, and NOT" logical operators. Truth tables define all possible variable combinations and their results. Minterms are products of all literals while maxterms are sums of literals. De Morgan's theorems allow transforming between sums and products using logical equivalences.

Uploaded by

vikas_2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
624 views102 pages

Boolean Algebra Qand Answer

The document discusses Boolean algebra and logical operations. It defines K-maps, truth tables, and Boolean algebra. George Boole invented Boolean algebra and identified the concepts of "AND, OR, and NOT" logical operators. Truth tables define all possible variable combinations and their results. Minterms are products of all literals while maxterms are sums of literals. De Morgan's theorems allow transforming between sums and products using logical equivalences.

Uploaded by

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

What is K-map ?

(1 Mark)
(Ans)

A Karnaugh Map is a graphical way of minimizing a boolean expression(Maxterms


orMinterms).
What is a Truth Table ?

(1 Mark)
(Ans)
A Truth Table is a table that gives all possible values of logical variables in all possible
combinations, and their corresponding results.
Who was George Boole ?

(1 Mark)
(Ans)

George Boole, was an Englishman who invented Boolean algebra. His concepts are well
known today in the field of mathematical logic. He gave the operators "And, Or, and Not"
used to connect conditions. His major book on symbolic logic identified the concept of
"Boolean Logic" in "The Mathematical Analysis of Logic" in 1847. He authored "An
Investigation of the Laws of Thought" in 1854. Here he described what the computer
industry now calls cybernetics.
Use NOR gates to represent the boolean expression - (X+Y)(Y+Z)(X+Z) ?

(2 Marks)
(Ans)

Steps are:
a) Derive the simplified POS expression
b) Draw the circuit diagram using NOT, AND and OR gates.
c) Replace NOT, AND and OR gates with NOR gates.
NOR gates are suitable for expressions in POS form.

Give the complement of the following Boolean expressions


a) XY + XY + XY
b) (B+D)(A+C)

(2 Marks)
(Ans)

a)Complement of XY + XY + XY
= (XY + XY + XY)
= (XY) . (XY) . (XY) as (X+Y+Z) = X.Y.Z
= (X + Y) . (X+ Y) . (X + Y) as (X.Y) = X+Y
= (X+Y).(X+Y).(X+Y)
b) Complement of (B+D)(A+C)
= ((B+D)(A+C) )
= (B+D) + (A+C)
= BD + AC

= BD + AC
From the following truth table, give the Canonical Sum_of_Products
expression?
X
Y
Z
F
0
0
0
0
0
0
1
0
0
1
0
1
0
1
1
0
1
0
0
1
1
0
1
0
1
1
0
0
1
1
1
1

(2 Marks)
(Ans)
XYZ + XYZ + XYZ = F
What is a Binary decision ?

(2 Marks)
(Ans)
A binary decision is one that results in either a Yes or a No.
Consider the statements below
a) Is Mumbai an important city of India?
b) Is the train on time?
c) Is the library open?
These can be answered with a yes or no, and are called logical statements. The result, True or False is called truth value.

Convert the given into Canonical SOP form -(A + C).(C + D)

(2 Marks)
(Ans)

Wherever a literal is missing in a term, add (missing literal . negated missing literal)
(A + C).(C + D) = (A + C + DD).(AA + C + D)
= (A+C+D)(A+C+D)(A+C+D)(A+C+D) as (X+YZ)=(X+Y)(X+Z)
= (A+C+D)(A+C+D)(A+C+D)
Convert the given expression into Canonical SOP form -Y.Z + X Y

(2 Marks)
(Ans)
Wherever a literal is missing in a term, multiply it withthe (missing literal+ its negated
missing literal)
YZ + X Y= (X + X)YZ + XY(Z + Z)
= XYZ + XYZ + XYZ + XYZ
= XYZ + XYZ + XYZ
What is a canonical expression ?

(2 Marks)
(Ans)

A Boolean expression that is composed of only Minterms or Maxterms is said to be in


Canonical form.Thus we can have expressions in Canonical Sum_of _Products form or
Canonical Product_of_Sums form.
Prove using the truth table, that, X.(X+Y) = X

(2 Marks)
(Ans)
Truth table is of the x,y,x.(x+y) is given below :-

X+Y

X.(X+Y)

0
0
1
1

0
1
0
1

0
1
1
1

0
0
1
1

The truth table shows the two columns X and X.(X+Y) to be identical.
Hence, X = X.(X+Y)

From the following truth table, give the Canonical Product_of_Sums and
Canonical Sum_of_Products expression?
A
B
C
D
F
0
0
0
0
1
0
0
0
1
0
0
0
1
0
1
0
0
1
1
0
0
1
0
0
0
0
1
0
1
1
0
1
1
0
0
0
1
1
1
1
1
0
0
0
1
1
0
0
1
0
1
0
1
0
1
1
0
1
1
0
1
1
0
0
0
1
1
0
1
1
1
1
1
0
0
1
1
1
1
1

(2 Marks)
(Ans)
Output is given below :A
B
C
D
F
Minterms
Maxterms
0
0
0
0
1
ABCD
0
0
0
1
0
A+B+C+D
0
0
1
0
1
ABCD
0
0
1
1
0
A+B+C+D
0
1
0
0
0
A+B+C+D
0
1
0
1
1
ABCD
0
1
1
0
0
A+B+C+D
0
1
1
1
1
ABCD
1
0
0
0
1
ABCD
1
0
0
1
0
A+B+C+D
1
0
1
0
1
ABCD
1
0
1
1
0
A+B+C+D
1
1
0
0
0
A+B+C+D
1
1
0
1
1
ABCD
1
1
1
0
0
A+B+C+D
1
1
1
1
1
ABCD
Canonical Sum_of_Products expression as sum of minterms
= ABCD + ABCD + ABCD + ABCD + ABCD + ABCD + ABCD + ABCD
Canonical Product_of_Sums expression as sum of maxterms
=(A+B+C+D).( A+B+C+D).( A+B+C+D).( A+B+C+D).( A+B+C+D).( A+B+C+D).
( A+B+C+D).( A+B+C+D).
Define Minterms and Maxterms ?

(2 Marks)

(Ans)
A Minterm is a product of all the literals (inputs) into the system.Each literal may be
with or without the bar (i.e. complemented).
A Maxterm is a sum of all the literals (inputs) into the system.The literals may be with
or without the bar (i.e. complemented).
How is Boolean Algebra different from the regular Algebra that you study in
Mathematics ?

(2 Marks)
(Ans)
In Boolean algebra, 0 and 1 (False and True) are the only values allowed.The meaning
and application of logical addition (+), logical multiplication (.), is very different from
addition and multiplication in ordinary algebra. Other operators like /, * are not used.
The basic postulates on which boolean expressions are based are not applicable in
ordinary algebra.There are certain laws (like Indempotence law and Absorption law) and
theorems that like, De Morgans theorems that apply to boolean algebra.
Define XNOR Gate ?

(2 Marks)
(Ans)
The XNOR Gate is an logically equivalent to an invertor XOR Gate i.e. XOR agte followed up by
a NOT Gate(inventor). The XNOR Gate Produces 1 (high) Output when the input combination
has even number of one 1's.
What Boolean Algebra ?

(2 Marks)
(Ans)

Boolean Algebra is a branch of mathematics, somewhat similar to, but different from
ordinary algebra. It is a system of symbols and operators that apply to logical problems.
It is an algebra in which elements can take only one of two values 0 or 1 that represent
false or true, and are subject to operations based on AND, OR and NOT.
What are logical operations ?

(2 Marks)
(Ans)
Logical operations involve the use of three operators NOT, AND and OR. NOT simple
negates a value. It uses one operand. Example- a) Not True (which means, False as True
and False are the only possible values) b) Knowing English AND French (means someone
who knows both English AND French) c) Knowing English OR French (means someone
who knows either English or French).
Define Tautology and Fallacy ?

(2 Marks)
(Ans)
A Tautology is any logical statement that always results in True. Example, the
statement Malaria is dangerous is always true.
A Fallacy is a statement that always results in False. Example Toxic waste is easy to
store - is always false.
What is the Principle of Duality ?

(2 Marks)
(Ans)

According to the Principle of Duality, the dual of any statement in Boolean algebra is
obtained by interchanging + and . and simultaneously inter-changing 0 and 1 in the
statement. In this way, starting with a boolean expression, we get another boolean
expression.
For example:
(i) The dual of the statement
(x . 1 )(0 + x') = 0 is (x + 0)(1 . x') = 1
(ii) The dual of the statement
(x + y)(y + z) = x.z + y is x.y + y.z = (x + z).y

Why are NAND and NOR called universal gates ?

(2 Marks)
(Ans)

Circuits using NAND and NOR are popular as they are easier to design and therefore
cheaper.Functions of other gates can easily be implemented using NAND and NOR
gates.For this reason they are called universal gates.
Design a circuit with 3 inputs that gives a high output only when the number of
high inputs is even ?

(3 Marks)
(Ans)
Truth Table for 3 inputs, X, Y and Z is X
Y
Z
F
0
0
0
0
0
0
1
0
0
1
0
0
0
1
1
1
1
0
0
0
1
0
1
1
1
1
0
1
1
1
1
0
F = m3 + m5 + m6

Marking the minterms in the Karnaugh map, we get the simplified SOP expression F = XYZ + XYZ + XYZ
State De Morgans Theorems. Prove the first theorem?

(5 Marks)
(Ans)

De Morgans two theorems are:

and

The first theorem says that when the sum(OR) of two variables is inverted, this is the
same as inverting each variable individually and then ANDing these inverted variables.

According to Complementarity Law


(1)

and

(2)
The first of these laws states that when a logical variable (or expression) is added to its
complement, the output is 1.
The second law states that when a logical variable (or expression) is multiplied with its
complement, the output is 0.
Let us assume A = X + Y where A, X and Y are logical variables.
According to the Complimentarity Law,

and

If A = X + Y, then, A= X + Y ,
+ which according to De Morgans first theorem is equal to X.Y So, we will try to prove
that
(X + Y) + X . Y = 1and (X + Y) . X Y = 0
Proving (X + Y) + X . Y = 1

Proving (X + Y).X Y = 0
Thus De Morgans first theorem is proved.

Thus De Morgans first theorem is proved.


Describe the Logical Operators in Boolean Algebra?

(5 Marks)
(Ans)
Mathematical operators like +, -, /, * are used with variables to form algebraic
expressions, like, a + b c*d.

NOT, AND and OR are logical operators used to form logical expressions, like, NOT
French, English AND German, English OR German.
NOT operator
Not French - the only specification is that the person should not be French.
The Venn diagram below shows X as the set of French persons, the rest of the area,
leaving X, represents those other than French, i.e. X. Thus, the bar negates X, or stands
for the complement of X.
X
_
X
1
0

0
1

Truth Table for NOT operator


NOT operates on a single variable hence is a unary operator.
The AND operator
English AND German - our search is narrowed, as we can consider only those who know
English as well as German. The logical AND operator is represented by . and is called
logical multiplication. The Venn diagram shows the rectangle as all the available people,
F is English speakers, H is German speakers and the overlapping part is people who
know both. AND allows us to pick up only from the overlapped part.
X
0
0
1
1

Y
0
1
0
1

X.Y
0
0
0
1

Truth Table for AND operator


The truth table shows that if X and Y both, are 1, the result of X.Y is 1.
The OR operator
English OR German - our search is broadened, as we can consider people who know
English, those who know German, or both. The logical OR operator is represented by +
and is called logical addition. The Venn diagram shows the rectangle as all the available
people, F is English speakers, H is German speakers and the overlapping part is people
who know both. OR allows us to pick up from any of the areas covered by F and H.
Truth Table for OR operator

X
0
0
1
1

Y
0
1
0
1

X+Y
0
1
1
1

The truth table shows that if X or Y is 1, the result of X + Y is 1.

What is a logic gate? Describe the 3 basic logic gates used in digital circuits ?

(5 Marks)
(Ans)
Logic gates are digital circuits constructed from diodes, transistors, and resistors that
produce an output, from some given inputs.
NOT gates-It is also called Inverter.The NOT operation can be performed on a single
input. For example, if the variable A is subjected to the NOT operation, the result x can
be expressed asX = where represents the NOToperation.
The truth table of the NOT operation is as follows:
A

X=

AND gates-The AND gate uses 2 or more inputs to produce asingle output.Theresultant
output 1 occurs only then all of the inputs are 1.
Truth Table for 2 input AND Gate
A

X=A.B

The output A.B can be written as AB, without the . symbol.


OR gates-The OR gate uses 2 or more inputs to produce a single output. The result
produced is 1 when any of the inputs is 1.The result 0 is produced only when all the
input variables are 0.
Truth Table for OR Gate
A

X=A+B

Computer Science[C++] For Class 12


Classes And Objects

What are static data members?

(1 Mark)
(Ans)
Static data members are class variables. Only one copy of the static data member is
maintained and this is shared by all the objects. They are visible only within the class but
their lifetime is the entire program. They can be used in all member functions.
What are static member functions?

(1 Mark)
(Ans)
A static member function is a member function that can access only static data
members. It is called using the class name and not with the object as is the case with
other member functions.
How is struct different from class in C++?

(1 Mark)

(Ans)
Members of a class are private by default while members of a structure are public by
default.
What is a friend function?

(1 Mark)
(Ans)

It is a non member function that can access private data members. However, this goes
against one of the basic principles of the class, that only public member functions can
access private members. Hence friend functions should be sparingly used.
What are objects?

(1 Mark)
(Ans)

An object is an instance of a class. For a class that has been defined, objects can be
created as variables of that class. Each object will have a set of data members defined in
the class.
What is the difference between private and protected members of a class?

(1 Mark)
(Ans)

The only difference is that private members cannot be inherited while protected
members can be.
What is nesting of member functions?

(1 Mark)
(Ans)
When a member function of a class calls another member function, it is known as
nesting of member functions.
How are public members different from private members of a class?

(1 Mark)
(Ans)

Public members can be called in outside functions, using the object. Private members
can be called or used only by other members of the class. Also, public members can be
inherited while private members cannot be.
What is a nested class?

(1 Mark)
(Ans)

A class declared inside another class is a nested class.


What do you understand by the term containership?

(1 Mark)
(Ans)

Containership refers to an object of a class being a member of another class.


When should we make a function inline?

(1 Mark)
(Ans)

Make only small functions inline. It must fulfill certain other conditions - it must not have
a loop, switch or goto if it returns a value, it must not have static variables and must not
be recursive.
What constitutes the public interface of the class?

(1 Mark)
(Ans)

Public members, that can be called in any function (using the object) constitute the
public interface of the class.
Write a statement declaring an array named Bk of 15 objects of class Book.

(1 Mark)
(Ans)
Book Bk[15];

State the advantages and disadvantages of inline functions.

(2 Marks)
(Ans)

In case of inline functions, the function call is replaced by the function code. Thus the
overheads involved in calling the function are avoided and the inline function runs a little
faster. The disadvantage is that if the function is called 10 times, its code will be inserted
in 10 places, making the program longer.
How are member functions different from non member functions?

(2 Marks)
(Ans)
1. Member functions can access private and protected members of the class while non
member functions have access to only public members and that too, through the
objects.
2. Member functions have no scope outside the class while non member functions have
scope outside the class.
How is memory allocated for a class and its objects?

(2 Marks)
(Ans)
The class definition gives the data members and member functions. Based on the class
definition, objects are declared. Each object will have its own set of data members but
there will be one set of functions accessed by all the objects. So, when the class is
defined, memory is allocated for member functions and they are stored there. When
objects are declared, separate memory space is allocated for each object, sufficient to
accommodate all its data members.
Can a member function and a non member function be given the same name?
Support your answer with an explanation.

(2 Marks)
(Ans)
Yes they can.
The scope of a member function is restricted to the class. It may be called by other
members of the class or if called in a non member function, it is linked with an object of
the class.
Non member functions have no such restrictions. If defined globally, they have program
scope and can be called from any function. If defined inside a function, they have scope
local to that function.
Define a class Book with the following specifications :
Private members
book_code
title
author
Price

integer
20 characters
20 characters
integer

Public members
getbook()

function that accepts book details


buybook()

function that accepts no. of copies to buy and displays


total amount to be paid.
Function definitions must be given.

(2 Marks)
(Ans)
class Book{

int book_code;
char title[20];
char author[20];
int Price;
public:
void getbook(){
cout << "nEnter Book Code : ";
cin >> book_code;
cout << "nBook Title : ";
cin.getline(title,20);
cout << "nBook Author : ";
cin.getline(author,20);
cout << "nPrice : ";
cin >> Price;
}
void buybook(){
int c;
cout << "nHow many copies to buy? ";
cin >> c;
cout << "nPay Rs."<< price*c;
}
};

Look at the following code fragment


int a,b;
class A{int x;
float y;
char z;
void initval(void){
x=0;
y=0.0;
z='0';
}
public:
int a;
int b;
void sums(int n){
cout<<"Sum1="<< (x + y)*n;
cout<<"Sum2="<< (a+b)*n;
}
void fn(int i, float j, char k);
};
void A::fn(int i,float j,char k){
x=i;y=j;z=k;
}
A ob;
void disp(void){
int a=210;
cout<< a;
}
Which variables can be accessed by the following functions?
sums(), fn(), disp()

(2 Marks)
(Ans)
sums() can access A::x, A::y, A::z, A::a, A::b, ::a, ::b and passed variable
fn() can access A::x, A::y, A::z, A::a, A::b, ::a, ::b
disp() can access ::a, ::b, local variable a, A::a and A::b through ob.

Define a class to store bank account details of customers based on the


specifications given :
Data members:
Account Number
integer
Name of Account Holder
20 characters
Type of Account
1 character (S - Savings C - Current)
Balance
float
Member Functions :
init() - to give data members initial values
disp() - to display account details
deposit() - to deposit money
draw() - to withdraw money, leaving at least Rs.1000 as balance
All functions must be defined.

(2 Marks)
(Ans)

class AC{ int acc_no;


char name[20];
char type;
float balance;
public:
void init(){
cout<<"nEnter Account No.";
cin>>acc_no;
cout<<"nName of Account Holder : ";
cin.getline(name,20);
cout<<"nType = S or C ";
cin>>type;
type=toupper(type);
cout<<"nBalance : ";
cin>>balance;
}
void disp(){
cout<<"nAccount No."<< acc_no;
cout<<"nName of Account Holder : "<< name;
cout<<"nType = "<< type;
cout<<"nBalance : "<< balance;
}
void deposit(float d){
balance = balance + d;
cout<<"nBalance Updated";
}
void draw(float d){
if(balance - d>=1000)
{ balance=balance-d;
cout<<"nBalance Updated";
}
else

cout<<"Leaves insufficient balance";


}
};

Identify errors in the following code :


class X{int a;
static int b;
public:
void f1(void){
a=10;
b=20;
}
static void f2(void){
cout<< a<< b;
}
};
X ob;
void main(){
ob.f1();
ob.f2();
}

(2 Marks)
(Ans)
Function f2() is a static member function. It is accessing a, which is a non static data
member. Secondly, static data member b is not defined outside the class.
How does a class implement Data Hiding, Data Abstraction and Encapsulation?

(3 Marks)
(Ans)

A class binds together data and functions that access it thus enforcing encapsulation.
The class represents essential features of the object, thus implementing data
abstraction.
In the class, members are classified as private, protected and public. Accessibility of the
members depends on which category they are under. Private and protected members
can only be accessed by public members of the class, thus enforcing data hiding.
Describe the access specifiers of a class in brief.

(3 Marks)
(Ans)
There are three access specifiers - private, protected and public.
Members declared as private or protected can only be accessed by other members of the
class. They are thus hidden from the outside world.
Members declared as public can be accessed even outside the class, in non-member
functions, but only by using an object of the class.
A dining hall can accommodate only 50 guests. Define a class to store seat
number and name of the guests who are seated on first come first seated basis.
Define functions to display details of any seat number and to display the
current seating situation. Write a program to show the working of this class.

(3 Marks)
(Ans)

#include < iostream.h>


#include < ctype.h>
class DH{int seat;
char name[20];
static int taken;
public:
void getdata(){

taken++;
cout<<"nSeat Number = "<< taken;
cout<<"nName = ";
cin.getline(name,20);
seat=taken;
}
static void status(){
cout<<"nTotal Seats = 50";
cout<<"nSeats Taken = "<< taken;
cout<<"n Available = "<< 50-taken;
}
void disp( ){
cout<<"nSeat No. = "<< seat;
cout<<"nName = "<< name;
}
};
DH ob[50];
int DH::taken;
void main(){
int i,s;
char mo='Y',c;
When can a function not be inline?

(4 Marks)
(Ans)
Some situations where defining a function as inline will not work
1. If the function returns a value and contains a loop, switch or goto statement.
2. If the function does not return a value and contains a return statement.
3. If the function contains static variables.
4. If the function is recursive.

Constructors And Destructors


What is a constructor ?

(1 Mark)
(Ans)
A constructor is a member function of a class that is invoked automatically when an
object of that class is created. It has the same name as the class and initializes the
object with legal initial values.
What purpose does a constructor serve?

(1 Mark)
(Ans)
The constructor provides some valid initial values to the object created.
What is a default constructor?

(1 Mark)
(Ans)
A constructor that does not accept any argument is a default constructor.
Example: for a class called STUDENT, the following is the default constructorSTUDENT( ) {rno=0;}
What are parameterized constructors?

(1 Mark)
(Ans)
A constructor that takes arguments is a parameterized constructor.
Example :
class ABC{
int a;
int b;
public:

ABC( int x, int y){a=x; b=y;} // parameterizes constructor


..
};
void main(){
ABC ob2(2,3); // parameterized constructor invoked
..
}
What is a temporary instance?

(1 Mark)
(Ans)
A temporary instance of a class is an unnamed object which is short lived. It remains in
memory as long as the statement defining it is executed and then is automatically
destroyed.

What is meant by the term copy initialization?

(1 Mark)
(Ans)
Initializing objects through the copy constructor is called copy initialization.
In the example, for a class ABC, the statement below creates object ob2 initialized with
the object ob.
ABC ob2(ob); // copy constructor called
What are destructors?

(1 Mark)
(Ans)

Destructors are special member functions that are invoked automatically when an object
is to be destroyed. The name of the destructor is the same as the class, preceded by a ~
character.
How is the constructor different from other member functions?

(1 Mark)
(Ans)

The constructor is a special function of the class. It stands out in many ways. Firstly, it is
the one invoked automatically when the object is created.It has the same name as the
class. It cannot return a value. It cannot be inherited. It cannot be static. If no
constructor has been defined for a class, the compiler creates one. Other member
functions do not have these features.
Explain constructor overloading with the help of examples.

(2 Marks)
(Ans)
Overloaded function refer to the same function performing different activities depending on the values passed to
it. Constructor too is a function, and it can be overloaded. Multiple constructors can be defined and different
number and types of values can be sent for initialization. Example :
class A{
int a;
int b;
public:
A ( ) {a=0; b=0;} //default constructor
A( int x, int y){a=x;b=y;}//constructor with 2 arguments
A(int x){a=x; b=2*x;} //constructor with 1 arguments
};
void main(){
A ob; // will invoke the default constructor
A ob2(2,3); // constructor with two arguments invoked
A ob3(6); // constructor with one arguments invoked
}
What are copy constructors?

(2 Marks)
(Ans)
The Copy Constructor is used to initialize an object using another object. It has the form
classname (classname & ).
Why is the object passed by reference to a copy constructor?

(2 Marks)
(Ans)

This is because, when an argument is passed by value, its copy is made. To make a copy
of an object, the copy constructor is called. Thus, it calls itself again. In fact, it calls itself
over and over again until the compiler is out of memory. So, the object is passed by
reference which creates no copies.
What will be the order of invocation of constructors for the following code?
class X{};
class Y { .. };
class Z { ..
public:
Z ( );
X ox;
Y oy;
};
void main() {
X x1;
Y y1;
Z z1;
}

(2 Marks)
(Ans)

The order of invocation will be


1. X :: X( ) for x1
2. Y :: Y( ) for y1
3. X :: X( ) for ox in z1
4. Y :: Y( ) for oy in z1
5. Z :: Z( ) for z1

What is meant by dynamic initialization of objects?

(2 Marks)
(Ans)
Dynamic initialization means that initial values for the object may be provided at
runtime. In the example, values to be passed as arguments are received at run time.
class ABC { int a;
int b;
public:
ABC( int x, int y) { a=x; b=y; }
..
};
void main( ){
int x, y;
cout<<Enter integer values for x and y ;
cin>>x>>y;
ABC ob ( x, y);

}
Why are destructors needed?

(2 Marks)

(Ans)
An object created in a program must be destroyed when it is no more needed. This task
is carried out by the destructor. It deinitializes the object and deallocates all allocated
resources.

How are the two statements given below different?


Shape s1(10,5);
//statement 1
Shape s1 = Shape(10,5);
// statement 2

(2 Marks)
(Ans)
In both the statements, an object, s1 is created. In statement 1, the constructor is called
implicitly. In statement 2, the constructor is called explicitly, by name.

How many times is the copy constructor called in the following code, using
class A :
A func(A x){
A y(x);
A z = y;
return z;
}

void main( ) {
A a;
A b = func(a);
A c = func(b);

(2 Marks)
(Ans)
The copy constructor is called 8 times.
1. object a passed by value to func( )
2. object y initialized in func ( ) with x
3. object z initialized in func ( ) with y
4. object z returned
5. object b passed by value to func( )
6. object y initialized in func ( ) with x
7. object z initialized in func ( ) with y
8. object z returned

Class Prod has been defined. The statement below gives an error, what could
be the reason?
Prod ob;
//error generated!

(2 Marks)
(Ans)
Assuming this statement is in an outside function, if the constructor is defined under
private or protected , the statement will generate an error. Another reason could be, if
the constructor is under public but the destructor has been defined under private or
protected.
What conditions must a function satisfy in order to create objects of a class?

(2 Marks)
(Ans)

A function can create objects of a class if it can access the constructor and destructor.

When the compiler can provide a constructor, why should we define it?

(2 Marks)
(Ans)

The compiler provides its own values, which are legal. When we define the constructor,
we can provide values according to our requirement.
Use an example and show how a constructor with default values works like the
default constructor.

(3 Marks)
(Ans)

The default constructor takes no arguments. However, the class can have a constructor with
default arguments too. In case values are not provided while creating the object, the constructor with default
values can provide values.
In the example below, we see how the constructor with default arguments can work just like the default
constructorclass ABC{
int a;
int b;
public:
void show(){
cout<<"A = "<< a<<"B = "<< b;
}
ABC( ){a=123;b=345; } //default constructor
ABC(int x=55, int y=88){a=x; b=y;} // constructor with default arguments.
};
void main(){
ABC ob; //default constructor called ? or one with default arguments?
ob.show();
}
Here, the object ob is being created and no arguments are passed, so the default
constructor should be invoked. However, the constructor with default values can also be
called as it provides values for missing arguments. In this example, to create object ob,
both default and the constructor with default values can be called. This is actually an
ambiguous situation and should be avoided.

Describe the two ways the constructor can be called.

(3 Marks)
(Ans)
The constructor may be called implicitly or explicitly.
Implicit Call to the Constructor here, the constructor is not called by name but is
invoked automatically. It initializes the object with the passed values.
Example : for a class named INFO, the statement below will implicitly call the
constructor.
INFO X(12,A);
Explicit Call to the Constructor here, the constructor is called by name to initialize
the object with the passed values.
Example : for a class named INFO, the statement below will explicitly call the
constructor.
INFO Y=INFO(12,A);
Here, the object created is Y and the constructor is explicitly called to initialize it with the
values 12 and A.
How will it affect the objects when the constructor is declared under private?
under public?

(3 Marks)
(Ans)

The constructor obeys all access rules. When declared under private, it will be available

to other members of the class only. Thus, member functions can declare objects. The
same also applies to friend functions as they can also access private members of a class.
When they are declared under public, they can be accessed in outside functions too.
Hence, objects can be declared in outside functions when the constructor can be
accessed.

What are the situations when a copy constructor is called?

(3 Marks)
(Ans)
1. When an object is created and initialized with another object, as shown in the
example below,
INFO Y(X);
Here, class is INFO, Y is the object being created and X is the object being used to
initialize it.
2. When an object is passed by value to a function.
func(ob); - function call, an object being passed
3. When a function returns an object.
ABC func2( ); - prototype of a function that returns an object of class ABC
ob = func2( );- function call
What are the main characteristics of destructors?

(3 Marks)
(Ans)

Destructors too are special member functions. Their characteristics are


1. They have the same name as the class, preceded by the ~ character (tilde).
2. They are invoked automatically when objects are destroyed.
3. No return type is specified for destructors
4. Destructors obey the access rules.
5. They cannot be static.
6. They cannot be inherited.
7. Arguments cannot be passed to a destructor.
8. It is not possible to take the address of a destructor.
9. An object cannot be member of a union if the class has a destructor.
10. Member functions can be called from inside the destructor.
11. The compiler creates default destructors wherever needed.
12. If the class has a destructor, the objects are de-initialized before they go out of
scope.
State the important characteristics of constructors?

(4 Marks)
(Ans)
Constructors are special member functions. Their characteristics are
1. They have the same name as the class.
2. They are invoked automatically when objects are created.
3. No return type is specified for constructors
4. Constructors obey the access rules. Only functions that have access to the constructor can create objects of
that class. So, if the constructor is private or protected, it is available only to members or friends. If it is
public, it can be used in outside functions.
5. They cannot be static.
6. They cannot be inherited but the derived class can call the base class constructor.
7. They can have default arguments.
8. It is not possible to take the address of a constructor.
9. An object cannot be member of a union if the class has a constructor.
10. Member functions can be called from inside the constructor.
11. The compiler creates default constructor and copy constructor wherever needed.
12. If the class has a constructor, the objects are initialized before use.
13.. Normally the constructor is called implicitly but it can be called explicitly too.

Inheritance: Extending Classes


What is inheritance ?

(1 Mark)
(Ans)

Inheritance is an important concept of Object Oriented Programming. It is the capability


of one class to inherit properties from another class.
What is the advantage of inheritance?

(1 Mark)
(Ans)
One of the main advantages is code reusability. Once a class has been satisfactorily
defined, it can be used in other classes without making changes. It represents real world
entities very effectively class Personcan have features that can be inherited by
Employee as well as Student.
What do you understand by base class and derived class (or sub class) ?

(1 Mark)
(Ans)

An existing class can be used to derive a new class. The existing class, whose properties
are inherited is the base class and the class that inherits features is the derived class.
A class inherits a function that has the same name and arguments as one of its
own member functions. The object calls the function and there is no scope
resolution operator given. Which of these two functions will be called?

(1 Mark)
(Ans)
The member function of its own class will be called.
Which members are not inherited even if they are public members of a class?

(1 Mark)
(Ans)
The Constructor and Destructor are not inherited.
What is Abstract Class?

(1 Mark)
(Ans)

When a class is used only to derive other classes it is an abstract class. No objects are
created for this class. In the example below, A is an abstract class.
class A
{ .
public :
int a;
};
class B : public A // inherit public member a from A
{ .
public :
int b;
};

void main( ){
B ob1;

}
What is the difference between private and protected members?

(1 Mark)
(Ans)

Private members are not inherited but can be indirectly accessed in the derived class by
inherited members of the same class. Protected members can be inherited and accessed
just like other protected members of the derived class.
Name the different forms of Inheritance.

(2 Marks)
(Ans)

The different forms of inheritance are Single, Multiple, Hierarchical, Multilevel and
Hybrid.

(Q.) What do you understand by visibility modes?


(2 Marks)
(Ans)
Visibility modes are used to specify how the features of the base class are inherited into
the derived class. The three visibility modes are public private and protected. The
inheritable base class members are placed under the access specifiers in the derived
class depending on the visibility mode and its own access specifier.

Can private members be inherited? If yes, how. If no, how can they be
accessed in the derived class?

(2 Marks)
(Ans)

Private members cannot be inherited. However, other member functions that access the
private members can be inherited. Thus, private members can be indirectly accessed
through inherited functions.

(Q.) What is Containership? How is it different from Inheritance?


(2 Marks)
(Ans)

When a class contains an object of another class as a member, it is a case of


containership. Containership is very different from Inheritance. In Inheritance, we have a
class that has its own features in addition to some features of another class. Through
Containership we can create an object that contains an object within it.

(Q.) Private members cannot be inherited. What can be done to make these
members inheritable?

(2 Marks)
(Ans)
To inherit private members we have to change their accessibility i.e. either make them
public members or make them protected members.

Public members are readily inherited and can be accessed by all outside functions too.
This may eliminate the advantages of data hiding.
Making them into protected members will allow them to be inherited while retaining the
feature of security.
The visibility mode under which they are derived decides whether they can be inherited
further. So, under public or protected visibility mode they can be inherited further but
under private visibility mode, they will again become private members.

(Q.) What is a Nested Class? How is it different from Inheritance?


(2 Marks)
(Ans)
When a class is defined inside another class, it is a nested class. This is different from
Inheritance. Members of the nested class can access its other members and object of the
nested class can access its public members. Similarly, members of the outside class can
access other members and the object can access public members. We cannot say that
members of one class become members of another class. Public members of the nested
class can still only be called by its objects. If they were inherited, objects of the derived
class would be able to call them too.
What is meant by virtual base class?

(2 Marks)
(Ans)
When a class inherits from multiple base classes, it can lead to an ambiguous situation. This
is specially when the base classes themselves are derived from a common base class
As shown in the figure, A is a base class from which two classes are derived, B and C.
These further act as base classes for D.

Let us now try to visualize the problem that can arise. D wants to access a function
which is inherited from base class A, into B and C. Obviously, since D is inheriting from
both B and C, it receives two copies of the members they inherited from their base class
A.

When this member is accessed, the compiler faces an ambiguous situation, which can be
resolved in two ways.
One way out is to call the member with the class name i.e. B :: member or C :: member
so that it is clear which member is being accessed.
The other way is to make the common base class (here, A) virtual, as shown in the
example below.
class A
{ .
public :
int a;
};
class B : public virtual A
{ .
public :
int b;
};
class C : public virtual A
{ .
public :
int c;
};
class D : public B, public C
{ .
public :
int c;
};
Now, because of the keyword virtual, classes B and C will share a single common base
class member a. Thus there will be no ambiguity when accessing it.

Class A inherits from Class B. Define a constructor for class A that takes 3
integer arguments, passes on two of these to the base class constructor and
initializes its own member x with the third one.

(2 Marks)
(Ans)

class A : public B{ int x;


..
public:
A( int a, int b, int c) : B(a, b)
{ x = c; }
..
};
What is the difference between the two derived classes below ?
a) class S1 : private P
b) class S2 : public P

(2 Marks)
(Ans)

In the first statement, class P is inherited in private mode. Thus inheritable public and
protected members of P become private members of S1. Private members can be
accessed only by other members or friends of the class, not by the objects.
In the second statement, class P is inherited in public mode. Thus inheritable public and
protected members of P become members of S2, with the same accessibility. Protected
members can be accessed only by other members but the public members will be
accessible by the objects.
How do visibility mode and access specifier determine the access of inherited
members?

(3 Marks)
(Ans)
The visibility mode specifies whether features of the base class are derived publicly, privately
or in protected mode. This controls the access specifiers of the inherited members in the
derived class.
Public visibility mode Inheritable public members of base class become public members
of the derived class and protected members of base class become protected members of
the derived class. Private members are not inherited.

Protected visibility mode - Inheritable public members and protected members of base
class become protected members of the derived class. Private members are not
inherited.

Private visibility mode - Inheritable public members and protected members of base

class become private members of the derived class. Private members are not inherited.

Describe the different forms of Inheritance in brief.

(3 Marks)
(Ans)
The different forms of inheritance are
Single When a subclass inherits from only one base class.

The syntax in single inheritance is


class derived_class_name : visibility_mode base_class_name
{
. // members of the derived class
}
Multiple - When a subclass inherits from multiple base classes.

The syntax in multiple inheritance is


class derived_class_name : visibility_mode base_class_name1, visibility_mode
base_class_name2 [,visibility_mode base_class_name1, ]
{
. // members of the derived class
}
Multilevel - When a subclass inherits from a class which inherits from another class.

The general form of multilevel inheritance is


class derived_class_name1 : visibility_mode base_class_name
{
. // members of the derived class
}
class derived_class_name2 : visibility_mode derived_class_name1
{
. // members of the derived class
}
Hierarchical - When many subclasses inherit from one base class.

The general form of inheritance is


class derived_class_name : visibility_mode base_class_name
{
. // members of the derived class
}
Hybrid A combination of 2 or more forms, like when a subclass inherits from multiple
base classes and the base classes inherit from a single base class.
[E K/-]

How are constructors and destructors handled in derived classes?

(3 Marks)
(Ans)
As you know, constructors and destructors are not inherited. A derived class has its own
members along with inherited members. An object of the derived class will have its own
data members and it will be built upon the data members inherited from the base class.
To create an object, the constructor must be called.
If the base class has a constructor that accepts arguments (i.e. parameterized
constructor) then the derived class should have a constructor that passes the arguments
to the base class constructor. If the base class has only default constructors, then the
derived class need not have a constructor.
The example below shows single inheritance in private visibility mode, where the base
class constructor takes an argument. The derived class has a constructor that invokes
the base class constructor and passes on the value to it.
#include < iostream.h >
class P{ //base class P
int a;
public:
P(int x){ a=x; // constructor takes 1 argument
cout<<"a = "<< a;
}
void getdat(){
cout<<"a = ";
cin>>a;
}
void dispdat(){
cout<< a;
}
};
class E : private P{ //derived class E

int c;
public:
E(int x, int y) : P(x) //constructor invokes base class constructor
{ c=y; }
void getdata(){
cout<<"c = ";
cin>>c;
getdat();
}
void dispdata(){
cout<< c ;
dispdat();
}
};
void main()
{
E e(12,34);
e.getdata();
e.dispdata();
}
Remember, to create an object, first the constructor of the base class and then the
constructor of the derived class will be called.
When an object is destroyed, first the derived class destructor is invoked and then the
base class destructor.

Look at the following class class A{


public :
int h;
int b;
};
Using A as base class, derive two classes, Rectangle and Triangle. Both of
these should have a function calcarea() that calculates and displays the area of
the rectangle or triangle, respectively. Define parameterized constructors to
initialize the values of height and base.

(3 Marks)
(Ans)
#include < iostream.h>
class A{
public :
int h;
int b;

};
class Rectangle : public A
{
public:
Rectangle(int x, int y){
h = x;
b = y;
}
void calcarea(){
int a=h * b;
cout<<"Area of the rectangle = "<< a;
}
};
class Triangle : public A
{
public:
Triangle(int x, int y){
h = x;
b = y;
}
void calcarea(){
float a=(h * b)*0.5;
cout<<"Area of the Triangle = "<< a;
}
};
void main(){
Triangle ot(11,9);

Rectangle or(12,8);
ot.calcarea();
or.calcarea();
}
What are the errors in the given code?
#include < iostream.h>
class A{
int a1;
protected :

//line1
//line2
//line3

//line4

int a2;

//line5

public :

//line6

int a3;

//line7

};

//line8

class B : public A
{

//line9
//line10

public:
void func(){

//line11
//line12

int b1,b2,b3;

//line13

b1=a1;

//line14

b2=a2;

//line15

b3=a3;

//line16

//line17

};

//line18

class C : A
{

//line19
//line20

public:
void func(){

//line21
//line22

int c1,c2,c3;

//line23

c1=a1;

//line24

c2=a2;

//line25

c3=a3;

//line26

//line27

};

//line28
//line29

void main(){
int x,y,z;

//line30
//line31

B ob;

//line32

x=ob.a1;

//line33

y=ob.a2;

//line34

z=ob.a3;

//line35

C oc;

//line36

x=oc.a1;

//line37

y=oc.a2;

//line38

z=oc.a3;

//line39

//line40

(3 Marks)
(Ans)
a) Line 14, a1 is a private member of A, so cannot be accessed
b) Line 24, a1 is a private member of A, so cannot be accessed
c) Line 33, a1 is a private member of A, so cannot be accessed
d) Line 34, a2 is a protected member of B, so cannot be accessed
e) Line 37, a1 is a private member of A, so cannot be accessed
f) Line 38, a2 is a private member of C, so cannot be accessed
g) Line 39, a3 is a private member of C, so cannot be accessed

Look at the code below and answer the questions that follow.
class Vehicle{
int maxspeed;

protected :
int maxseats;
public :
void getdat(int, int);
void dispdat();
};
class Heavy : protected Vehicle
{

int mileage;
protected :
int load;
public:
void getd(int, int);
void dispd();

};
class Van : private Heavy
{
int weight;
public:
void getdata(int);
void dispdata();
};

a)
b)
c)
d)

Name the base class and derived class names for class Heavy.
Which functions can be accessed by dispdata()?
Which functions can be accessed by objects of class Heavy?
Which functions can be accessed by objects of class Van?

(4 Marks)
(Ans)
a) Base class is Vehicle and derived class is Van for class Heavy
b) Function dispdata() can access getdata(), getd(), dispd(), getdat() and dispdat()

c) Objects of class Heavy can access getd() and dispd()


d) Objects of class Van can access getdata() and dispdata()

Look at the code below and answer the questions that follow.
class A{
void afun();
protected : int a1,a2;
public : void getA();
void dispA();
};
class H : protected A{
int h1,h2;
protected : int h3,h4;

void getH();
public:
void dispH();
};
class V : public H
{
int v1;
protected :
int v2;
void getV(int);
public:
void dispV();
};

a)
b)
c)
d)

Name the base class and derived class names for class H.
Name all protected members of class V.
Which data members can be accessed by function getV()?
Which functions can be accessed by objects of class V?

(4 Marks)
(Ans)
a) Base class is A and derived class is V for class H
b) Protected members are v2, getV(), h3,h4, getH(), a1, a2, getA(), dispA()
c) Function getV() can access v1, v2, h3, h4, a1,a2
d) Objects of class V can access dispV() and dispH()

Create a base class Building that stores the number of floors and the number of
rooms the building has. From this, derive a class Flats that stores the number
of bathrooms and open terraces. From Building, derive another class Offices
that stores the number of Fire Exits.

(4 Marks)
(Ans)
#include< iostream.h >
class Building{
int floors;
int rooms;
public:
void getd(){
cout<<"nNo. of Floors = ";
cin>>floors;
cout<<"nNo. of Rooms = ";
cin>>rooms;
}
void dispd(){
cout<<"nNo. of Floors = "<< floors;
cout<<"nNo. of Rooms = "<< rooms;
}
};
class Flats : public Building{
int baths;
int terraces;
public :
void getdat(){
getd();
cout<<"nNo. of Bathrooms = ";
cin>>baths;
cout<<"nNo. of Terraces = ";
cin>>terraces;
}
void dispdat(){
dispd();
cout<<"nNo. of Bathrooms = "<< baths;
cout<<"nNo. of Terraces = "<< terraces;
}
};
class Offices : public Building{
int firexits;
public :
void getdata(){
getd();
cout<<"nNo. of Fire Exits = ";
cin>>firexits;
}
void dispdata(){
dispd();

cout<<"nNo. of Fire Exits = "<< firexits;


}
};
void main(){
Flats of;
Offices oo;
of.getdat();
of.dispdat();
oo.getdata();
oo.dispdata();
}

Data File Handling


What is meant by stream?

(1 Mark)
(Ans)

A stream is a sequence of bytes, or, flow of data. It acts as an interface between the file
and program.
Which classes are used for file input and output operations?

(1 Mark)
(Ans)
The classes used are ifstream, ofstream and fstream.
Name any two functions used in file input-output error handling.

(1 Mark)
(Ans)
int bad() and int fail() are used for error handling.
Why should we check for end of file?

(1 Mark)
(Ans)
We check for end of file to prevent attempts to read in case the file has ended.
How are text files different from binary files?

(2 Marks)
(Ans)
Text files are also called ASCII files. They stores information in the form of ASCII
characters. There are 128 different ASCII codes. Also, text files contain lines of text and
each of these has an end-of-line (EOL) marker automatically appended whenever you
indicate that you have reached the end of a line. When a file is opened in text mode,
various character translations take place. In case of binary files, information is stored in
the same format in which it is stored in the memory. No character translation takes place
when a binary file is opened, because of which binary files can be read and written faster
by the computer.
How is get() different from getline() ?

(2 Marks)
(Ans)

Both get() and getline() can read characters from the input stream into an array till the
specified number of characters are entered or till the delimiting character is
encountered( n by default). The difference is that, in case of getline() this character is
removed from the input stream but get() leaves it in the input stream.
How is the file mode ios::ate different from ios::app?

(2 Marks)
(Ans)
When a file is opened in the mode ios::ate or ios::app , the file pointer is positioned at

the end of the file. With ios::app we can add data only at the end of the file, but with
ios::ate, we can write anywhere in the file.
Describe two member functions from fstream class.

(2 Marks)
(Ans)

Some member functions of fstream class are seekp(), seekg(), tellg() and tellp().
Functions seekg() and tellg() are used with the input stream. Common forms of these
functions are
a) ifstream & seekg(long);
b) ifstream & seekg(long, pos) ;
c) long tellg();
In form a) seekg() positions the get pointer at an absolute position given by the long
integer.
In form b) seekg() positions the get pointer at a position given by the long integer and
by the value of pos.
pos can be - ios :: beg // from beginning of file
ios :: cur // from current position
ios :: end // from the end
In form c) tellg() gives the byte position of the get pointer in the file as a long integer.

How is get() different from read()?

(2 Marks)
(Ans)

Function get() reads one character at a time but read() can read chunks like structures
and objects at one go.

When should the file mode ios::nocreate be used?

(2 Marks)
(Ans)
Normally, in a program, when we give a file name to be opened, it is available. If it is not
there and the program is going to output data to the file, it gets created by the given
name. At times, if the file is not there, we dont want it created in situations like this
we use ios :: nocreate.
What are the two ways of opening a file?

(2 Marks)
(Ans)
A file can be opened in two ways
a) Using the constructor of the stream class this method is useful when only one file is used in the stream.
Constructors of the stream classes ifstream, ofstream and fstream are used to initialize the file stream object with
the file name.
For example, to open a file Names.Dat for reading i.e. input, we create a stream object of class ifstream and pass
on the filename to it, as
ifstream read_file(Names.Dat);
b) Using the function open() - this method is useful when we want to use different files in the stream. If two or
more files are to be processed simultaneously, separate streams must be declared for each.
ifstream ifl; //input stream ifl created
ifl.open(Names.Dat); // file Names.Dat linked with ifl
Now, using ifl, the file can be read.
When we open a file using function open(), along with the filename we can also give the file mode. The general
form of the function open() with two arguments is

stream_object. open(filename, filemode);


If the file mode is not given, the defaults are assumed. If ifstream is used, the default
mode is ios :: in. If ofsream is used, the default mode is ios :: out. fstream does not
provide a mode by default and so we have to specify the mode when we use the function
open ().
Explain using an example how we check for end of file.

(2 Marks)
(Ans)

The function eof() is used to detect end of file. It returns a non zero value when end of
file is reached. Another way to check for end of file is whether the stream object returns
zero or not. It returns zero when the end of file is reached.
ifstream fin;
fin.open(Items.Dat, ios::in|ios::binary);
while(fin) //as long as it is non zero
{ fin.read((char *)& I, sizeof(ITEM));
..
}
The value in fin becomes zero when the end of file is reached, and the loop ends. Since
reading occurs inside the loop, there will be no more attempts to read the file.

What is the difference between ifstream and ofstream classes?

(2 Marks)
(Ans)

Both ifstream and ofstream are derived from class fstreambase. Class ifstream is used to
create an input stream to read data from the file and contains functions for reading data
from the file.Class ofstream is used to create an output stream to write data to the file
and contains functions for writing to the file.
What is the difference between sequential and random access?

(2 Marks)
(Ans)
In sequential files, records are stored one after the other in sequence. To read any
record, all the preceding records must be read. In case of random access, the read
operation takes place exactly where the record to be accessed is. To calculate the exact
address in memory, a key field is transformed into the relative address.
Describe the streams used for input and output with a file.

(3 Marks)
(Ans)
There are 3 kinds of streams input, output and input-output.
If we want to use the file for input i.e. reading, we must create an input stream, using class ifstream. For
example, ifstream ifl;
If we want to use the file for output i.e. writing, we must create an output stream, using class ofstream. For
example, ofstream ofl;
If we want to use the file for input as well as output, we must create a stream
performing both input and output, using class fstream. For example, fstream iofl;

Describe the different file opening modes, in brief.

(3 Marks)
(Ans)
File mode describes how the file is to be used. When we open a file using function open(), along with the
filename we can also give the file mode. The general form of the function open() with two arguments is
stream_object. open(filename, filemode);
The different file modes are

ios :: in to open the file for reading


ios :: out to open the file for writing. If the file exists, its contents are discarded.
ios :: app to append output at the end of the file
ios :: ate to go to end of file on opening, input / output can be anywhere within the file
ios :: trunk to delete the contents of the file
ios :: binary to open a file in binary mode. Default is text mode.
ios :: nocreate if the file does not already exist, it will not be created, open() will fail
ios :: noreplace if the file already exists, it will not be used, open() will fail
If the file mode is not given, the defaults are assumed. If ifstream is used, the default
mode is ios :: in. If ofsream is used, the default mode is ios :: out. fstream does not
provide a mode by default and so we have to specify the mode when we use the function
open (). File modes can be combined using the bitwise Or operator (the | symbol).

Given a structure Member, as below, open the file MEMLIST.DAT that already
stores data of Member, and add a record at the end.
struct Member{
int code;
char name[20];
int age;
char sex;
};

(3 Marks)
(Ans)

#include < fstream.h>


struct Member{
int code;
char name[20];
int age;
char sex;
};
void main(){
Member m;
char c;
ofstream ofl;
ofl.open("MEMLIST.DAT", ios::app|ios::binary);
cout<<"nMember Code : ";
cin>>m.code;
c=cin.get();
cout<<"nMember Name : ";
cin.getline(m.name,20);
cout<<"nAge : ";
cin>>m.age;
c=cin.get();
cout<<"nMember Sex (M/F) : ";
cin>>m.sex;
ofl.write((char*)&m,sizeof(Member));
ofl.close();
}

Write a program that opens a file named CLASS.DAT and displays the number of
characters in it.

(3 Marks)
(Ans)
#include < fstream.h>
void main(){
int num=0;
char c;
ifstream ifl;
ifl.open("CLASS.DAT",ios::in);
while(ifl){
ifl.get(c);
cout<< c;
num++;
cout<< num;
}
ifl.close();
cout<<"Total characters = "<< num;
}
Write a program to use the class Book declared in the previous question and
the file Books.Dat. Display all the data in the file.

(3 Marks)
(Ans)

#include < fstream.h>


#include < string.h>
class Book{
int bookcode;
char bookname[20];
public:
void getdat(){
cout<<"nBook Code : ";
cin>>bookcode;
char c=cin.get();
cout<<"nBook Name : ";
cin.getline(bookname,20);
}
void dispdat(){
cout<<"nBook Code : "<< bookcode;
cout<<"nBook Name : "<< bookname;
}
int match(int cd){
if(cd==bookcode)
return 1;
else
return 0;
}
};
void main(){
Book b;
ifstream ifl;
ifl.open("Books.dat",ios::in|ios::binary);
if(!ifl) {
cout<<"Unable to open file - Returning";
return;}
while(ifl){
ifl.read((char *)&b,sizeof(Book));
b.dispdat();
}

Consider class Employee in the previous question. Accept the filename again
and display all the data in it.

(3 Marks)
(Ans)

#include < fstream.h>


class Employee{
int empcode;
char empname[20];
char depart[20];
public:
void getdat(){
cout<<"nEmployee Code : ";
cin>>empcode;
char c=cin.get();
cout<<"nEmployee Name : ";
cin.getline(empname,20);
cout<<"nDepartment : ";
cin.getline(depart,20);
}
void dispdat(){
cout<<"nEmployee Code : "<< empcode;
cout<<"nEmployee Name : "<< empname;
cout<<"nDepartment : "<< depart;
}
};
void main(){
Employee e;
int num=0;
char fname[13];
cout<<"Enter file name ";
cin>>fname;
ifstream ifl;
ifl.open(fname, ios::in|ios::binary);
if(!ifl){
cout<<"Cannot open file "<< fname;
return;
}
while(ifl) {
ifl.read((char*)&e,sizeof(Employee));
e.dispdat();
}
ifl.close();
}

Describe how the two file pointers can be manipulated.

(4 Marks)
(Ans)

The two file pointers are the get pointer and the put pointer. The get pointer is used with
a file that is open for input and put pointer is used with a file open for output. A file is
read from the position marked by the get pointer. In the same way, when a file is
written, it is at the position marked by the put pointer.

These two pointers can be manipulated to move directly to a location in the file to read
or write. The functions used for this are seekg() and seekp(). Two more functions may
be useful here, tellg() and tellp(). Function tellg() gives the position of the get pointer in
the file and tellp() gives the position of the put pointer in the file.
Suppose the file TEST.DAT is open for input, linked with the input stream ifl.
ifl.seekg(50); // will move the get pointer to byte number 50 in the file.
ifl.seekg(25, ios::beg); // will move the get pointer to the 25th byte from the beginning of the file
ifl.seekg(-5, ios::end); // will move the get pointer back 5 bytes from the end of the file
ifl.seekg(12, ios::cur); // will move the get pointer to the 12th byte from the current position
long p=ifl.tellg(); // store position of get pointer in p
ifl.seekg(p,ios::beg); // move get pointer p bytes from the beginning
Suppose the file TEST.DAT is now open for output, linked with the output stream ofl.
ofl.seekp(50); //will move the put pointer to byte number 50 in the file.
ofl.seekp(25, ios::beg); // will move the put pointer to the 25th byte from the beginning of the file
ofl.seekp(-5, ios::end); // will move the put pointer back 5 bytes from the end of file
ofl.seekp(12, ios::cur); // will move the put pointer to the 12th byte from the current position
long p=ofl.tellp(); // store position of put pointer in p
ofl.seekp(p,ios::beg); // move put pointer p bytes from the beginning

Write a program to use the structure Member, as below, open the file
MEMLIST.DAT that already stores data of Member, and display the details of a
member whose code is given.
struct Member{
int code;
char name[20];
int age;
char sex;
};

(4 Marks)
(Ans)
#include < fstream.h>
#include < string.h>
struct Member{
int code;
char name[20];
int age;
char sex;
};
void main(){
Member m;
char c;
int cd;
ifstream ifl;
ifl.open("MEMLIST.DAT", ios::in|ios::binary);
cout<<"Enter code to find ";
cin>>cd;
c=cin.get();
while(ifl){
ifl.read((char *)&m,sizeof(Member));
if(cd==m.code){
cout<<"nMember Code : "<< m.code;

cout<<"nMember Name : "<< m.name;


cout<<"nAge : "<< m.age;
cout<<"nMember Sex : "<< m.sex;
break;
}
}
ifl.close();

Write a program to create a class Book that stores the book code and name.
Define functions necessary to accept data, display data and check for
matching. Open the data file Books.Dat and delete the record where book code
matches the entered code.

(4 Marks)
(Ans)
#include < fstream.h>
#include < stdio.h>
class Book{
int bookcode;
char bookname[20];
public:
void getdat(){
cout<<"nBook Code : ";
cin>>bookcode;
char c=cin.get();
cout<<"nBook Name : ";
cin.getline(bookname,20);
}
void dispdat(){
cout<<"nBook Code : "<< bookcode;
cout<<"nBook Name : "<< bookname;
}
int match(int cd){
if(cd==bookcode)
return 1;
else
return 0;
}
};
void main(){
Book b;
int cd;
int found=0;
ofstream ofl;
ofl.open("temp.tmp", ios::out|ios::binary);
ifstream ifl;
ifl.open("Books.dat",ios::in|ios::binary);
cout<<"nEnter Book Code ";
cin>>cd;
while(ifl){
ifl.read((char *)&b,sizeof(Book));
found=b.match(cd);
if(found==0)
ofl.write((char *)&b,sizeof(Book));
}
ifl.close();

ofl.close();
remove("Books.Dat");
rename("temp.tmp", "Books.Dat");

Consider class Employee with data members empcode, empname and depart.
Define necessary functions to accept and display data. Write a program to
accept data for different employees and write to the file whose name is
provided by the user.

(4 Marks)
(Ans)
#include < fstream.h>
class Employee{
int empcode;
char empname[20];
char depart[20];
public:
void getdat(){
cout<<"nEmployee Code : ";
cin>>empcode;
char c=cin.get();
cout<<"nEmployee Name : ";
cin.getline(empname,20);
cout<<"nDepartment : ";
cin.getline(depart,20);
}
void dispdat(){
cout<<"nEmployee Code : "<< empcode;
cout<<"nEmployee Name : "<< empname;
cout<<"nDepartment : "<< depart;
}
};
void main(){
Employee e;
int num=0;
char fname[13];
cout<<"Enter file name ";
cin>>fname;
ofstream ofl;
ofl.open(fname, ios::app|ios::binary);
if(!ofl){
cout<<"Cannot open file "<< fname;
return;
}
cout<<"How many employees? ";
cin>>num;
for(int i=1;i<=num;i++){
e.getdat();
ofl.write((char*)&e,sizeof(Employee));
}
ofl.close();
}

Pointers

What are pointers?

(1 Mark)
(Ans)
Pointers are variables that store memory addresses.

How are pointers different from reference variables?

(1 Mark)
(Ans)
A reference variable is an alias or another name for an existing variable while a pointer is
a variable that stores an address. The reference does not occupy memory space but a
pointer does. The declaration too is different
int a;// variable named a
int &alsoa = a; // reference alsoa created, is an alias for a;
int *pa; // pointer pa created
pa=&a;// address of a stored in pa
The value at the address in the pointer is accessed using the * operator, called
dereferencing. In case of references, there is no such need, they directly give the value.
What is Free Store ?

(1 Mark)
(Ans)
Free Store is also called Heap. It is unallocated memory that is used during program
execution. Memory that is dynamically allocated from this free store is unnamed and is
manipulated through the address i.e. pointers.
How is addition carried out with pointers?

(1 Mark)
(Ans)
Every pointer has a base data type. It holds the address of variables of that data type.
When 1 is added to a pointer, the size of the data type is added to it. Suppose pointer pa
holds the address of integer variable a, as 1001. Adding 1 to pa will give 1003. This is
because the size of int is 2.
Suppose pf is a pointer that holds the address of float variable f, as 2300. Adding 3 to pf
will add 3 times the size of float i.e. 12, to the address in pf, making it 2312.
Write statements to display the address of a float type variable named rate.

(1 Mark)
(Ans)

float rate;
float *fp;
fp = &rate;
cout<< fp;
Give the prototype of a function named funstring that returns a string and takes
a string as argument, using pointers.

(1 Mark)
(Ans)

char * funstring(char *);


Explain, using an example, how objects can be passed to a function as
reference and how a function can return reference to an object.

(2 Marks)
(Ans)
#include< iostream.h>
class Emp{
int code;
public :
void getdat(int x){code=x;}
void dispdat(){cout<< "code = "<< code;}
};
Emp& func(int x, Emp& Em){

Em.getdat(x);
cout<< "Value passed";
return Em;
}
void main(){
Emp e1, e2;
e2.getdat(3);
func(5,e1) = e2; //function call
e1.dispdat();
e2.dispdat();
}
In this program an integer and an object as reference, are passed to function func().
Reference to the object is returned by the function. The function call places the function
on the left side of the = sign. The returned variable is assigned the object e2. When the
objects are displayed, e1 and e2 both have the same output.

How is the memory organized when a program is executed?

(2 Marks)
(Ans)
Four logically separate areas are created after a C++ program is compiled.
One area holds all the program statements that are to be executed i.e. the compiled
program code.
The next area holds all the global variables being used.
The third area, also called Stack, stores all local variables, arguments passed to
functions and the return address when functions are called.
The fourth area, called Heap or Free Store, is free memory which is dynamically
allocated during program execution.

How is static memory allocation different from dynamic memory?

(2 Marks)
(Ans)

Static Memory Allocation : when memory to be allocated is known beforehand, it is


allocated during compilation. Generally in a program, variables are declared along with
data type and arrays are declared with size and memory is allocated accordingly.
Dynamic Memory Allocation : when the amount of memory required is not known
beforehand, it is allocated while the program is running, and is known as dynamic
memory allocation. Two operators are used - new and delete. Memory for allocation at
runtime is obtained from the free store or heap.
How is the operator new used? Explain with examples.

(2 Marks)
(Ans)

The new operator allocates memory dynamically and returns a pointer that stores the
address of the location where memory has been allocated. The general form of allocating
is :
pointer_variable_name = new data_type;
Here, data type can be any valid data type, including structures and classes. Bytes are
allocated according to the data type and the address is stored in the pointer variable of
the same data type.
For example : int *pa;
pa = new int;
*pa=12; // 12 is stored at the address in pa
Here, 2 bytes will be allocated for an integer which will be accessed through the address
in pointer pa.
The allocated memory can be initialized at the time of allocation itself,

char *pc;
pc = new char(A);
The above statement allocates memory for a char type value and stores A in it. The
address is stored in pointer pc.
To dynamically allocate memory for a 1-D array,
pointer_variable_name = new data_type[size];
where size is number of elements in a 1-D array.
int *A= new int[10];
will allocate memory for a 10 element integer array whose address is in A. Now, array
elements can be referred as A[0], A[1], A [2] and so on.
To dynamically allocate memory for a 2-D array,
pointer_variable_name = new data_type[rows * columns];
where rows is the number of rows and columns the number of columns in the array.

Why is the operator delete used?

(2 Marks)
(Ans)
The delete operator frees (de-allocates) the memory pointed to by the pointer.
The memory allocated using new remains allocated until it is freed using the delete
operator. If the allocated memory is not de-allocated, then with every run of the program
the amount of available memory decreases. The general form of using the delete
operator is,
delete pointer_variable_name;
delete pa; // frees memory pointed to by pa
delete [10] A;// frees memory allocated to array A, array size is optional
delete [ ] X;// frees memory allocated for array X
How are * and & used with pointers?

(2 Marks)
(Ans)
The * is also called the indirection operator and & is also called address of operator.
When a pointer is declared, the * is used :- int *pa;
When an address is to be stored the & is used :- pa = &a;
When the value at the address in the pointer is to be accessed (i.e. dereferenced), the
* is used, as in, cout<<*pa;
How are arrays and pointers related?

(2 Marks)
(Ans)
The name of an array is regarded as a pointer. It holds the address of the first element
of the array. Consider the statements below int A[10] = {1,2,3,4,5,6,7,8,9,10};
A is the array name, it holds the address of the first element A[0].
cout<< A; //displays the address of the first element
cout<< *A; //displays value at that address i.e. 1
cout<< A+1; //displays another address
cout<< *(A+1); //displays value at that address i.e. 2
As you can see, A behaves just like a pointer.
Describe an array of pointers.

(2 Marks)
(Ans)
An array of pointers is an array, each element of which is a pointer.
An array of integer pointers would be declared as int *N[5];
Now, each of the array elements, N[0], N[1], N[2], N[3] and N[4] would hold the
address of an integer variable. Look at the statements below
int a = 12;
int b = 23;

int c = 34;
int d = 45;
int e = 56;
N[0] = &a;
N[1] = &b;
N[2] = &c;
N[3] = &d;
N[4] = &e;
The two following statements would give the same output.
cout<< a;
cout<< *N[0];
Lets look at another example using a string.
char N[]=Discover Wildlife;
cout<< N;
cout<< *N;
cout<< *(N+1);
Output of these lines: Discover WildlifeDi
(code contd.)
char *p=N;
cout<< p;
cout<< *p;
cout<< *(p+1);
Output of these lines: Discover WildlifeDi
Again, the array name behaves exactly like the pointer.

What is the difference between constant pointers and pointers to constants?

(2 Marks)
(Ans)

A constant pointer means that the address in it cannot be changed.


int a=12; // integer variable with value 12
int *pa = &a;// pointer pa stores address of a
++pa; // increment (address in) pa
int *const cpa=&a; // constant pointer named cpa stores address of a
++cpa; //error, constant pointer cannot be changed
A pointer to a constant means that the pointer holds the address of a constant.
const int cnum=23; // constant cnum declared
const int *pcnum = &cnum; // pointer to a constant stores address of cnum
++cnum; // Error, cnum is a constant
++pcnum; // increment address in pcnum

How is passing references to a function different from passing pointers?

(2 Marks)
(Ans)

In both the cases, the original data changes after the function call.
When reference is passed, the prototype is something like
void func1(int &, int &);
The actual parameters are simply given new names and accessed through them. The
function call is the same as the call when function is called by value.
When pointers are passed, the prototype is something like void func2(int *, int *);
When the function is called, addresses are passed. These addresses are stored in pointer
variables by the function and the data at these addresses is accessed.

What are self referential structure?

(2 Marks)
(Ans)

A structure that has a member that refers to the structure itself is known as a self
referential structure.
Example struct guest{
int tel;
char name[20];
guest *next; // pointer to type guest
};
Here, structure guest is a self referential structure. It has a member, next, which stores
the address of guest type.
What is a dynamic structure?

(2 Marks)
(Ans)
Once a structure has been defined, variables, including pointers can be declared for it. When memory is
allocated dynamically for a structure, it is called a dynamic structure.
Example
struct A{
int a;
char b;
};
A v1,*v2;
v2=new A;
Remember, variables created using new must be deleted when no longer needed, by
delete.
Give an example to show a function returning a pointer to an object.

(2 Marks)
(Ans)

#include< iostream.h>
class Emp{
int code;
public :
void getdat(int x){code=x;}
void dispdat(){cout<< "code = "<< code;}
};
Emp* func(int x, Emp &Em){
Emp *p;
Em.getdat(x);
cout<< "Value passed";
p = &Em;
return p;
}
void main(){
Emp e1, e2;
Emp *ep;
e2.getdat(3);
ep = func(5,e1); // function call
e1.dispdat();
e2.dispdat();
ep->dispdat();
}
Pointer p is assigned the address of the object in the function func(), and returned.
When the function dispdat() is called with the pointer, the arrow operator is used.

Show how pointers to structure can be passed to a function.

(2 Marks)
(Ans)

#include< iostream.h>
struct item{

int code;

int price;
};
item* func(item *ptr){
cin>>ptr->code;
cin>>ptr->price;
return ptr;
}
void main(){
item i1,*pi;
pi = func(&i1); // function call
cout<< "from Pointer "<< pi->code<< pi->price;
cout<< "from variable "<< i1.code<< i1.price;
}
Here, i1 is a structure variable and pi is a pointer. Address of i1 is passed to the function
that accepts values and returns a pointer.
What is the this pointer?

(2 Marks)
(Ans)

The member functions of a class exist at one place in memory and are used by all the
objects. When an object calls a function, the function is automatically passed a pointer to
that object. Thus, the function has the address of the object and can use its data. This
pointer is called the this pointer.
Example
#include< iostream.h>
class stu{
int rno;
int marks;
public:
stu(int a, int b){
rno=a;
marks=b;
}
void disp(stu s){
cout<< this->rno;
cout<< this->marks;
cout<< "nPassed Object";
cout<< s.rno;
cout<< s.marks;
}
};
void main(){
stu s1(10,100);
stu s2(11,98);
s2.disp(s1);
}
The output of this program clearly shows that s2 is the object associated with this when
s2 calls the member function. As this is a pointer, it uses the arrow operator -> and
not the dot . operator to access members.

What is the difference between int *p1 = new int(12);


and
int *p2 = new int [12];

(2 Marks)
(Ans)
In statement - int *p1 = new int(12);
Bytes are allocated in memory, to store an integer and initialized to 12, the address of
this memory location is stored in pointer p1.
In statement - int *p2 = new int [12];
Bytes are allocated in memory for a 12 element integer array. The address of this
memory location is stored in pointer p2. Now, p2 can be used just like the array name.
What is the difference between A[3] and *(A + 3)?

(2 Marks)
(Ans)

A[3] refers to the value in array A with index number 3.


*(A + 3) refers to the value at the address A + 3.
In both the cases here, the same element is accessed.

When A is an array , the expression A++ is invalid. Why?

(2 Marks)
(Ans)

A is the address where the system has placed the array and it will stay here till the end
of the program. As it is the base address of the array, it is a constant and cannot be
changed. However, we can declare a pointer and assign A to it. Now, the pointer variable
can be incremented if required.
int A[]={1,2,3,4,5};
int *p;
p=A;
++p;

What is pointer to void?

(2 Marks)
(Ans)
Normally when we declare a pointer, we give it a type which is the same as the type of
the variable whose address it will store. i.e. int *ptr; will create pointer ptr which will
hold addresses of integer variables.
Pointer to void is like a general purpose pointer that can store address of any data type.
It is used only in certain situations.To declare a pointer to void, give the statement - void
* ptr;
What is memory leak? What causes it? How can it be avoided?

(3 Marks)
(Ans)

When memory is allocated dynamically using the new operator, it remains occupied
even when the program is over. Such occupied memory blocks are known as orphaned
memory blocks . Gradually, as the number of such blocks increases, there is less
memory available to the program which affects its working. This situation is called
Memory Leak.
Some reasons for memory leak are there is no delete in the program to free dynamically allocated memory
the statement with delete is bypassed in certain situations

new assigns the value to a pointer which already holds an address


Memory leak can be avoided by
always freeing the dynamically allocated memory
assigning the address passed by new to a fresh pointer.

Write a function that accepts a string as argument, removes all blanks from it
and returns it.

(4 Marks)
(Ans)
#include< iostream.h>
void main(){
char A[80];
char *str;
char* funblank(char*); // function prototype
cout<< "Enter string ";
cin.getline(A,80);
str=funblank(A); // function call
cout<< A<< endl;
cout<< str<< endl;
}
char* funblank(char* t){
char *tmp;int i=0;
while(*t !=''){
if(*t!=' '){
tmp[i]=*t;
++i;
}
++t;
}
tmp[i]='';
return tmp;
}

Write a function that accepts a string as argument, removes all blanks from it
and returns it.

(4 Marks)
(Ans)

#include< iostream.h>
void main(){
char A[80];
char *str;
char* funblank(char*); // function prototype
cout<< "Enter string ";
cin.getline(A,80);
str=funblank(A); // function call
cout<< A<< endl;
cout<< str<< endl;
}
char* funblank(char* t){
char *tmp;int i=0;
while(*t !=''){
if(*t!=' '){
tmp[i]=*t;
++i;

}
++t;
}
tmp[i]='';
return tmp;
}

Write a program to store 5 names in an array of pointers, named list, and then
reverse the order of these names in the array.

(4 Marks)
(Ans)
#include< iostream.h>
void main()
{
char *tmp; int i,j;
char *list[]={"Asia", "Bahamas","Canada","Denmark","England"};
for( i=0;i< 5;i++)
cout<< list[i]<< endl;
for( i=0,j=4; i < 2;i++,j--)
{
tmp=list[i];
list[i]=list[j];
list[j]=tmp;
}
for( i=0;i < 5;i++)
cout<< list[i]<< endl;
}

(Q.) What is the difference between an array and a structure?


(1 Mark)
(Ans)

An array is a collection of elements of the same data type. Each array element is
referenced using the index or subscript. A structure has members of different data types.
The members in the structure are accessed using the dot . operator.

(Q.) What is the length of the given array?


ARR [ -3 .. 4]

(1 Mark)
(Ans)

Length = UB LB + 1
where UB (or Upper Bound) = 4
LB (or Lower Bound) = -3
Size = 4 - ( -3) +1
=8

Q.) What is the prerequisite for Binary Search method?


(1 Mark)
(Ans)

The array should be sorted for Binary Search to work. Also, the upper and lower bounds
for the array should be known, as mid point is calculated.

(Q.) What will be the address of the elements ARR[2] and ARR[-1] in an array
ARR[-5 .. 9] that has the base address 4500 and element size 2?

(2 Marks)
(Ans)
Address of ARR[i] = B + W(i LB)
where B is Base Address, W is element size and LB is Lower Bound of the array.
B = 4500 W = 2
i = 2 LB = -5
Address of ARR[ i ] = 4500 + 2( 2 (-5))
= 4514
B = 4500 W = 2
i = -1 LB = -5
Address of ARR[ i ] = 4500 + 2( -1 (-5))
= 4508

(Q.) What is an array? How are one-dimensional arrays different from twodimensional arrays?

(2 Marks)
(Ans)
An array is a collection of finite elements of the same data type, placed contiguously in memory. Each array
element can be referenced using index or subscript numbers.
Arrays can be one-dimensional or multi-dimensional.
A onedimensional array is declared with one size specification. Each element is accessed using the array name
and index number which refers to its location. In array A[10], the elements can be accessed as A[0], A[1] and so
on.
A twodimensional array can be regarded as an array of arrays. It requires 2 size specifiers. It is a kind of multidimensional array. To declare an integer array named AX with 4 rows and 8 columns, give
int AX[4][8];
Elements can be accessed as AX[r][c] where r is the row and c the column number.
Remember in C++, the row and column numbers start from 0.

(Q.) What is the difference between Linear and Binary Search?


(2 Marks)
(Ans)
They are both searching techniques. Linear Search can be used on sorted or unsorted arrays. It involves
comparing each array element with the given value.

Algorithm for Linear Search


1. SET ctr = 0// 0 is the Lower Bound of the array
2. REPEAT STEPS 3 to 4 UNTIL ctr > UB // check each element of the array
3. IF A[ctr] = Val THEN// compare value and array element
{
PRINT Val, located at , ctr
GO TO 6
}
4. ctr = ctr + 1 // increment counter
5.IF ctr > UB THEN
PRINT Val, Not in array
6. END
Binary Search can be used only on sorted arrays. It is considered more efficient than
Linear Search as the number of comparisons is much less. It first compares the value
and the middle element of the array. As it is a sorted array, if the value is less than the
middle element, the elements in the left half should be checked otherwise if the value is
greater than the middle element, the right half of the array should be checked. This
process is done repeatedly till the element is located or declared not found.
Algorithm for Binary Search with array sorted in ascending order
1. SET low = LB, up = UB // UB and LB are upper and lower bounds
2. REPEAT STEPS 3 to 6 UNTIL low > up // repeat until low goes beyond up
3. m = INT( low + up) / 2 // find mid point of array
4. IF A[ m ] = Val THEN // compare value and array element
{ PRINT Val, located at , m + 1
GO TO 7
}
5. IF A [ m ] < Val THEN
low = m + 1
6. IF A[ m ] > Val THEN
up = m - 1
7. END

An array is given below. Give the status at the end of each pass using selection
sort method.
2 4 6 8 1 3 5 7

(2 Marks)
(Ans)
After
After
After
After
After
After
After

I-14682357
II -1 2 6 8 4 3 5 7
III -1 2 3 8 4 6 5 7
IV -1 2 3 4 8 6 5 7
V -1 2 3 4 5 6 8 7
VI -1 2 3 4 5 6 8 7
VII -1 2 3 4 5 6 7 8

Using the array below, give the status at the end of each pass using bubble sort
method.
2 4 16 28 11 3 25 27

(2 Marks)
(Ans)
After I- 2 4 16 11 3 25 27 28
After II -2 4 11 3 16 25 27 28
After III -2 4 3 11 16 25 27 28
After IV -2 3 4 11 16 25 27 28
After V -2 3 4 11 16 25 27 28
After VI -2 3 4 11 16 25 27 28
After VII -2 3 4 11 16 25 27 28
After VIII -2 3 4 11 16 25 27 28
Using the array below, give the status at the end of each pass using insertion
sort method. 12 24 26 28 11 13 25 27

(2 Marks)
(Ans)
After I - 12 24 26 28 11 13 25 27
After
After
After
After
After
After
How

II - 12 24 26 28 11 13 25 27
III - 12 24 26 28 11 13 25 27
IV - 11 12 24 26 28 13 25 27
V - 11 12 1324 26 28 25 27
VI - 1112 1324 25 26 28 27
VII - 1112 1324 25 26 27 28
are two-dimensional arrays implemented in memory?

(2 Marks)
(Ans)
An array is allocated contiguous storage in memory. For this, the 2D array is linearized. This can be done in two
ways Row Major or Column Major.
In Row Major form, the first row is stored followed by the second row and so on. In
Column Major, the first column is stored followed by the second column and so on. The
computer keeps track of the starting address of the array (base address) and accesses
the element by calculating its address.
X is a 2D array defined as [-2 .. 4, -3 .. 4]. Each element of the array takes up
2 bytes. Its base address is given as 2000. Calculate the address of X[2,3], if
the array is stored in row major form.

(2 Marks)
(Ans)
Address of X[ i ] [ j ] = B + W( nc(i LB_R) + (j LB_C))
Here, B = 2000 nc = 8
W = 2 LB_R = -2
i = 2 LB_C = -3
j=3
Address of A[i , j] = 2000 + 2( 8( 2 - (-2) ) + (3 - (-3) )
= 2076

Each element of the array A[-10 .. 5, 5 .. 15] takes 1 byte. Its base address is
given as 1000. Calculate the address of A[ -5, 8]. The array is in column
major.

(2 Marks)

(Ans)
Address of A[ i ] [ j ] = B + W( nr( j LB_C) + ( i LB_R))
Here, B = 1000 nr = 16
W = 1 LB_R = -10
i = -5 LB_C = 5
j=8
Address of A[-5, 8] = 1000 + 1( 16(8 - 5) + ( -5 (-10) )
= 1053
What do you means by data structures? Describe different types of data
structure.

(3 Marks)
(Ans)
The fundamental data types (char, int, float, double,void) can be grouped together and treated as a unit. This
grouped unit is a data structure.
Data structures have been classified into two categories Simple Data Structure these are built using the fundamental data types i.e. char, int, float anddouble.
Examples - arrays and structures
Compound Data Structure these are built using simple data structures. These are further divided into linear
and non-linear.
Linear data structures are those whose elements form a sequence. Examples Stacks, Queues and Linked
Lists.
Non-Linear data structures are those whose elements are at different levels. Example
- trees.
Describe in brief, the different operations that are performed on an array.

(3 Marks)
(Ans)
The basic operations performed on arrays are
Traversing - visiting each element for some processing.
Searching traversing the array to see if a certain given value exists in it or not. Two commonly used methods
are Linear Search and Binary Search. Linear search can be used on unsorted arrays. Binary Search is done
only on sorted arrays.
Insertion This can be done if there is space available in the array. In an unsorted array, the new element can be
placed at the end. If the array is sorted, the element is given its proper position in the sorted sequence, by
shifting other elements.
Deletion - If the element to be deleted exists in the array, then the element should be removed and the elements
that follow shifted so that the rest of the sequence remains undisturbed.
Sorting - Array elements may be arranged in ascending or descending order. Some sorting techniques are
bubble sort, selection sort, insertion sort, shell sort, heap sort, quick sort.
Merging two arrays may be combined to form a third array. If the two arrays are sorted, then using merge
sort technique, we can create the third array, sorted.
Write a function linear() that accepts an integer array and the value to search
and returns the position at which it is found(if found), using the Linear Search
technique.

(3 Marks)
(Ans)
int linear(int A [ ], int n){
int i, pos = -1;
for(i=0; i < 10 ; i++)
if(A[ i ] == n){
pos = i+1;
break;
}

return pos;
}
Write a function binary() that accepts an integer array and the value to search
and returns the position at which it is found(if found), using the Binary Search
technique.

(3 Marks)
(Ans)

int binary(int A[ ], int n)


int pos, l, u, m;
pos=-1;
l=0;
u=9;
while(l <= u){
m=(u + l)/2;
if(A[m]==n){
pos=m+1;
break;
}
if(A[m]>n)
u=m-1;
else
if(A[m] < n)
l=m+1;
}
return pos;
}

How can a value be inserted into an array? Describe the different ways. Give
the algorithm for any one.

(4 Marks)
(Ans)
Insertion of another value can be done if there is space available in the array. If the array is unsorted i.e.
elements are not placed in any particular sequence, the new element can be made the last element. If the array is
sorted, the element must be given its proper position in the sorted sequence.
Algorithm for Insertion in a Sorted Array Ascending order
1. SET i = 0
2. REPEAT STEP 3 AS LONG AS A[ i ] < Val
3. IF A[ i ] < Val THEN
i = i + 1;
4. SET pos = i;
5. SET i = UB
6. REPEAT STEP 7 UNTIL i = pos
7. { A[ i ] = A[ i-1 ];
i=i1
}
8. A[ pos ] = Val;
9. END

Write a program that deletes all occurrences of a value from an integer array
A[20] and shifts the rest of the elements to the right.

(4 Marks)
(Ans)

// to delete all occurrences from sorted array and shift right


#include < iostream.h>
#include < conio.h>
void main(){
clrscr( );
int i, j, k, n, pos, A[20];
cout<<"nEnter integers for the array, in ascending order";
for(i=0;i< 20;i++)
cin>>A[ i ];
cout<<"nEnter integer to delete : ";
cin>>n;
k = 0;
pos = -1;
for(i=0; i < 20; i++){
if (A[ i ] == n){ // if found, shift all in front, back
pos = i;
for(j=pos; j > 0; j--)
A[ j ] = A[ j - 1 ];
A[ k ] = 0;
++k;
}
}
if (pos==-1)
cout<<"n Not found in array n";
for(i=0; i < 20; i++)
cout<< A[ i ]<< ' ';
getch();

Write a program to display the sum of elements on both the diagonals in a


2dimensional array.

(4 Marks)
(Ans)
// To display sum of both diagonals separately
#include < iostream.h>
#include < conio.h>
void main()
{
clrscr();
int i, j, X[4][4], sl = 0, sr = 0;
cout<<"nEnter integers for the array";
for(i=0; i < 4; i++) // accept 16 nos. into array X
for(j=0; j < 4; j++)
{
cin>>X[ i ] [ j ];
cout<<"n Sum of left diagonal = ";
}
for(i=0; i < 4; i++) // add left diagonal
{
sl = sl + X[ i ] [ i ];
cout<< sl;
cout<<"n Sum of right diagonal = ";
}

for(i=0; i < 4; i++)// add right diagonal


for(j=0; j < 4; j++)
{
if( i +j == 3)
sr = sr + X[ i ] [ j ];
cout<< sr;

}
}
) Write a program to accept integers into a 1 dimensional array and then place
all the even numbers before all the odd numbers.

(4 Marks)
(Ans)

// to shift even nos before odd


#include < iostream.h>
#include < conio.h>
void main(){
clrscr();
int i, j, A[10], B[10];
cout<<"nEnter integers for the array";
for(i=0; i<10; i++) // accept 10 elements into array A
cin>>A[ i ];
j=0;
for(i=0; i<10; i++){ // place even nos. in array B
if(A[ i ]%2==0){
B[ j ] = A[ i ];
++j;
}
}
for(i=0; i < 10; i++){ // place odd nos. in array B
if(A[ i ]%2==1){
B[ j ] = A[ i ];
++j;
}
}
for( i=0; i<10; i++) // copy array B to array A
A[ i ] = B[ i ];
for(i=0;i<10;i++) // display array A
cout<< A[ i ]<< ' ';
}

Write a program to accept integers into a 2D array and then replace all the
elements below the diagonal with 0.

(4 Marks)
(Ans)
// To replace elements below left diagonal with 0s
#include < iostream.h>
#include < conio.h>
void main()
{
clrscr();
int i, j, X[4][4];
cout<<"nEnter integers for the array";
for(i=0; i < 4; i++) // accept 16 elements into array

for(j=0; j < 4; j++)


cin>>X[ i ] [ j ];
for(i=0; i < 4; i++) // assign 0 if below diagonal
for(j=0; j < 4; j++)
{
if ( i > j )
{
X[ i ] [ j ] = 0;
cout<< "n Final Array n";
}
}
for(i=0; i < 4; i++)
{// display final array
for(j=0; j < 4; j++)
{
cout << X[ i ] [ j ]<< " ";
cout<<"n";
}
}
}

What is merge-sort? Write a program to merge-sort 2 arrays into a third one.


The two arrays are sorted in descending order and the resultant array should
be in ascending order .

(5 Marks)
(Ans)
Merge sort is when two sorted arrays are merged to create the third array which is also sorted.
In this technique, the current values of the two arrays are compared and the one smaller is put into the new array.
The marker in the array used moves ahead one element. Again the current elements of the two arrays are
compared and the smaller value put into the new array. This process continues till one of the arrays ends and
then the remaining elements of the other array are placed in the new array.
//Merge sort ascending- with component arrays in descending order
#include < iostream.h>
void main(){
int ia, ib, ic, A[6], B[6], C[12];
cout<<"nEnter 6 integers, in desc order "; //first array
for(ia=0; ia < 6; ia++)
cin>>A[ ia ];
cout<<"nEnter 6 more integers, in desc order "; // second array
for(ia=0; ia < 6; ia++)
cin>>B[ia];
for(ia=5,ib=5,ic=0; ia>=0 && ib>=0; ) // creation of third array
{
if(A[ia] > B[ib]){
C[ic] = B[ib];
++ic;
--ib;
}
else{

C[ic] = A[ia];
++ic;
--ia;
}
} // end of for loop
if(ia < 0)
while(ib>=0){
C[ic] = B[ib];
++ic;
--ib;
}
if(ib < 0)
while(ia >= 0){
C[ic] = A[ia];
++ic;
--ia;
}
cout<<"n Merged Array n";
for(ic=0; ic<12; ic++)
cout<< C[ic]<< ' ';

} // end of main function


Structured Query Language
Write a query on table EMP to display output as belowEmpName is on Project ProjCode
Raman is on Project
Del112
Saran is on Project
Jai122

(1 Mark)
(Ans)
SELECT EmpName, is on Project , ProjCode FROM emp;

What is Data Dictionary?

(1 Mark)
(Ans)
A Data Dictionary is a database containing data about all the databases and objects
therein, that make up a database system. It is often thought of as data about the data
or metadata.
What is NULL?

(1 Mark)
(Ans)
Null is a keyword implying an empty value. Two NULLs cannot be added, subtracted or
compared. A NULL can not be equated with 0 or blank spaces. To use in query, write as
below
SELECT *FROM student
WHERE grade IS NULL;

Write a query on table EMP to display output as belowEmpName


Raman
Saran

is on Project
is on Project
is on Project

ProjCode
Del112
Jai122

(1 Mark)
(Ans)

SELECT EmpName, is on Project , ProjCode FROM emp;


Give the statement to display the number of employees with job as Clerk from
table EMPLOYEE.

(1 Mark)
(Ans)
SELECT COUNT(EmpName) FROM employee
where Job = Clerk;
How is pattern matching carried out using SQL statements?

(1 Mark)
(Ans)

LIKE searchescharacter data to see if any part of it matches a pattern. The character
pattern-matching operation is called wildcard search. Two symbols are used to make the
search string
%(Percent) - it represents any sequence of zero or more characters.
_(Under Score) - it represents any single character.
To look at the details of all students whose name starts with A we can give:
SELECT * FROM student
WHERE name LIKE A% ;
Output
ROLLNO
NAME
MARKS
GRADE
CLASS
2

Ankur

88.5

XII A

3
Abhinav
65.5
B
XII A
The query gives A% as a pattern to match in column name - A which may be followed
by any character.
To look at the details of all students whose name starts with one unknown letter that is
followed by aurav we can give
SELECT * FROM student
WHERE name LIKE _aurav;
Output
ROLLNO
NAME
MARKS
GRADE
CLASS
9

Gaurav

78.8

XII B

11
Saurav
77.7
B
XII C
The underscore character, _, represents one character, followed by aurav. [D U/-]

What is NULL ?

(1 Mark)
(Ans)

Null is a keyword implying an empty value.Two NULLs cannot be added, subtracted or


compared. A NULL can not be equated with 0 or blank spaces.
To use in query, write as below
SELECT *FROM student WHERE grade IS NULL;
Give the statement to display the number of employees with job as Clerk from
table EMPLOYEE ?

(1 Mark)
(Ans)

SELECT COUNT(EmpName) FROM employee where Job = Clerk ;

Give the SQL statement to create a table EMPLOYEE with the structure as given
below EmpCode
EmpName
Job
Salary
ProjCode

4 digit number
up to 10 characters long
up to 10 characters long
7 digits including 2 decimal digits
6 characters

(2 Marks)
(Ans)

CREATE TABLE employee (EmpCode number(4), EmpName varchar2(10), Job


varchar2(10), Salary number(7,2), ProjCode varchar2(6));
How can a table be created from an existing table ?

(2 Marks)
(Ans)
A new table can be created from an existing one by using the CREATE and SELECT
statements in a query.
Example :
CREATE TABLE newtab AS ( SELECT EmpCode, ProjCode FROM employ WHERE
Job = Manager);
Table newtab will have 2 columns, EmpCode and ProjCode, and data picked up from rows
where Job was Manager, in the table employ.If the WHERE clause is left out, data from
all the rows will be inserted.

Describe the Primary Key constraint used on a table ?

(2 Marks)
(Ans)

The Primary Key uniquely identifies each row. It can not have NULL values or repeated
values in it. A table can have only one Primary Key. When it is placed as a constraint on
a column (or a set of columns), the column has to store values in keeping with these
rules.
Example : CREATE TABLE student (rollno number (2) NOT NULL PRIMARY KEY, name
char(15), marks number(5,1), grade char(1), class char(5));
How can rows be inserted into a table from another table ?

(2 Marks)
(Ans)
Data rows are added to atable using the INSERT command.INSERT command can also be
used to take values from one table and add them to another. In place of the valuesclause
an appropriate query is given and the resulting rows are added into the target table.
Example : INSERT INTOtemp SELECT name, class FROM student WHERE
marks>75;
Here, rows where marks > 75 will be considered from table STUDENT and the NAME and
CLASS columns will be inserted into table TEMP.
To insert using a query, keep in mind that :
(i) Both the tables must be already created.
(ii)The columns of the tables being inserted into, must match the columns output by the
sub query.
Describe the Primary Key constraint used on a table.

(2 Marks)

(Ans)
The Primary Key uniquely identifies each row. It can not have NULL values or repeated
values in it. A table can have only one Primary Key. When it is placed as a constraint on
a column (or a set of columns), the column has to store values in keeping with these
rules.
Example :CREATE TABLE student (rollno number (2) NOT NULL PRIMARY KEY,
name char(15), marks number(5,1), grade char(1), class char(5));
Describe the Order By clause.

(2 Marks)
(Ans)
The ORDER BY clause allows you to impose an order on your output. Using this clause
will display your query results in a sorted manner, by one or more columns. The sorting
can be done either in ascending or descending order,ascending being the default order.
When writing the query, it is generally placed last.
The example below
SELECT name, marks
FROM student
ORDER BY marks;
displays output as
NAME MARKS
Brij 60.5
Abhinav 65.5
Gaurav 78.8
Dhruv 79.5
Ankur 88.5
The output is in ascending order of marks.
SELECT *FROM student
ORDER BY name DESC;
The above query displays data in descending order of names, alphabetically.

Describe the Having clause.

(2 Marks)
(Ans)
The HAVING clause places conditions on groups in contrast to WHERE clause that places
conditions on individual rows. While WHERE conditions cannot include aggregate
functions, HAVING condition can.
SELET Grade, MAX (marks)
FROM student
GROUP BY grade
Having MAX (marks)>75;
What is the difference between WHERE and HAVING clause?

(2 Marks)
(Ans)

The HAVING clause places conditions on groups in contrast to WHERE clause that places
conditions on individual rows. While WHERE conditions cannot include aggregate
functions, HAVING condition can do so.
This meanswe can not do some thing like the followingSELECT Grade, MAX(marks)
FROM student
WHERE MAX(marks)>75

GROUP BY Grade;
WHERE would apply to individual rows like
SELECT Grade, marks
FROM student
WHERE marks>75 ;
To see the maximum marks for each grade, if over 75, you would use the HAVING
clause. The HAVING clause defines the criteria to select the output of certain groups.
SELET Grade, MAX(marks)
FROM student
GROUP BY grade
Having MAX (marks)>75;
How is a table deleted? Under what condition can a table be deleted?

(2 Marks)
(Ans)
We can not delete a table until it is empty as we can delete only empty tables. We can
remove the entire table using DROP TABLE command.Once a table is removed, it cannot
be retrieved. The command to remove the table student permanently from the database
is:
DROP TABLE student;
Give the SQL statement to create a table EMPLOYEE with the structure as given
below EmpCode
4 digit number
EmpName
up to 10 characters long
Job
up to 10 characters long
Salary
7 digits including 2 decimal digits
ProjCode
6 characters

(2 Marks)
(Ans)

CREATE TABLE employee


(EmpCode number(4), EmpName char(10),
Job char(10), Salary number(7,2),
ProjCode char(6));
What is the difference between count(), count(*), count(code),
count(DISTINCT dept) and count(ALL dept)?

(2 Marks)
(Ans)

The functions can be distinguished as follows:


1. count() is a function to count, it needs an argument.
2. count(*) to count the number of rows in a table.

3. count(code) to count the number of non-null values in column code.


4. count(DISTINCT dept) - to count the number of distinct entries, i.e. to count a
particular entry only once even if it appears many times.

5. count(ALL dept) to count the number of non-null values in column dept, i.e.
counting repetitions too.

Give the statement to add a row of data to table EMPLOYEE as givenA101 as Empcode, Shyam as Empname, Clerk as Job, 5000 as Salary and
LUC222 as ProjCode.

(2 Marks)

(Ans)
INSERT INTO employee (EmpCode, EmpName, Job, Salary, ProjCode) VALUES (A101,
Shyam, Clerk, 5000, LUC222);

How can rows be inserted into a table from another table?

(2 Marks)
(Ans)

Data rows are added to a table using the INSERT command. INSERT command can also
be used to take values from one table and add them to another. In place of the values
clause an appropriate query is given and the resulting rows are added into the target
table.
Example :
INSERT INTO temp
SELECT name, class
FROM student
WHERE marks>75;
Here, rows where marks > 75 will be considered from table STUDENT and the NAME and
CLASS columns will be inserted into table TEMP.
To insert using a query, keep in mind that :
(i) Both the tables must be already created.
(ii)The columns of the tables being inserted into, must match the columns output
by the sub query.
How can a table be created from an existing table?

(2 Marks)
(Ans)

A new table can be created from an existing one by using the CREATE and SELECT
statements in a query. Example :
CREATE TABLE newtab AS
(
SELECT EmpCode, ProjCode FROM employ WHERE Job = Manager
);
Table newtab will have 2 columns, EmpCode and ProjCode, and data picked up from rows
where Job was Manager, in the table employ. If the WHERE clause is left out, data from
all the rows will be inserted.
How is a table deleted? Under what condition can a table be deleted ?

(2 Marks)
(Ans)
Only empty tables can be deleted.We can remove the entire table and once removed, the
table cannot be retrieved.The command to remove the table student permanently from
the database is :
DROP TABLE student;

What are DDL, DML and DCL ?

(3 Marks)
(Ans)

Data Definition Language (DDL) is one of the major components of the Structured
Query Language (SQL). It is used to create data structures like databases, tables, views
and indexes. Some of the commands comprising DDL are CREATE TABLE, DROP TABLE
and CREATE INDEX.
Data Manipulation Language (DML) is a category of SQL used to manipulate data

query, insert, update etc. Examples of DML commands are SELECT, INSERT, DELETE .
Data Control Language (DCL) is a subset of SQL, used to control access to data in a
database. Examples of DCL commands include:GRANT - to allow specified users to
perform specified tasks, REVOKE to cancel previously granted or denied permissions.
What is a view? How is it different from a table? What are the advantages of
using views?

(3 Marks)
(Ans)
A view is a logical table that contains no data of its own. Its contents are taken from
other tables through the execution of a query. As the values is those tables change, so
automatically, will the values in the view.
The table on which a view is based is called a base table. Views are like windows through
which you view information that is actually stored in a base table.
Advantages of using a VIEW
Views display data selectively and so restrict access to data
Views are used to get results of complicated queries, especially where multiple tables
are used.
One view can be used to display data from several tables.
What are the different operators and how are they used in SQL statements?

(3 Marks)
(Ans)

At times you would like to see only certain rows according to your requirement instead of
all the rows all the time. The WHERE clause lets you give a condition which restricts the
rows.
While specifying the condition, operators are used. There are three types of operators
Relational Operators
Logical operators
Special operators

Relational Operators are used for comparison between two values.


Operator

Meaning

Equal to

>

Greater than

>=
<
<=

Greater than or equal to


Less than
Less than or equal to

<>
Not equal to
Example
SELECT * FROM student
WHERE marks>75;
Here output rows will be selected based on the condition marks>75, > being a relational
operator.

Logical Operators are used to combine two or more conditions to produce a single result. The
conditions are evaluated to True or False and a row is considered only if the final result is
True. Logical operators may also be used to negate the results of a single condition.
Operator

Meaning

AND

Returns True if both component conditions are True

OR

Returns True if any one component condition is True

NOT
Returns True if the condition is False
Example
SELECT * FROM student
WHERE grade=A AND class=XII A;

Here the first condition is grade = A and the second condition is class=XII A. The AND
between them means that all the rows for which both conditions are true will be part of
the result.
Example
SELECT * FROM student
WHERE grade=A OR class=XII A;
Here the first condition is grade = A and the second condition is class=XII A. The OR
between them means that all the rows for which any one condition is true will be part of
the result.
Example
SELECT * FROM student
WHERE NOT grade=A
Here the condition grade = A is to be negated. The rows where grade is not A are seen
in the output.

Special operators are used to give other comparison conditions.


Operator

Meaning

BETWEEN Between two values (inclusive)


AND
IN (set)

Match any value in the list

LIKE

Match a character pattern

IS NULL
Is a null value
Using BETWEEN:- It displays rows based on a range of values.
Example
SELECT * FROM student
WHERE marks BETWEEN 75 AND 90;
The output will be rows that have the value for column marks between 75 and 90.
Using IN:- It tests for a value in a specified set of values.
Example
SELECT * FROM student
WHERE name IN(Brij, Dhruv, Anu, Surbhi);
The output rows have the value in column name as one of those given in the list within
parenthesis.
Using LIKE:- LIKE can be applied only to columns of CHAR datatype. LIKE searches
character data to see if part of it matches a pattern . Two symbols are used to make the
search string
%(Percent) - it represents any sequence of zero or more characters.
_(Underscore) - it represents any single character
To look at the details of all students whose name starts with A we can give
SELECT * FROM student
WHERE name LIKE A%;
Here we have specified only A which may be followed by any character, as implied by
the % sign.
To look at the details of all students whose name starts with an unknown letter but is
followed by aurav we can give
SELECT * FROM student
WHERE name LIKE _aurav;
What is a Constraint ? Discuss the different constraints in brief ?

(5 Marks)
(Ans)
Constraint is a restriction or a check that is applied to the columns of the table. They prevent invalid data entry
into tables as the data they store must satisfy the checks or conditions placed. Constraints are specified when the
table is defined. Constraints may be defined at the column level or the table level.
Some commonly used constraints that may be applied are
NOT NULL - column cannot contain null values
UNIQUE- value must be unique in all rows

PRIMARY KEY -uniquely identifies each row


FOREIGN KEY - establishes a relationship between columns of different tables.
CHECK- gives a condition that must be true.
CREATE TABLE student (rollno number (2) NOT NULL PRIMARY KEY, name char(15), marks number
5,1) CHECK (marks >25), grade char(1), class char(5) DEFAULT = KG);
On giving this command, a table named STUDENT will be created. When data is entered, it will not allow
BLANK OR duplicate values in ROLLNO column, marks should be greater than 25 and default value for class
will be KG. Here we have applied column level constraints.
To apply constraint to the table as a whole, put it at the end of the table definition.
CREATE TABLE employee (empcode number (4) NOT NULL, name char(15), salary number(5,1),
dept char(4), joindate date, birthdate date, CHECK ( joindate > birthdate);
On giving this command, a table named EMPLOYEE will be created. When data is
entered, it will not allow BLANK values in empcode column, and ensure that joining date
is after date of birth.

Give the name and purpose of the different aggregate functions used in SQL.

(5 Marks)
(Ans)
Aggregate functions are applied to all rows in a table or to a subset of the table specified
by a WHERE clause. Aggregate functions produce a single value for the entire group of
table entries. These functions are :
COUNT produces the number of rows
SUM produces the arithmetic sum of all selected values of a given column.
AVG produces the average (mean) of all selected values of a given column
MAX produces the largest of all selected values of a given column
MIN produces the smallest of all selected values of a given column
Aggregate functions are used like column names in the SELECT clause of queries. The
functions SUM and AVG are used only with numeric columns. COUNT, MAX, MIN can be
used with numeric, date or character.
The name of the column on which the function is to be applied, is placed within
parenthesis. Only one column within a pair of parenthesis should be given at a time. To
use more than one function, write them and separate them by commas. To apply the
same function to many columns, repeat the function giving a different column name
every time in the same statement.

Database Concepts
What are Keys?

(1 Mark)
(Ans)

Anyrow in a relation can be distinguished from other rows by using an attribute (there
may be one or more). Such attributes are called Keys.

What is DBMS?

(1 Mark)
(Ans)
DBMS stands for Data Base Management System. A database is an organized collection
of related data. Data is stored as raw facts and figures.These facts and figures may have
been collected, stored, processed and manipulated but are without context.When data is

placed in context, it becomes meaningful and it becomes Information. A Database


Management System or DBMS is a software system that allows access to data contained
in databases.It provides an effective and convenient method of storing, retrieving and
updating information.
What are the different data models ?

(1 Mark)
(Ans)
Different data models describe how data structures may be defined and data
relationships and constraints maintained. The three most widely accepted data models
are the Relational, Network and Hierarchical models.

What are the advantages of using DBMS ?

(2 Marks)
(Ans)
The advantages provided by a DBMS are
1.Reduction of Redundancy.Unnecessary duplication of data is avoided.It reduces the extra storage required,
eliminates the extra processing involving large masses of data, eliminates inconsistencies which can exist in
multiple copies.
2.Sharing of Data. The database allows sharing of data by several users.
3.Integrity of Data MaintainedThis means that data is accurate and consistent.Checks can be built in to ensure
data is correct.
4.Inconsistency of Data Controlled.This is linked closely to minimizing redundancy sharing of data.
5.Security of Data Maintained.Confidential data must not be accessed by unauthorized persons so,access of data
by different users can be controlled.
6.Data Independence. The way data is stored in the database does not affect access of data from the database.
Describe the different Keys in a relation?

(2 Marks)
(Ans)

Keys are of the following types Primary Key A column (or columns) in a table that uniquely identifies each row.A
primary key value is unique and cannot be null.There is only one primary key for a table.
Foreign key -A column (or a set of columns) that refers to the primary key in another
table i.e. it is used as a link to a matching column in another table.
Candidate key - A column (or columns) that uniquely identifies rows in a table. Any of
the identified candidate keys can be used as the table's primary key. Any of the
candidate keys that is not part of the primary key is called an alternate key.

What are the advantages of using DBMS?

(2 Marks)
(Ans)
The advantages provided by a DBMS are
1. Reduction of Redundancy:-Unnecessary duplication of data is avoided. It reduces the
extra storage required, eliminates the extra processing involving large masses of data,
and eliminates inconsistencies which can exist in multiple copies.
2. Sharing of Data:- The database allows sharing of data by several users.
3. Integrity of Data Maintained:- This means that data is accurate and consistent.
Checks can be built in to ensure data is correct.
4. Inconsistency of Data Controlled:- This is linked closely to minimizing redundancy
sharing of data.
5. Security of Data Maintained:- Confidential data must not be accessed by unauthorized
persons so, access of data by different users can be controlled.
6. Data Independence:- The way data is stored in the database does not affect access of
data from the database.

Describe the Network data models in brief ?

(2 Marks)
(Ans)
In this data model, data is represented by a collection of records and the relationships are represented by links.
Each record is a collection of fields (attributes) each of which contains only one data value. A link is an
association between two records.
How is the select operation used ?

(2 Marks)
(Ans)
Select operation selects tuples(rows) that satisfy a certain condition(or predicate), from a relation.It gives a
horizontal subset from the relation where each row satisfies the given condition.The select operation is denoted
by the small Greek letter sigma.
If we write, Sales>2000(SALESMEN) the result will be those rows from relation SALESMEN where Sales
is more than 2000.
How is a database management system different from a file processing
system?

(2 Marks)
(Ans)
In a file processing system, data is stored in various files.In order to access or modify the data
in these files, programs have to be written. Some problems that commonly arise in such
systems are data redundancy, data inconsistency, loss of data integrity, incorrect data,
insecure data and data that is not according to set standards. The database management
system is inherently for sharing of data and provides controls so that the problems
encountered in the earlier mentioned system are eliminated or minimized.
Explain the terms Relation, Entity, Domain, Degree ?

(2 Marks)
(Ans)
Relation it is a table, with rows and columns to store data.
Entity it is something that exists, for which data is stored.For example a person, place, department etc.
Domain it is the set of permitted entries in a column.For example,a column COLOUR, may have the domain
{red, green,blue} where these are the only permitted values.
Degree it is the number of columns (or attributes) in a table.

How is the project operation used ?

(2 Marks)
(Ans)
The Project operation selects attributes(columns) from a relation. It is denoted by the Greek letter pi i.e. . The
result is a vertical subset of the given relation. Any duplicate rows are automatically removed. The columns
appear as subscript to and the table name appears in parenthesis.
If we write,

Zone, Sales (SALESMEN)


the result would be, columns Zone and Sales of the relation SALESMEN. The columns
appear in the result in the same order in which given in the projection expression.

What is meant by union-compatible?

(2 Marks)

(Ans)
The union operation requires two relations and produces another relation that contains
tuples from both the relations. For this operation, both relations must be union
compatible. This means both relations must have the same number of attributes
(columns) or degree. The domains of the i th attribute of the first relation and the
domains of the ith attribute of the second relation must be the same for all i.
Breif out different data models ?

(2 Marks)
(Ans)
Out the three data models, the Hierarchical model is the oldest.It has been in use on
mainframe computers involving, large quantities of data and lot of data processing.The
Network model is preferred if the user or the developer is to be given control over the
data storage.The Relational model is preferred by people who feel that the mechanisms
to access data must be hidden from users, and the system must be easy to understand
and construct.
Are there any disadvantages of using a database ?

(2 Marks)
(Ans)

Since data sharing is an integral part of the database, some problems may arise if
controls are not properly built into it. Some issues that need special attention in this
regard are maintaining data security and maintaining data integrity. System hardware
and operational costs may be high.Large systems maybe complex complicated to
maintain.
What are views ?

(2 Marks)
(Ans)

Views are virtual tables. They only exist as data derived from tables on which they are
based.A view is not stored as a table, rather, only its definition is stored.It is an excellent
way to restrict data access to people.
Explain the Set Difference Operation ?

(2 Marks)
(Ans)

Using the set difference operation we can find tuples that exist in one relation but in the
other. It is represented by the (minus) sign. Consider th example below. The two
tables are A and B. The operation A B gives another relation which is the result of this
operation.The two relations must be compatible i.e. of the same degree and the domains
of the corresponding columns must be the same.
AB
Class Name
Age
II
ASHISH
7
The result of A - B is
III
RAJAT
8
Class Name
Age
III
PUNIT
8

Explain the Set Intersection Operation ?

(2 Marks)
(Ans)
Using the set intersection operation we can find tuples that are common to two relations.
It is represented by the sign. Consider th example below. The two tables are A and B.
The operation A B gives another relation which is the result of this operation. It is the
same as writing A (A B). The two relations must be compatible i.e. of the same
degree and the domains of the corresponding columns must be the same.
AB

Class
II
III

Name
ASHISH
RAJAT

Age
7
8

The result of A
Class Name
II
ASHISH
III
RAJAT

How is data security


management system ?

B is
Age
7
8

ensured in a database

(2 Marks)
(Ans)
Data is vital to any organization and some of it may be confidential. Confidential data
must not be accessed by unauthorized persons.A database management system has
authentication schemes laid down, giving different levels of users different permissions
to access data. According to this, user may be allowed modify the data or simply read it
without making any changes.The data that can be seen is also controlled .
Describe the Hierarchical data model in brief ?

(3 Marks)
(Ans)
In the Hierarchical data model too data is represented by a collection of records and the relationships are
represented by links, somewhat similar to the Network model. Each record is a collection of fields (attributes)
each of which contains only one data value. Here, however, records are organized as tree instead of arbitrary
graphs.
The figure below shows a possible view of a database.
10-JUN-07 20-JUN-07
FD201

JAMAICAN INN

M122 MADAN

DAPHNE DA MERRIER

180

23232344

The record at the top of the tree is called the root.Operations like retrieval, deletion, modification etc. are
performed through a data manipulation language.
What is Cartesian product ?

(3 Marks)
(Ans)
Cartesian product is denoted by the x sign. The Cartesian product of two relations r1 and r2 is written as r1 x
r2. The resulting relation has columns from both the tables and rows that give all possible combinations of rows
between the two tables. The number of attributes in the resulting table is the sum of the number of attributes in
both the tables. The number of tuples in the resulting table is the product of the number of tuples in both the
tables.
Table ITEM below has 3 attributes Table SUPPLIER below has
2
attributesand
ICode
IName
Price
5 tuples.and
F505
Fruit Cake
100
3 tuples.
F675
Banana Bread
150
If we write
F203
Walnut Pie
250
T145
Shampoo
120
ICode
IName
Price
SCode
T156
Jasmine Soap
35
F505
Fruit Cake
100
S101
F505
Fruit Cake
100
S223
F505
Fruit Cake
100
S145
F675
Banana Bread
150
S101
F675
Banana Bread
150
S223
F675
Banana Bread
150
S145
F203
Walnut Pie
250
S101
F203
Walnut Pie
250
S223
F203
Walnut Pie
250
S145
T145
Shampoo
120
S101
T145
Shampoo
120
S223
T145
Shampoo
120
S145
T156
Jasmine Soap
35
S101
T156
Jasmine Soap
35
S223
T156
Jasmine Soap
35
S145

SCode
S101
S223
S145

SName
Aman Suppliers
Quality products
Suman & Co.

SName
Aman Suppliers
Quality products
Suman & Co.
Aman Suppliers
Quality products
Suman & Co.
Aman Suppliers
Quality products
Suman & Co.
Aman Suppliers
Quality products
Suman & Co.
Aman Suppliers
Quality products
Suman & Co.

ITEM x
SUPPLIER
the
resulting
table, as
below, has
5 attributes
(3 + 2) and
15 tuples
(5 * 3)

Describe the Relational data models in brief ?

(5 Marks)
(Ans)
In the Relational Data Model data is organized into tables with rows and columns.Each column has a unique
name and is called an attribute.A row of the table represents a relationship among a set of values.As the table is
a collection of such rowsit has a close relationship with the mathematical concept of relation, from where this
model takes its name.
The example below shows 2 tables of a database.
Student andAcademic :
Student(Adm_no, Name, Phone, DOB, Sex)
Academic(Class, Roll_No, Term1, Term2, Final)
Student
Adm_no
97012
97120
98078
98100

Name
Rajat Malik
Rajat Malik
Karan Kaushik
Prayatn Kumar

Phone
2234567
Class
2067895
8A
3456234
8B
2678789
7A

Sex
Roll_no M
F
12
M
12
M
3

Academic

Term1
Term2
89
90
78
88
66
76
9A
14
88
89
In the table Student, each student has a unique admission number.Using this number any row can be identified.
This column, Adm_no is therefore the primary key in the table.The table has four tuples (rows) and four
attributes (columns).Similarly, the other table has a primary key (Class + Roll_No) that can identify each row of
the table.These tables can be used to insert more rows, modify data in the rows, delete unwanted rows and to
query the tables.

Communication And Network Concepts


What are the goals of Networking?

(2 Marks)
(Ans)
The main goals of networking have always been to share resources and to provide a
medium for communications.
Sharing Resources among these are included not only printers and fax machines, but

Final
92
86
75
89

other devices like modems and servers. Software and data on the server maybe
accessed and shared by different users.
Reducing Cost it saves money to have a powerful server to store common files rather
than have separate computers , each with its own set of files. Sharing other resources
too saves on cost.
Reliability - If a machine goes down, another can take over. Copies of important files
can be maintained easily.
Speed - Fast communication of data and messages.

What is 80 20 rule of Network designing?

(2 Marks)
(Ans)

In a properly designed small to medium-sized network, 80 percent of the traffic on a


given segment should be local, and not more than 20 percent should need to move
across a backbone link.

Give 2 advantages and 2 disadvantages of wireless communication.

(2 Marks)
(Ans)

Wireless communication does not use a medium, like cables, for transmission. There are
advantages and disadvantages of this mode.
Advantages 1. Can be used where cable or wires cannot be laid over mountains,
sea etc.
2. Allows mobility, communication can generally be from anywhere, anytime
Disadvantages 1. It is not secure as anyone with the right receiver can catch the
signals
2. Sensitive to atmospheric conditions, like rain, storm etc.
What is cybercrime? Cyberlaw?

(2 Marks)
(Ans)
Cybercrime is criminal activity done using computers and the Internet. This includes
anything from illegally downloading music files to stealing sensitive data.
Cyber law (or Cyberlaw) describes the legal issues related to use of information
technology. Some topics it covers include intellectual property, privacy, freedom of
expression, and jurisdiction.
How is e-mail different from chatting?

(2 Marks)
(Ans)
Email or electronic mail is a way of sending electronic messages using the computer and
over a network. The recipient does not have to be online for the email to reach
successfully. He/she can read the mail when he is online.
Chatting is textual conversation between 2 or more people who are simultaneously
online. This communication goes on in real time.
Write a note on WLL.

(2 Marks)
(Ans)
WLL (Wireless local loop) provides wireless communication from fixed locations such
as, homes or offices.The quality of service is very good and it supports fax and modem
communication, internet and can connect to a Public Call Office. Here, there is a wireless
link as the "last mile / first mile" to connect to the telephone service or to broadband
internet. The signal transmissions occur through the air over a terrestrial microwave
platform instead of through copper or fiber cables.
Base stations are set up with multi-channel transmitters and receivers and customers

are provided an interface unit into which the telephone is connected. When a call is
made, a signal is sent to the base station, and a connection is made to allow
communication. For an incoming call, the base station makes a wireless connection and
gets the call through.
The advantages of WLL include the ability to connect with users, even in remote areas
without the need for laying new cables and the capacity for broad bandwidth that is not
impeded by fiber or cable capacities.
What are protocols? Give examples.

(2 Marks)
(Ans)
When computers communicate with each other, there needs to be a common set of rules
and instructions that each computer follows. A specific set of communication rules is
called a protocol. Because of the many ways computers can communicate with each
other, there are many different protocols, like, PPP, TCP/IP, SLIP, HTTP, and FTP.

Transmission Control Protocol (TCP), which uses a set of rules to send and receive
information packets with other Internet points
Internet Protocol (IP), which uses a set of rules to address each message so it
reaches the correct destination
Hypertext Transfer Protocol (HTTP) which uses a set of rules to allow
communication between a browser and server
File Transfer Protocol (FTP), which uses a set of rules to allow transfer of files
(uploading and downloading) between the users computer and server
What is Interspace?

(2 Marks)
(Ans)
InterSpace is an indicator of what the Internet of the future will be like. It has a
client/server architecture and hosts multiple users, by incorporating real-time audio and
video communication that allows people to interact within a three-dimensional
environment.
InterSpace can be used for distance learning, on-line shopping, gaming, and interactive
"Cyber-Events". It provides a great way to meet and talk to people from all over the
world.
Describe the client / server architecture.

(3 Marks)
(Ans)
Businesses of various sizes have various computer needs. Large businesses generally
have large computer setups, such as mainframes and networks. The network usually has
a client-server architecture, which is a type of division of labour for computing.
Under the client-server architecture, the server functions as the "brains" of the network,
serving a group of client computers, commonly called workstations. The server will be a
large-capacity computer, with a large amount of data and application software stored on
it. The client computers are smaller and have to place requests for data and applications
to the server, which then carries out these requests.
The Internet revolves around the client-server architecture. Your computer runs software
called the client and it interacts with another software known as the server located at a
remote computer. The client is usually a browser such as Internet Explorer, Netscape
Navigator or Mozilla. Browsers interact with the server through protocols. These
protocols help in the accurate transfer of data through requests from a browser and
responses from the server.
What is the difference between a web page, web site and web portal?

(3 Marks)

(Ans)
Web pages are generally created using html. and a collection of Web pages will form a
website.
A website is a destination whereas a web portal acts as an entry point to various services
or resources. The portal will usually include a search facility, directory of other sites,
news, e-mail, etc. For example,Yahoo.
Generally, there is no need to login into a website, it provides general information for any
user who might visit.The portal will have a login facility and will provide information
based on who you are.
What steps can be taken to secure a network?

(3 Marks)
(Ans)

It is imperative to secure a network so that only authorized users and programs can
access data. Some methods usually used are
Authorization this checks whether the person wishing to use a resource has the
permission to do so. This is done through logins.
Authentication uses passwords to check that the logged in user is who he claims to
be.
Use of Smart Cards This card has details of the holder on it and generates a code
that the computer can recognize.
Use of Biometrics using features that are unique to everybody, like finger prints,
retina patterns to identify the user.
Firewall restricting access to the network or specific computers through hardware and
software.
Explain URL its purpose and components.

(3 Marks)
(Ans)
URL, or Uniform Resource Locator, is the location of a file on the Web. When we type the
address of a Web page in the browser, we give the URL.
The most common format of a URL is http://www.mytown.com/shopping/aasd1.html.
The URL has two parts the first part, http:// gives the protocol used to locate the file
on the Web.
Http represents the Hyper Text Transfer Protocol, which is used to transfer Web pages
across the Internet to Web browsers such as Netscape Navigator, Internet Explorer, or
Linux. The protocol is followed by a colon and two slashes (://).
The portion of the URL following the protocol , here - www.mytown.com,
specifies the name of the host computer to access. WWW stands for World Wide Web.
The right-most designator (here, .com) describes the type of institution or organization.
Following the host name, the directory structure and filename are mentioned. Here,
shopping is a directory under the root directory of the host you are accessing. The file
aasd1.html is located in this directory.
How is the Ethernet Card different from Modem?

(3 Marks)
(Ans)
The Ethernet card allows your computer to connect to a network where all the systems
are physically cabled together. It handles only digital signals.
A modem, also connects a computer to a network but it changes digital computer signals
to analog signals for transfer over phone lines.
Network cards are thousands of times faster than a modem. A modem lets you connect
to an ISP, a network card lets you connect to a network or even a modem.
What are the features of 3G devices?

(3 Marks)
(Ans)

3G stands for third generation of wireless networks, combining high-speed mobile


access, carrying voice and data (including video, text, multimedia). The 3G networks

cover network technologies including GSM, CDMA, WCDMA, TDMA and WiMAX. The
mobile network industry is keen to adopt 3G as it feels that multimedia based content is
quickly becoming the norm. This includes services like - Music downloads ,
Mapping/navigation, Instant messaging, Web surfing, Email services and Gaming.
3G allows high bandwidth, packet based transmission at high data rates. EDGE
(Enhanced Data rates for Global Evolution) is an interface that will make it possible for
3G devices to have high data transfer rates.
Discuss video conferencing.

(3 Marks)
(Ans)
Through video conferencing, two or more people who are far apart can communicate in
real time, as though sitting face to face for a meeting. Besides the audio and visual
transmission of activities, videoconferencing can be used to share documents, computerdisplayed information, and whiteboards.
The core technology used in a video-teleconference system is digital compression of
audio and video streams in real time. The hardware or software that performs
compression is called a codec (coder/decoder). Compression rates of up to 1:500 can be
achieved. The resulting digital stream of 1s and 0s is subdivided into labelled packets,
which are then transmitted through a digital network.
What is the difference between worm and virus?

(3 Marks)
(Ans)
Viruses and worms are malicious programs that can cause damage to the computer, but
there are differences between them.
A computer virus attaches itself to a file enabling it to spread from one computer to
another, leaving infections as it travels.
Almost all viruses are attached to an executable file, which means the virus may exist on
your computer but it actually cannot infect unless you run or open the malicious
program. Remember, a virus cannot be spread without a human action, such as running
an infected program.
A worm is similar to a virus by design and is considered to be a sub-class of a virus.
Worms spread from computer to computer, but unlike a virus, it has the capability to
travel without any human action. A worm takes advantage of file or information
transport features on your system, which allows it to travel.
The worm has the capability to replicate itself on your system, so your computer can
send out hundreds of copies of the worms instead of a single worm, creating a
devastating effect. For example, a worm can send a copy of itself to everyone listed in
your e-mail address book. Then, the worm replicates and sends itself out to everyone
listed in each of the receiver's address book, and this continues.
A worm consumes too much system memory causing Web servers, network servers and
individual computers to stop responding.
What is the difference between Internet and WWW?

(3 Marks)
(Ans)
Often, people use the terms Internet and World Wide Web interchangeably, but they are
two separate but related things.
The Internet is a massive network of networks, a networking infrastructure. It forms a
network in which any computer can communicate with any other computer as long as
they are both connected to the Internet. Information that travels over the Internet does
so via a variety of protocols.
The World Wide Web, or simply Web, is a way of accessing information over the medium
of the Internet. It is an information-sharing model that is built on top of the Internet.
The Web uses the HTTP protocol to transmit data. The Web also utilizes browsers, such
as Internet Explorer or Firefox, to access Web documents called Web pages that are

linked to each other via hyperlinks. Web documents also contain graphics, sounds, text
and video.
The Web is just one of the ways that information can be distributed over the Internet.
The Internet, not the Web, is also used for e-mail, Usenet news groups, instant
messaging and FTP. So the Web is just a portion of the Internet, though a large one.
What is the difference between GSM and CDMA?

(3 Marks)
(Ans)
GSM and CDMA are differing technologies used for wireless communication. One of the
basic things that differentiates GSM and CDMA is the way they handle bandwidth and
divide up the signals between multiple users.
GSM (Global System for Mobile communication) uses a Time Division method. This
means that each device on the local network is allocated a time slice where it "owns" the
bandwidth, and it can send/receive its data. If there are 8 available time slices in a given
cycle, each phone would then get 1/8th of every cycle in which it could send and receive
signals. Each users data is digitized and compressed and sent in his own time slot. Data
is encrypted for security. The SIM (Subscriber Identity Module) is an important
component of the GSM cellular device and contains connection data, memory for data
and applications, and a processor.
CDMA (Code Division Multiple Access) is technology that was first used during World War
II. CDMA works on the principle of Spread spectrum.
The data is sent in small pieces over a number of frequencies available for use. Each
users data is encrypted in a particular way and at the receiving end, decrypting is done
to recover the actual signal.
Describe TCP/IP.

(4 Marks)
(Ans)

The Transmission Control Protocol (TCP) is one of the core protocols of the Internet
Protocol suite, often simply referred to as TCP/IP. Using TCP, applications on different
networked hosts can create connections to one another, over which they can exchange
streams of data. The protocol guarantees reliable and in-order delivery of data from
sender to receiver. TCP provides connections that need to be established before sending
data. TCP connections have three phases:
1.connection establishment
2.data transfer
3.connection termination
At the receivers end, the TCP arranges the received packets in proper sequence and
discards duplicate packets while at the senders end, TCP makes sure any lost or
damaged packets are resent, so that the message is properly communicated.
The Internet Protocol (IP) is a data-oriented protocol used for communicating data
across a packet-switched internet work.
IP (Internet Protocol ) is a connectionless protocol. This means that IP does not establish
a handshake with connected hosts in order to start generating data. The functions of IP
can be simply put as:
- Handling address mapping for the transmitting and receiving hosts.
- Creating the most basic unit of transmission, a datagram. A datagram has a particular
format and size.
What is the difference between switch and hub?

(4 Marks)
(Ans)
Although hubs and switches both link the PCs in a network, a switch is more expensive
and a network built with switches is generally considered faster than one built with hubs.
When a hub receives a packet of data at one of its ports from a PC on the network, it
transmits the packet to all of its ports and, thus, to all of the other PCs on the network.
If two or more PCs on the network try to send packets at the same time a collision is

said to occur. When that happens all the PCs have to go though a process described in
CSMA/CD to resolve the conflict. Each Ethernet Adapter has both a receiver and a
transmitter. Because they have to operate at half duplex (data flows one way at a time)
and a hub retransmits data from one PC to all of the PCs, the maximum bandwidth is
100 Mhz and that bandwidth is shared by all the PC's connected to the hub. The result is,
when a person downloads a large file from another computer, the network becomes
congested.
Two computers can be connected directly together in an Ethernet with a crossover cable.
A crossover cable doesn't have a collision problem. It hardwires the Ethernet transmitter
on one computer to the receiver on the other. Data can be sent in both directions
simultaneously. The maximum available bandwidth is 200 Mbps, 100 Mbps each way,
and there are no other PC's with which the bandwidth must be shared.
An Ethernet switch automatically divides the network into multiple segments, acts as a
high-speed, selective bridge between the segments, and supports simultaneous
connections of multiple pairs of computers. When the switch receives a packet, it reads
the destination address in the packet, establishes a temporary connection between the
source and destination ports, sends the packet on its way, and then terminates the
connection.
High-speed electronics in the switch automatically connect the ports from a sending
computer to the receiving computer on a per packet basis. Multiple connections like this
can occur simultaneously.

Define the following terms with respect to data communication


a) Data
b) Signals
c) Signaling
d) Transmission
(2 Marks)
(Ans)

a) Data: A collection of facts in raw form that becomes information after


processing
b) Signals: Electric or electromagnetic encoding of data
c) Signaling: Propagation of signals across a communication medium
d) Transmission: Communication of data achieved by the processing of
signals

List the similarities between FDDI and Token Ring.


(2 Marks)
(Ans)

FDDI uses a rotating ring setup in the same way as does the token ring
protocol.
FDDI's ring operation is basically very similar to the Token Ring early
release operation in the way that tokens are passed on the network.

List the 4 disadvantages of network.


(2 Marks)
(Ans)

Server faults stop applications from being available


Network faults can cause loss of data
Network fault could lead to loss of resources
User work dependent upon network
Compare star topology to bus topology.
(2 Marks)
(Ans)

As compared to the bus topology, a star network requires more devices


and cables to complete a network. The failure of each node or cable in a
star network wont take down the entire network as happens in the Bus
topology.
However, if the central connecting devices such as hub, switch or router
fail due to any reason, ultimately the entire network can come down or
collapse.
Explain the characteristics of FDDI in brief.
(2 Marks)
(Ans)

FDDI stands for Fiber Distributed Data Interface. The FDDI topology
is ring with two counter-rotating rings for reliability and with no hubs.
Cable type is fiber-optic. Connectors are specialized. The media access
method is token passing. Multiple tokens may be used by the system.
The maximum length is 100 kilometers. The maximum number of nodes
on the network is 500. Speed is 100 Mbps. FDDI is normally used as a
backbone to link other networks. A typical FDDI network can include
servers, concentrators and links to other networks.
What is the difference between broadcast and point-to-point?
(2 Marks)
(Ans)

Broadcast meanswe aresending digital signals to any device connected


to a network.

Point-to-point meansthat we aresending digital signals from a specific


point to a specific point (identified by IP address or MAC address).
What are the basic elements of a communication system?
(2 Marks)
(Ans)

The following are the basic requirements for working of a communication


system:
1. The sender (source) who creates the message to be transmitted
2. A medium that carries the message
3. The receiver (sink) who receives the message
List the differences between FDDI and Token Ring.
(3 Marks)
(Ans)

As opposed to Token Ring's single ring, FDDI uses two to


achieve better results and less chance of failure.
In a basic Token Ring network, at any instant, there is a single
active ring monitor which supplies the master clock for the ring,
whereas in FDDI, this approach is not ideal because of the high
data rates. Instead, each ring interface has its own local clock
and outgoing data is transmitted using this clock.
Unlike the basic Token Ring which is based on the use of
priority and reservation bits, the priority operation of the FDDI
ring uses a principle that is based on a parameter known as the
Token Rotation Time or TRT.
FDDI uses a timed token protocol where Token Ring uses
priority/reservation token access, leading to differences in frame
formatandhow station traffic is handled.
Explain the difference between analog signal and digital signal.
(3 Marks)
(Ans)

Analog: Analog signals are continuous electrical signals that vary in


time. In other words, anAnalog or analogue signal is any continuous
signal for which the time varying feature (variable) of the signal is a
representation of some other time varying quantity, i.e., analogous to
another time varying signal. It differs from a digital signal in terms of
small fluctuations in the signal which are meaningful.
Digital: A digital system is a data technology that uses discrete
(discontinuous) values. By contrast, non-digital (or analog) systems use
a continuous range of values to represent information. Although digital
representations are discrete, the information represented can be either

discrete, such as numbers, letters or icons, or continuous, such as


sounds, images and other measurements of continuous systems.
Differentiate between star topology and mesh topology.
(3 Marks)
(Ans)

Star Topology

In the computer networking world, the most commonly used topology in


LAN is the star topology. Star topologies can be implemented in homes,
offices or even in a building. All the computers in the star topologies are
connected to central devices like hub, switch or router. The functionality
of all these devices is different. Computers in a network are usually
connected with the hub, switch or router with the Unshielded Twisted
Pair (UTP) or Shielded Twisted Pair Cables.
Mesh Topology
Mesh topology works on the concept of routes. In Mesh topology,
message sent to the destination can take any possible shortest, easiest
route to reach its destination. In the previous topologies star and bus,
messages are usually broadcast to every computer, especially in bus
topology. Similarly, in the Ring topology, message can travel in only one
direction, i.e., clockwise or anticlockwise. Internet employs the Mesh
topology and the message finds its route for its destination. Router works
to find the routes for the messages and making them reach their
destination. The topology in which every device connects to every other
device is called a full Mesh topology unlike in the partial mesh in which
every device is indirectly connected to the other devices.
xplain the following terms:
a) LAN
b) MAN
c) WAN
(3 Marks)
(Ans)

a)LAN (Local Area Network): A group of computers that shares a


common connection and is usually in a small area or even in the same
building. For example, it can be an office or a home network. It is
usually connected by Ethernet cables and has high speed
connections. If it was a wireless setup, it would be called a WLAN,
which would have a lower connection speed.

b)MAN (Metropolitan Area Network): This is a larger network that


connects computer users in a particulargeographic area or region. For
example, a large university may have a network so large that it may be
classified as a MAN. The MAN network usually exists to provide
connectivity to local ISPs, cable TV, or large corporations. It is far larger
than a LAN and smaller than a WAN. Also, large cities like London and
Sydney, Australia, have metropolitan area networks.
c)WAN: (Wide Area Network) This is the largest network and can interconnect networks throughout the world because it is not restricted to a
geographical location. The Internet is an example of a worldwide public
WAN. Most WANs exist to connect LANs that are not in the same
geographical area. This technology is high speed and very expensive to
setup.
What are the advantages of network? Explain in detail.
(3 Marks)
(Ans)

Speed: Sharing and transferring files within networks are very rapid.
Thus, it saves time while maintaining the integrity of the file.
Cost: Individually licensed copies of many popular software programs
can be costly. Networkable versions are available at considerable
savings. Shared programs on a network allow for easier upgrading of the
program on one single file server instead of upgrading individual
workstations.
Security: Sensitive files and programs on a network are password
protected (established for specific directories to restrict access to
authorized users) or designated as copy inhibit, so that you do not
have to worry about illegal copying of programs.
Centralized Software Management: Software can be loaded on one
computer (the file server) eliminating the need to spend time and energy
installing updates and tracking files on independent computers
throughout the building.
Resource Sharing: Resources such as printers, fax machines and
modems can be shared.
Electronic mail: E-mail aids in personal and professional
communication. Electronic mail on a LAN can enable staff to
communicate within the building, having not to leave their desk.

Flexible Access: Access their files from computers throughout the firm
Workgroup Computing: Workgroup software(such as Microsoft
BackOffice) allows many users to work on a document or project
concurrently.
What is star topology? How does it work? What is the main
disadvantage of it?
(3 Marks)
(Ans)

Star topology is also known as star network. It is one of the most


common network setups where each of the devices and computers on a
network connects to a central hub. It needs more cable to be networked
than the usual bus topology. It is used in homes and offices. A major
disadvantage of this type of network topology is that if the central hub
fails, all computers connected to that hub would be disconnected.
Explain point-to-point communication in detail with examples.
(4 Marks)
(Ans)

A point-to-point connection is a dedicated communication link between


two systems or processes. Think of a wire that directly connects two
systems. The systems use that wire exclusively to communicate. The
opposite of point-to-point communications is broadcasting, where one
system transmits to many.
A telephone call is a circuit-oriented, point-to-point link between two
phones. However, calls are usually multiplexed across telephone
company trunks; so, while the circuit itself may be virtual, the users are
engaging in a point-to-point communication session.
An end-to-end connection refers to a connection between two systems
across a switched network. For example, the Internet is made up of a
mesh of routers. Packets follow a hop-by-hop path from one router to the
next to reach their destinations. Each hop consists of a physical point-topoint link between routers. Therefore, a routed path consists
of multiplepoint-to-point links. In the ATM and frame relay environment,
the end-to-end path is called avirtual circuit that crosses a pre-defined
set of point-to-point links.
Where is ring topology primarily used?Explain them.
(4 Marks)
(Ans)

Ring topology is used mainly in two kinds of networks:

a) Token Ring Networks


b) Fiber Distributed Data Interface
Token Ring Networks:
Unlike Ethernet, Token Ring uses a ring topology whereby the data is
sent from one machine to the next and so on around the ring until it ends
up back where it started. It also uses a token passing protocol which
means that a machine can only use the network when it has control of
the Token. This ensures that there are no collisions because only one
machine can use the network at any given time.
Fiber Distributed Data Interface :
The Fiber Distributed Data Interface or FDDI is a 100 mbps line using
the LAN network and is connected through a fiber optic cable. The FDDI
technology is used where the networks need a high speed bandwidth
and need to cover huge distances than the copper wires usually cover.
There are two kinds of networks in this category -- one is the fiber optic
wire based and the other is the copper wire based called the Copper
distributed data interface.
The inside architecture of the FDDI is based on the dual rings where the
data is flowing in the opposite directions. There are two levels of rings -the primary and the secondary. Most of the data transmission takes
place using the primary ring and the secondary is idling. However, in
case the primary does not work, the secondary takes over the primarys
functionalities.
What is star topology? How does it work? What is the main
disadvantage of it?
(3 Marks)
(Ans)

Star topology is also known as star network. It is one of the most


common network setups where each of the devices and computers on a
network connects to a central hub. It needs more cable to be networked
than the usual bus topology. It is used in homes and offices. A major
disadvantage of this type of network topology is that if the central hub
fails, all computers connected to that hub would be disconnected.
Explain point-to-point communication in detail with examples.
(4 Marks)

(Ans)

A point-to-point connection is a dedicated communication link between


two systems or processes. Think of a wire that directly connects two
systems. The systems use that wire exclusively to communicate. The
opposite of point-to-point communications is broadcasting, where one
system transmits to many.
A telephone call is a circuit-oriented, point-to-point link between two
phones. However, calls are usually multiplexed across telephone
company trunks; so, while the circuit itself may be virtual, the users are
engaging in a point-to-point communication session.
An end-to-end connection refers to a connection between two systems
across a switched network. For example, the Internet is made up of a
mesh of routers. Packets follow a hop-by-hop path from one router to the
next to reach their destinations. Each hop consists of a physical point-topoint link between routers. Therefore, a routed path consists
of multiplepoint-to-point links. In the ATM and frame relay environment,
the end-to-end path is called avirtual circuit that crosses a pre-defined
set of point-to-point links.
Where is ring topology primarily used?Explain them.
(4 Marks)
(Ans)

Ring topology is used mainly in two kinds of networks:


a) Token Ring Networks
b) Fiber Distributed Data Interface
Token Ring Networks:
Unlike Ethernet, Token Ring uses a ring topology whereby the data is
sent from one machine to the next and so on around the ring until it ends
up back where it started. It also uses a token passing protocol which
means that a machine can only use the network when it has control of
the Token. This ensures that there are no collisions because only one
machine can use the network at any given time.
Fiber Distributed Data Interface :
The Fiber Distributed Data Interface or FDDI is a 100 mbps line using
the LAN network and is connected through a fiber optic cable. The FDDI
technology is used where the networks need a high speed bandwidth

and need to cover huge distances than the copper wires usually cover.
There are two kinds of networks in this category -- one is the fiber optic
wire based and the other is the copper wire based called the Copper
distributed data interface.
The inside architecture of the FDDI is based on the dual rings where the
data is flowing in the opposite directions. There are two levels of rings -the primary and the secondary. Most of the data transmission takes
place using the primary ring and the secondary is idling. However, in
case the primary does not work, the secondary takes over the primarys
functionalities.
Explain the term network topology. Name the four basic
topologies. Explain any two topologies in brief.
(4 Marks)
(Ans)

Network topology is defined as the physical inter-connection of various


elements (links, nodes, etc.) of a computer network. Network Topologies
can be physical or logical. Physical Topologymeans the physical design
of a network including the devices, location and cable installation.Logical
topology refers to the fact as to how data actually transfers in a network
as opposed to its design.
The network topology recognises four basic topologies:

Bus topology

Star topology

Ring topology

Tree topology

Bus topology:
A bus topology is a method of transmission on networks that uses a
common vehicle for transmissions and is, therefore, categorized as
shared communication. Imagine a bus picking up various people from
one stop and dropping of people as it travels and picks up a few more.
That is what happens in a bus network exactly.
However, in a Bus topology, only one device is allowed to transmit at a
given point of time. The DAP or the Distribute Access Protocol has the
information about which station has to transmit the data. The data that is
being transmitted has frames that will have the source name and the
network address.

Ring topology:
In local area networks where the ring topology is used, each computer is
connected to the network in a closed loop or ring. Each machine or
computer has a unique address that is used for identification purposes.
The signal passes through each machine or computer connected to the
ring in one direction. Ring topologies typically utilize a token passing
scheme, used to control access to the network. By utilizing this scheme,
only one machine can transmit on the network at a time. The machines
or computers connected to the ring act as signal boosters or repeaters
which strengthen the signals that transverse the network. The primary
disadvantage of ring topology is that failure of one machine will cause
the entire network to fail.
Which topology allows only one device to transmit at a time?
Explain in detail with its advantages and disadvantages.
(4 Marks)
(Ans)

Bus topology connects each computer (node) to a single segment trunk


(a communication line, typically coax cable, that is referred to as the
'bus'). The signal travels from one end of the bus to the other. A
terminator is required at each to absorb the signal so that it does not
reflect back across the bus. A media access method called CSMA/MA is
used to handle the collision that occurs when two signals are placed on
the wire at the same time. The bus topology is passive. In other words,
the computers on the bus simply 'listen' for a signal; they are not
responsible for moving the signal along.
Advantages:
Failure of one of the stations does not affect others.
Good compromise over the other two topologies as it allows
relatively
high rate of data transmission
Well suited for temporary networks that must be set up in a hurry
Easy to implement and extend
Disadvantages:
Require a network to detect when two nodes are transmitting at the
same time
Does not cope well with heavy traffic rates
Difficult to administer/troubleshoot
Limited cable length and number of stations
A cable brake can disable the entire network; no redundancy

Maintenance cost may be higher in the long run


Performance degrades as additional computers are added.
C++ Revision Tour

Name the header file(s) that is needed for successful compilation of


the following C++ code:
void main()
{
char String[20];
gets(String);
strcat(String, CBSE);
puts(String);
}
(1 Mark)
(Ans)

The header files needed for the successful compilation of the above code are: string.h
and stdio.h.
What are the basic features of object oriented programming?
(1 Mark)
(Ans)

The basic features of object oriented programming are data abstraction, data
encapsulation, inheritance, and polymorphism.
Determine the output:
a = 1;
b = a++;
cout << a++;
cout << (b+a);
cout << ++b;
(1 Mark)
(Ans)

The output of the above code is 2 4 2.


What is a modular programming?
(1 Mark)
(Ans)

Modular programming is the breaking down of the program into smaller sub tasks, which
in turn may be broken down again so that the lowest-level functions are as simple as
possible.
What are the two types of functions available in C++?
(1 Mark)
(Ans)

The two types of functions available in C++ are:


Implicit and Explicit functions.
Name the header files to which the following belong:
(i) puts()
(ii) strcmp()
(1 Mark)

(Ans)

puts() belongs to stdio.h header file and strcmp() belongs to string.h header file.
What are the three expressions given in the for statement?
(1 Mark)
(Ans)

The three expressions are the initialization expression, test expression and the
increment/decrement (reinitialization) expression.
What is a recursive function?
(1 Mark)
(Ans)

A function that calls itself directly or indirectly is referred to as recursive function.


Find the syntax error(s), if any, in the following program:
include < iostream.h >
void main()
{
int x,y; cin >> x;
for(x = 0; x<5, ++x)
cout y else cout << x << y;
}
(2 Marks)
(Ans)

The correct program is


# include < iostream.h> //Correction 1
void main()
{
int x,y; cin>>x;
for(x = 0; x<5; ++x) //Correction 2
cout << y;
cout< < x << y; //Correction 3
}
Correction 1: The condition is terminated by a comma(,), instead of a
semicolon(;).
Correction 2: << is missing.
Correction 3: else cannot exist without if.
Write the output of the following program:
#include< iostream.h >
static int i = 100;
void abc()
{
static int i = 8;
cout << first = << i;
}
void main()
{
static int i = 2;
abc(); cout << second = << i << endl;
}
(2 Marks)
(Ans)

The output is
first = 8 second = 2
Find the output of the following program:
void main()
{
int x = 5, y = 6;
cout << x++;
cout << ,;
cout << ++x;
cout << ,;
cout << y++ << , << ++y;
}
(2 Marks)
(Ans)

The output is 5,7,6,8.


Write the output of the following program:
#include< iostream.h >
void X(int A, int &B)
{
A = A+B;
B = A-B;
A = A-B;
}
void main()
{
int a = 4, b = 18;
X(a,b);
cout << a << , << b;
}
(2 Marks)
(Ans)

The output is 4,4.


What will be the output of the following program:
# include < iostream.h >
void main()
{
int var1 = 5, var2 = 10;
for( int i = 1; i< =2; i++)
{
cout << var1++ << \t << --var2 << endl;
cout << var2-- << \t << ++var1 << endl;
}
}
(2 Marks)
(Ans)

The output is:


59

97
77
79
Why is main function special? Give two reasons.
(2 Marks)
(Ans)

(i) Whenever a C++ program is executed, only the main() is executed. The
execution of a program starts and ends at main().
(ii)The main() is the driver function of the program. If it is not included in the
program, no execution can take place.

Explanation :
null

Write two advantages of using include compiler directive.


(2 Marks)
(Ans)

(i) The # include compiler directive includes desired header files in our
program.
(ii) It supports modularity, i.e., a bigger program can be decomposed in
terms of header files and later included as apre-processor directive.
Differentiate between call by value and call by reference of function call.
(2 Marks)
(Ans)

Call by value - The values of the actual arguments are passed to the function.
Call by reference - The address of the actual arguments is used in the functioncall.
What is the purpose of the header file in a program?
(2 Marks)
(Ans)

Header files, also called include files, provide function prototype declarations for library
functions.
Explain the use of this pointer in C++.
(2 Marks)
(Ans)

While manipulating objects for user program, C++ maintains an internal pointer called
this, to point to the current object being operated upon.
Whenever a member function of an object is called, the compiler places the address of
the object in pointer this before invoking the function.
Write the output of the following program:
#include< iostream.h >
int func(int &x, int y = 10)
{
if(x%y = =0) return ++x; else return y;
}
void main()
{
int p = 20, q = 23;

q = func(p,q);
cout << p << q << endl;
p = func(q);
cout << p << q << endl;
q = func(p);
cout << p << q << endl;
}
(2 Marks)
(Ans)

The output is as:


2023
1023
1111
In the following program:
(i)
How many times will the while loop run?
(ii)
What would be the last value of A displayed out?
#include< iostream.h >
void main()
{
int A = 10;
while(++A<15)
{
cout << A++;
}
}
(3 Marks)
(Ans)

(i) The while loop will run for two times.


(ii) The last value to be displayed is 13.
Give the output of the following program:
# include< iostream.h >
void quare(int, int);
void main()
{
int i = 4, j = 10;
square(i,j);
cout << i;
cout<<j;
}
void square(int i, int j)
{
i = i * j;
j = j * j;
}
(3 Marks)
(Ans)

The output of the above program is 410.


Identify the problem with the following code:
void large( int &a, int &b);

int main()
{
.
large(5,7);
..
}
void large(int &a, int &b)
{
if(a>b) a = -1;
else b = -1;
}
(3 Marks)
(Ans)

There is no problem with the program code.


A function printchar is defined as
void printchar(char ch = *, int len = 40)
{
for( int x = 0; x<len; x++) cout << ch;
cout << endl;
}
How will you invoke the function printchar for following output:
(i)
to print * 40 times
(ii) to print * 20 times
(iii) to print = 40 times
(iv) to print = 30 times
(3 Marks)
(Ans)

(i) printchar()
(ii) printchar(*, 20)
(iii) printchar(=,40)
(iv) printchar(*, 30)
Write a function that interchanges the value of two integers A and B without
using any extra variable.
(4 Marks)
(Ans)

. //Function to swap A and B without using a third variable


void SWAP(int A, int B)
{
A=A+B
B = A - B;
A = A B;
cout << ntAfter swapping a is -> << A;
cout << ntAfter swapping a is -> << A;
getch();
}
Write a function which will take the height of a person in inches and return the
height in feet and inches in two separate variables.
(4 Marks)

(Ans)

//Function to convert the inch to feet


void feet_inch(int inch)
{
float feet;
feet = float(inch)/12; // Typecasting
cout << The persons height in inch is << inch << endl;
cout<< The persons height in feet is << feet;
}
Write a function which will take the height of a person in inches and return the
height in feet and inches in two separate variables.
(4 Marks)
(Ans)

//Function to convert the inch to feet


void feet_inch(int inch)
{
float feet;
feet = float(inch)/12; // Typecasting
cout << The persons height in inch is << inch << endl;
cout<< The persons height in feet is << feet;
}
Write a function to find the sum of series.
1+2+3+4+5+6+.upto N terms.
(4 Marks)
(Ans)

//Function to find the sum of series 1+2+3+..+N


int sumseries(int N)
{
int i, sum = 0;
for( i = 0; i< = N; i++)
sum = sum + i;
return(sum);
}

You might also like