Você está na página 1de 269

CBSE

CLASS – XII
OLD QUESTIONS & ANSWERS

Data Structures

C++
D

Ddat
Structured Query Language
Boolean Algebra
Communication concepts
Network concepts
G
C
T
S)
(P
ar
m
Ku

Prepared By:
er
nd

VIRENDER KUMAR
re
Vi

PGT COMPUTER SCIENCE

Jawahar navodaya vidyalaya

PEDAVEGsI, west Godavari dt., a.p


Dat coletd form the source web of cbse ,extramks .com, cbse guespar and
Model Test paers . htp/cbseni.o,xramk:d
w.examrco/CBSE-Pps,ybguid

XII Computer

1
XII COMPUTER SCIENCE
CBSE Board - 2013

[Time allowed: 3hours] [Maximum Marks: 70]


Instructions (i) All questions are compulsory
(ii) Programming Language: C++
1. (a) What is the benefit of using default parameter/argument in a function? Give a suitable example to illustrate it 2
using C++ code.
Ans The benefit of using default parameter/argument in a function are as following:
 They can be used to add new parameters to existing function.
 They can be used to combine similar function into one.
Example:
float intrest(float p, int t, float r = 0.10);
Now if any function call is appear as follows:
S_IN = intrest(5400, 2); // third argument missing
Here, the value 0.10 value is used for the third argument r.
(b) Observe the following C++ code and write the name(s) of the header file(s), which will be essentially required to run 1
it in a C++ compiler:
void main()
{
float Area, Side;
cin>>Area;
Side=sqrt(Area);
cout<<”One Side of the Square:”<<Side<<endl;
}
Ans. Following header files will be essentially required to run the above code in a C++ compiler:
1. iostream.h
2. math.h
(c) Observe the following C++ code carefully and rewrite the same after removing all the syntax error(s) 2
present in the code. Ensure that you underline each correction in the code.
Important Note:
- All the desired header files are already included, which are required to run the code.
- Correction should not change the logic of the program.
#define Change(A,B) 2*A+B;
void main()
{
Float X,Y,F;
cin>>X>>Y;
F=Change[X,Y];
cout<<”Result:”<<F<endline;
}
Ans. #define Change(A,B) 2*A+B;
void main()
{
float X,Y,F;
cin>>X>>Y;
F=Change(X,Y);
cout<<”Result:”<<F<<endl;
}
(d) Observe the following C++ code carefully and obtain the output, which will appear on the screen after 2
execution of it.

1|Page
Important Note:
- All the desired header files are already included in the code, which are required to run the code.
void main()
{
char *Text=”AJANTA”; int
*P, Num[]={1,5,7,9};
P=Num;
cout<<*P<<Text<<endl;
Text++;
P++;
cout<<*P<<Text<<endl;
}
Ans. Output:
1AJANTA
5JANTA
(e) Observe the following C++ code carefully and obtain the output, which will appear on the screen after 3
execution of it.
#include<iostream.h>
class Mausam
{
int City,Temp,Humidity;
public:
Mausam(int C=1) {City=C; Temp=10; Humidity=63;}
void Sun(int T) {Temp+=T;}
void Rain(int H) { Humidity+=H;}
void CheckOut()
{
cout<<City<<":"<<Temp<<"&"<<Humidity<<"%"<<endl;
}
};
void main()
{
Mausam M,N(2);
M.Sun(5);
M.CheckOut();
N.Rain(10);
N.Sun(2);
N.CheckOut();
M.Rain(15);
M.CheckOut();
}
Ans. Output:
1:15&63%
2:12&73%
1:15&78%
(f) Based on the following C++ code find out the expected correct output(s) from the option (i) to(iv). Also, find 2
out the minimum and the maximum value that can be assigned to the variable Guess used in the code at the
time when value of Turn is 3.
void main()
{
char Result[][10]={"GOLD","SILVER","BRONZE"};

2|Page
int Getit=9,Guess;
for(int Turn=1;Turn<4;Turn++)
{
Guess=random(Turn);
cout<<Getit-Guess<<Result[Guess]<<"*";
}
}
(i) 9GOLD*9GOLD*8SILVER*
(ii) 9GOLD*7BRONZE*8GOLD*
(iii) 9GOLD*8SILVER*9GOLD*
(iv) 9GOLD*8SILVER*8GOLD*
Ans. Correct answer is 9GOLD*9GOLD*8SILVER*
2. (a) Write any two similarities between Constructor and Destructor. Write the function headers for constructor and 2
destructor of a class Flight.
Ans. Similarities:
 Constructors and destructors do not have return type, not even void nor can they return values.
 References and pointers cannot be used on constructors and destructors because their addresses cannot be
taken.
For example:
class Flight
{
public:
Flight(); // Constructor for class Flight
~Flight(); // Destructor for class Flight
};
(b) Answer the questions (i) and (ii) after going through the following class: 2
class Race
{
int CarNo, Track;
public:
Race(); // Function 1
Race(int CN); // Function 2
Race(Race &R); // Function 3
void Register(); // Function 4
void Drive(); // Function 5
};
void main()
{
Race R;
:
}
(i) Out of the following, which of the option is correct for calling Function 2?
Option 1-Race T(30);
Option 2-Race U(R);
(ii) Name the feature of Object Oriented Programming, which is illustrated by Function 1, Function 2 and
Function 3 combined together.
Ans. (i) Option-1 Race T (30) is correct.
(ii) Constructor overloading.

3|Page
(c) Define a class Bus in C++ with the following specifications: 4
Data Members
 Busno - to store Bus No
 From – to store Place name of origin
 To – to store Place name of destination
 Type – to store Bus Type such as ‘O’ for ordinary
 Distance – to store the Distance in Kilometers
 Fare –to store the Bus Fare
Member Functions
 A constructor function to initialize Type as ‘O’ and Freight as 500
 A function CalcFare() to calculate Fare as per the following criteria:
Type Fare
‘O’ 15*Distance
‘E’ 20*Distance
‘L’ 24*Distance
 A function Allocate() to allow user to enter values for Busno, From, To, Type and Distance. Also,
this function should call CalcFare() to calculate Fare.
 A function Show() to display the content of all the data members on screen.
Ans. #include <iostream.h>
#include <conio.h>
class Bus
{
private:
char From[20],To[20];
int fare,busno,distance;
char Type;
public:
Bus ( );//Constructor
~Bus( );//Destructor
int CalcFare();
void Allocate();
void Show();
};
Bus :: Bus( )
{
fare=500;
Type='O';
}
void Bus :: Allocate( )
{
cout<<"Enter the Bus no: ";
cin>>busno;
cout<<"\nFrom: ";
cin>>From;
cout<<"\nTo: ";
cin>>To;
cout<<" \nEnter the Type: ";
cin>>Type;
cout<<"\nEnter the distance: ";
cin>>distance;
CalcFare();

4|Page
}
int Bus:: CalcFare( )
{
if(Type=='O')
{
fare=15*distance;
}
else if(Type=='E')
{
fare=20*distance;
}
else if(Type=='L')
{
fare=24*distance;
}
else
cout<<"Wrong Type";
return fare;
}
void Bus :: Show()
{
cout<<"\n\n****Your Booking Detail***"<<endl;
cout<<"Bus no: "<<busno<<endl;
cout<<"From: "<<From<<endl;
cout<<"To: "<<To<<endl;
cout<<"Type: "<<Type<<endl;
cout<<"Distance: "<<distance<<endl;
cout<<"Total Fare: "<<fare<<endl;
}
Bus :: ~Bus( )
{
cout<<"Bus Detail is Closed";
}
void main( )
{
Bus s;
clrscr();
s.Allocate();
s.Show();
getch( );
}
(d) Consider the following c++ code and answer the questions from (i) to (iv): 4
class Personal
{
int Class,Rno;
char Section;
protected:
char Name[20];
public:
personal(); void
pentry();
void Pdisplay();
};
class Marks: private Personal
{

5|Page
float M[5];
protected:
char Grade[5];
public:
Marks();
void Mentry();
void Mdisplay();
};
class Result: public Marks
{
float Total, Agg;
public:
char FinalGrade, comments[20];
Result();
void Rcalculate();
void Rdisplay();
};
(i) Which type of inheritance is shown in the above example?
(ii) Write the names of those data members, which can be directly accessed from the objects of
class Result.
(iii) Write the names of those member functions which can be directly accessed from the objects
of class Result.
(iv) Write names of those data members, which can be directly accessed from the Mentry()
function of class Marks.
Ans. (i) Multilevel Inheritance
(ii) FinalGrade, comments
(iii) Rcalculate(), Rdisplay(), Mentry(), Mdisplay();
(iv) Name[20], M[5], Grade[5]
3.(a) Write code for a function void ChangOver (int P[],int N) in C++, which re-positions all the elements of the array by 3
shifting each of them to the next position and by shifting the last element to the first position.
For example:If the content of array is
0 1 2 3 4
12 15 17 13 21

The changed content will be:


0 1 2 3 4
21 12 15 17 13
Ans. #include <iostream.h>
void ChangOver (int P[ ], int N);
int main (void)
{
int P[ ]= {1, 3, 5, 7, 9};
ChangOver ( P, 5);
for ( int i=0; i<5; i++)
{
cout << P[i] << ' ';
}
return(0);
}
void ChangOver (int P[ ], int N)
{
int temp;
int temp1;

6|Page
+ 55
(e) Write a function QDELETE() in C++ to perform delete operation on a Linked Queue, which contains Passenger 4
no and Passenger name. Consider the following definition of node in the code.
struct node
{
long int Pno;
char Pname[20];
node *Link;
};
Ans. class Queue
{
NODE *front, *rear;
Queue() {front=NULL; rear=NULL;}
public:
void Addq();
void Delete();
};
void Queue::Delete()
{
if(front==NULL)
cout<<”Queue is empty”;
else
{
NODE *t = front;
front = front->Link;
if(front==NULL)
rear = NULL;
delete t;
}
}
4 (a) Fill in the blanks marked as Statement 1 and Statement 2, in the program segment given below with 1
appropriate functions for the required task.
class Club
{
long int MNo; // Member Number
char MName[20]; // Member Name
char Email[30]; //Email of Member
public:
void Register(); // Function to register member
void Disp(); // Function to display details
void ChangeEmail() // Function to change Email
{
cout<<"Enter Changed Email:";
cin>>Email;
}
long int GetMno() { return MNo;}
};
void ModifyData()
{
fstream File;
File.open("CLUB.DAT",ios::binary|ios::in|ios::out);
int Modify=0,Position;
long int ModiMno;

8|Page
cout<<"Mno - whose email required to be modified:";
cin>>ModiMno;
Club CL;
while(!Modify && File.read((char*)&CL,sizeof(CL)))
{
if(CL.GetMno()==ModiMno)
{
CL.ChangeEmail();
Position=File.tellg()-sizeof(CL);
//Statement 1: To place file pointer to the required position
____________________________________;

//Statement 2: To write the object CL on to the binary file


______________________________________;
Modify++;
}
}
if(Modify)
cout<<"Email changed....."<<endl;
else
cout<<"Member not found...."<<endl;
File.close();
}
Ans. Statement 1:
File.seekp(Position);
Statement 2:
File.write((char*) &CL, sizeof(CL));
(b) Write a function CountYouMe() in C++ which reads the contents of a text file story.txt and counts the words 2
You and Me (not case sensitive).
For example, if the file contains:
You are my best friend.
You and me make a good team.
The function should display the output as
Count for You: 2
Count for Me: 1
Ans. #include<conio.h>
#include<iostream.h>
#include<fstream.h>
#include<string.h>
void COUNT()
{
ifstream Fil;
Fil.open("STORY.TXT");
char Word [80];
int C1=0, C2=0;
while (!Fil.eof())
{
Fil>>Word;
if(strcmp(Word,"You")==0)
C1++;
else if (strcmp(Word,"me") ==0)
C2++;
}
cout<<"Count for You:"<<C1<<endl;

9|Page
cout<<"Count for me:"<<C2;
Fil.close();
}
(c) Assuming the class ANTIQUE as declared below, write a function in C++ to read the objects of ANTIQUE 3
from binary file ANTIQUE.DAT and display those antique items, which are priced between 10000 and
15000.
class ANTIQUE
{
int ANO;
char Aname[10];
float Price;
public:
void BUY() { cin>>ANO;gets(Aname);cin>>price;}
void SHOW()
{
cout<<ANO<<endl;
cout<<Aname<<endl;
cout<<Price<<endl;
}
float GetPrice() { return Price;}
};
Ans void search(float pr)
{
Ifstream ifile(“ANTIQUE.DAT”, ios::in | ios::binary);
if(!ifile)
{
cout<<”could not open ANTIQUE.DAT file “; exit(-1); }
else
{
ANTIQUE a; int found=0;
while(ifile.read((char *)&a, sizeof(a)))
{
Pr=a.GetPrice();
if(pr>=10000 && pr<=15000)
{
a.SHOW(); found=1; break;
}
}
}
if(found==0)
cout<<”given price not match”;
}
5 (a) Explain the concept of candidate keys with the help of an appropriate example. 2
Note:
Write SQL queries for (b) to (g) and write the outputs for the SQL queries mentioned shown in (h1) to
(h4) parts on the basis of tables PRODUCTS and SUPPLIERS
Table: PRODUCTS
PID PNAME QTY PRICE COMPANY SUPCODE
101 DIGITAL CAMERA 14X 120 12000 RENIX S01
102 DIGITAL PAD 11i 100 22000 DIGI POP S02
104 PEN DRIVE 16 GB 500 1100 STOREKING S01
106 LED SCREEN 32 70 28000 DISPEXPERTS S02
105 CAR GPS SYSTEM 60 12000 MOVEON S03
Table: SUPPLIERS

Page 10 of 14
SUPCODE SNAME CITY
S01 GET ALL INC KOLKATA
S03 EASY MARKET CORP DELHI
S02 DIGI BUSY GROUP CHENNAI
Ans. A table may have more than one such attribute/group of attribute that identifies a tuple uniquely, all such
attribute(s) are known as Candidate Keys.

Candidate Key

(b) To display the details of all the products in ascending order of product names (i.e. PNAME). 1
Ans SELECT * FROM PRODUCTS ORDER BY PNAME;

(c) To display product name and price of all those products, whose price is in the range of 10000 and 15000 1
(both value inclusive).
Ans: select PNAME,PRICE FROM PRODUCTS WHERE PRICE>=10000 && PRICE<=15000;

(d) To display the number of products, which are supplied supplier. i.e., the expected output should be: 1
S01 2
S02 2
S03 1
Ans. SELECT SUPCODE, COUNT(SUPCODE) FROM PRODUCTS GROUP BY SUPCODE;
(e) To display the price, product name and quantity (i.e., qty) of those products which have quantity more 1
than 100.
Ans. SELECT PRICE,PNAME,QTY FROM PRODUCTS WHERE QTY>100;
(f) To display the names of those suppliers, who are either from DELHI or from CHENNAI. 1
Ans: SELECT SNAME FROM SUPPLIERS WHERE CITY="DELHI" || CITY="KOLKATA";
(g) To display the name of the companies and the name of the products in descending order of company 1
names.
Ans: SELECT COMPANY,PNAME FROM PRODUCTS ORDER BY COMPANY DESC;
(h) Obtain the outputs of the following SQL, queries based on the data given in tables PRODUCTS and 2
SUPPLIERS above.
(h1) SELECT DISTINCT SUPCODE FROM PRODUCTS;
(h2) SELECT MAX(PRICE), MIN(PRICE) FROM PRODUCTS;
(h3) SELECT PRICE*QTY AMOUNT FROM PRODUCTS WHERE PID=104;
(h4) SELECT PNAME,SNAME FROM PRODUCTS P, SUPPLIERS S WHERE P.SUPCODE=S.SUPCODE AND
QTY>100;
Ans: (h1) SUPCODE

Page 11 of 14
S01
S02
S03
(h2)
MAX(PRICE) MIN(PRICE)
28000 1100
(h3) AMOUNT
55000
(h4)
PNAME SNAME
DIGITAL CAMERA 14X GET ALL INC
PEN DRIVE 16GB GET ALL INC

6 (a) Verify the following using Boolean Laws X + Z = X + X’ . Z + Y . Z 2

IMPORTANT NOTE: This question was wrong in board paper expected question may this X+Z=X+Y'.Z+Yy.Z
Ans. x+z=x+y'.z+y.z
RHS=x+y'.z+y.z
=x+z(y'+y) (y'+y=1 Complementarity law)
=x+z(1)
=x+z
=LHS
(b) Obtain the Boolean Expression for the logic circuit shown below: 2

Ans. The equivalent Boolean expression for the given Logic Circuit is: F = P’Q + (Q + R’)
(c) Write the Sum of Product form of the function F(A, B, C) for the following truth table representation of F. 1
A B C F
0 0 0 0
0 0 1 0
0 1 0 1
0 1 1 1
1 0 0 1
1 0 1 0
1 1 0 0
1 1 1 1
Ans. Add a new column containing minterms. Now the table is as follows :
A B C F minterms
0 0 0 0 A’B’C’
0 0 1 0 A’B’C
0 1 0 1 A’BC’
0 1 1 1 A’BC

Page 12 of 14
1 0 0 1 AB’C’
1 0 1 0 AB’C
1 1 0 0 ABC’
1 1 1 1 ABC
Now by adding all the minterms for which output is 1, we get desired sum-of-products expression which is
F(A,B,C) = A’BC’ + A’BC + AB’C’ + ABC
(d) Obtain the minimal form for the following Boolean expression using Karnaugh map. 3
F(U, V, W, Z) = ∑(0, 1, 2, 3, 6, 7, 8, 9, 10, 13, 15)
Ans. There are four pairs and one quad that reduce as given below:
Pair-1(m7 + m6) reduces to U’VW
Pair-2(m8 + m9) reduces to UV’W’
Pair-3(m13 + m15) reduces to UVZ
Pair-4(m8 + m10) reduces to UV’Z’
Quad (m0 + m1 + m2 + m3) reduces to U’V’
Simplified Boolean expression for given K-map is
F(U,V,W,Z) = U’VW + A’C’O + UVZ + UV’Z’ + U’V’

7. (a) Write two advantages of using an optical fiber cable over an Ethernet cable to connect two service stations, 1
which are 200 m away from each other.
Ans.  Optical fiber cable guarantees secure transmission and a very high transmission capacity.
 Optical fiber cable is immune to electrical and magnetic interference.
(b) What is the different between HTTP and FTP? 1
Ans. FTP, is a protocol used to upload files from a workstation to a FTP server or download files from a FTP server to
a workstation whereas, HTTP, is a protocol used to transfer files from a Web server onto a browser in order to
view a Web page that is on the Internet.
Rovenza Communication International (RCI) is an online corporate training provider company for IT related courses.
The company is setting up their new campus in Kolkata. You as a network expert have to study the physical locations
of various blocks and the number of computers to be installed. In the planning phase, provider the best possible
answer for the queries (i) to (iv) raised by them.

Block to Block distances (in Mtrs.)


From To Distan
ce
Administrative Block Finance Block 60
Administrative Block Faculty Recording Block 120
Finance Block Faculty Recording Block 70
Expected Computers to be installed in each block

Page 13 of 14
Block Computers
Administrative Block 30
Finance Block 20
Faculty Recording Block 100
(i) Suggest the most appropriate block, where RCI should plan to install the server.
(ii) Suggest the most appropriate block to block cable layout to connect all three blocks for efficient
communication.
(iii) Which type of network out of the following is formed by connecting the computers of these
three blocks?
 LAN
 MAN
 Wam
(iv) Which wireless channel out of the following should be opted by RCI to connect to students from
all over the world?
 Infrared
 Microwave
Satellite
Ans. (i) Faculty recording block
(i)

(ii) LAN
(iii) Satellite
(d) Write two advantages of using open source software over proprietary software. 1
Ans.  Open Source Software is software whose source code is available to customer and it can be modified and
redistributed without any limitations whereas source code of proprietary Software is not available.
 Open Source Software may come free of cost or with a payment of normal charges whereas proprietary
software is neither open nor freely available.
(e) Which of the following crime(s) does not come under cybercrime? 1
(i) Copying some important data from a computer without taking permission from the owner of the
data.
(ii) Stealing keyboard and mouse from a shop.
(iii) Getting into unknown person’s social networking account and start messaging on his behalf.
Ans. (i) Stealing keyboard and mouse from a shop.

Page 14 of 14
XII COMPUTER SCIENCE
CBSE Board - 2012

[Time allowed: 3hours] [Maximum Marks: 70]


Instructions (i) All questions are compulsory
(ii) Programming Language: C++
1. (a) Give the difference between the type casting and automatic type conversion. Also, give a suitable C++ code to 2
illustrate both.
Ans. Type casting Automatic Type conversion
 Type Casting is used to convert  Automatic Type Conversion is the type conversion done
value of one type to another type by the compiler wherever required.
 for example  for example
float x=(float) 3 / 2; float x=3/2;
// 1.5 will be assigned as result, //here 1.0 will be assigned as result, because 1 is
because 3 is converted into 3.0 automatically converted in 1.0
(b) Which C++ header file(s) are essentially required to be included to run/execute the following C++ source code(Note: Do 1
not include any header file, which is/are not required):
void main()
{
char TEXT[]=”SomeThing”;
cout<<”Remaining SMS Chars :”<<160-strlen(TEXT)<<endl;
}
Ans. i. iostream.h
ii. string.h
(c) Rewrite the following program after removing the syntactical error(s) (if any). Underline each correction. 2
#include <iostream.h>
Class Item
{
long IId,Qty;
public:
void Purchase{cin>>IId>>Qty;}
void Sale()
{
cout<<setw(5)<<IId<<” Old:”<<Qty<<endl;
cout<<”New:”<<--Qty<<endl;
}
};
void main( )
{
Item I;
Purchase();
I.Sale();
I.Sale()
}
Ans. #include <iostream.h>
#include <iomanip.h>
class Item
{
long IId,Qty;
public:
void Purchase(){cin>>IId>>Qty;}
1|Page
void Sale()
{
cout<<setw(5)<<IId<<” Old:”<<Qty<<endl;
cout<<”New:”<<--Qty<<endl;
}
};
void main( )
{
Item I;
I.Purchase();
I.Sale();
I.Sale();
}
(d) Find the output of the following program: 3
#include<iostream.h>
class METRO
{
int Mno,TripNo,PassengerCount;
public:
METRO(int Tmno=1)
{
Mno=Tmno;TripNo=0;PassengerCount=0;
}
void Trip(int PC=20)
{
TripNo++;PassengerCount+=PC;
}
void StatusShow()
{
cout<<Mno<<”:”<<TripNo<<”:”<<PassengerCount<<endl;
}
};
void main()
{
METRO M(5),T;
M.Trip();
T.Trip(50);
M.StatusShow();
M.Trip(30);
T.StatusShow();
M.StatusShow();
}
Ans. 5:1:20
1:1:50
5:2:50
(e) Find the output of the following program : 2
#include<iostream.h>
#include<ctype.h>
typedef char Str80[80];
void main( )
{
char *Notes;
Str80 Str=”vR2GooD”;
2|Page
int L=6;
Notes=Str;
while(L>=3)
{
Str[L]=(isupper(Str[L])?tolower(Str[L]):toupper(Str[L]));
cout<<Notes<<endl;
L--;
Notes++;
}
}
Ans. vR2Good
R2GoOd
2GOOd
gOOd
(f) Observe the following program and find out, which output(s) out of(i) to(iv) will not be expected from the 2
program? What will be the minimum and the maximum value assigned to the variable chance?
#include<iostream.h>
#include<stdlib.h>
void main( )
{
randomize( );
int Arr[]={9,6},N;
int Chance=random(2)+10;
for (int C=0;C<2;C++)
{
N=random(2);
cout<<Arr[N]+Chance<<”#”;
}
}
(i) 9#6# (ii) 19#17# (iii) 19#16# (iv) 20#16#
Ans. (iii) 19#16#
Minimum Value: 16
Maximum Value: 20
2. (a) What is the difference between the members in private visibility mode and the members in protected visibility mode 2
inside a class? Also, give a suitable C++ code to illustrate both.
Ans.
Private Protected
Private members of a class are accessible only from within Protected members are accessible from members of their
other members of the same class or from their friends. same class and from their friends, but also from members
of their derived classes.
Example Example
#include <iostream> #include <iostream.h>
class Example class ExBase
{ {
public: protected:
int a; int i, j;
int add(); };
private:
int b; class ExDerived : public ExBase {
}; public:
int Example::add() void show()
{ {

3|Page
return a+b ; i=35;
} j=45;
void main( ) //both i & j are accessible here
{ cout<<"Value of i "<<i;
Example ex; cout<<"Value of j "<<j;
ex.a = 10; // OK: because a is }
public };
ex.b = 20; // Error: because b is void main()
private {
int sum=ex.add(); // local ExDerived exd;
variable exd.show();
cout << "Sum of a + b : " << //both I and j are not accessible
} exd.i=50;
Output: Error due to access of exd.j=60;
private member }

(b) Answer the question (i) and (ii) after going through the following class : 2
class Travel
{
int PlaceCode; char Place[20]; float Charges;
public:
Travel( ) //Function 1
{
PlaceCode=1;strcpy(Place,”DELHI”);Charges=1000;
}
void TravelPlan(float C ) // Function 2
{
cout<<PlaceCode<<“:”<<Place<<”:”<<Charges<<endl;
}
~Travel( ) // Function 3
{
cout<<”Travel Plan Cancelled”<<endl;
}
Travel(int PC,char p[],float C) // Function 4
{
PlaceCode=PC;strcpy(Place,P);Charges=c;
}
};
i) In Object Oriented Programming, what are Function 1 and Function 4 combined together referred as?
ii) In Object Oriented Programming, which concept is illustrated by Function 3? When is this function
called/invoked?
Ans. (i) Polymorphism OR Constructor Overloading
(ii) Function 3: Destructor
A destructor called/invoked when an object of that class is destroyed. When a variable goes out of scope,
or a dynamically allocated variable is explicitly deleted using the delete keyword, the class destructor is
called to help clean up the class before it is removed from memory.
(c) Define a class RESTRA in C++ with following description: 4
Private Members:
 FoodCode of type int
 Food of type string
 FType of type string
 Sticker of type string
 A member function GetSticker() to assign the following values for Sticker as per the given Ftype:

4|Page
FType Sticker
Vegetarian GREEN
Contains Egg YELLOW
Non-Vegetarian RED
Public Members :
 A function GetFood() to allow user to enter values for FoodCode, Food,Ftype and call function
GetSticker() to assign Sticker.
 A function ShowFood() to allow user to view the concept of all the data members.
Ans. class RESTRA
{
int FoodCode;
char Food[20];
char FType[20];
char Sticker[20];
void GetSticker();
public:
void GetFood();
void ShowFood();
};
void RESTRA::GetFood()
{
cin>>FoodCode;
cin>>Food;
cin>>FType;
GetSticker ();
}
void RESTRA:: GetSticker ()
{
if (strcmp(FType,"Vegetarian"))
strcpy(Sticker,"GREEN");
else if (strcmp(FType,"Contains Egg"))
strcpy(Sticker,"YELLOW");
else if(strcmp(FType,"Non-Vegetarian"))
strcpy(Sticker,"RED");
}
void RESTRA:: ShowFood ()
{
cout<< FoodCode <<'\t'<<Food<<'\t'<<FType<<'\t'<<Sticker<<endl;
}
(d) Answer the questions (i) to (iv) based on the following: 4
class COMPANY
{
char Location[20];
double Budget,Income;
protected:
void Accounts( );
public:
COMPANY();
void Register( );
void Show( );
};
class FACTORY: public COMPANY
{
5|Page
char Location[20];
int Workers;
protected:
double Salary;
void Computer();
public:
FACTORY();
void Enter( );
void show( );
};
class SHOP: private COMPANY
{
char Location[20];
float Area;
double Sale;
public:
SHOP();
void Input();
void Output();
};
(i) Name the type of inheritance illustrated in the above C++ code.
(ii) Write the names of data members, which are accessible from member functions of class SHOP.
(iii) Write the names of all the member functions, which are accessible from objects belonging to class
FACTORY.
(iv) Write the names of all the members, which are accessible from objects of class SHOP.
Ans. (i) Hierarchical Inheritance
(ii) None of the data members can be accessible except SHOP class data members.
(iii) Register( ),Enter( ) and Show( ) of Factory class.
(iv) Input( ), Output( )
3. ( a ) Write a function SWAP2BEST (int ARR[],int Size) in C++ to modify the content of the array in such a way that the 3
elements, which are multiples of 10 swap with the value present in the very next position in the array.
For example:
If the content of array ARR is
90,56,45,20,34,54
The content of array ARR should become
56,90,45,34,20,54
Ans. #include <iostream.h>
#include <conio.h>
void SWAP2BEST(int ARR[], int Size);
int main ()
{
//Here we are taking different values for more perfect result with more
//numbers of array elements. You can change the values and number of array
//elements as per your choice.
int ListofNum[8] = {6, 28, 30, 17, 50, 45, 80, 82};
clrscr();
SWAP2BEST(ListofNum, 8 ) ;
return 0;
}
void SWAP2BEST(int ARR[], int Size)
{
int i= 0;
int temp=0;

6|Page
for (i = 0; i < Size; ++i)//loop for printing original array values
{
cout<<ARR[i]<<" ";
}
cout<<endl;
for (i = 0; i < Size; ++i)
{
if(ARR[i+1]=='\0')
{
}
else
{
if(ARR[i+1]%10==0)
{
temp=ARR[i];
ARR[i]=ARR[i+1];
ARR[i+1]=temp;
}
}
}
for (i = 0; i < Size; ++i) //loop for printing swapped array value
{
cout<<ARR[i]<<" ";
}
}
(b) An array T[20][10] is stored in the memory along the column with each of the element occupying 2 bytes, find 3
out the memory location of T[10][5], if an element T[2][9] is stored at location 7600.

Ans. AssumingLBR=LBC=0
B=7600
W=2 bytes
Number of Rows(N)=20
Numberof Columns(M)=10
LOC(Arr[I] [J]) = B +(I + J*N)*W
LOC(T[10][5]) = 7600+(10+5*20)*2
= 7600 + (300*2)
= 7600 + 600
= 8200

(c) Write a function in C++ to perform insert operation in a static circular Queue containing Book’s information 4
(represented with the help of an array of structure BOOK).
struct BOOK
{
long Accno; // Book Accession Number
char Title[20]; // Book Title
};
Ans. Student try to answer this question

(d) Write a function ALTERNATE (int A[][3],int N,int M) in C++ to display all alternate element 2
from two-dimensional array A (starting from A[0][0]).
For example:
If the array is containing:
23 54 76

7|Page
37 19 28
62 13 19
The output will be:
23 76 19 62 19
Ans. #include <iostream.h>
#include <conio.h>
void process_Array(int Arr[][3],int x, int y);
void process_Array(int A[][3],int N, int M)
{
clrscr();
for (int R = 0; R < N; R++)
{
if(R%2==0)
{
for (int C = 0; C < M; C=C+2)
{
cout<< A[R][C]<<" ";
}
}
else
{
for (int C = 1; C < M;C=C+2)
{
cout<< A[R][C]<<" ";
}
}
}
cout<<endl;
cout<<endl;
for (int I = 0; I < N; I++)
{
for (int J = 0; J < M; J++)
{
cout << A[I][J]<<" ";
}
cout<<endl;
}
}
int main ()
{
int arr[3][3] ={{23, 54, 76},
{37, 19, 28},
{62, 13, 19},
};
process_Array(arr,3,3);
return 0;
}
(e) Evaluate the following POSTFIX notation. Show status of stack after every step of evaluation (i.e. after each 2
operator):
True,False,NOT,AND,False,True,OR,AND
Ans. Student try to answer this question
4 (a) Observe the program segment given below carefully and the question that follow: 1
class Stock
8|Page
{
int Ino,Qty; char Item[20];
public:
void Enter() {cin>>In0;gets(Item); cin>>Qty;}
void Issue(int Q) { Qty+=Q}
void Purchase(int Q) { Qty-=Q}
int GetIno(return Ino;}
};
void Purchaseitem(int Pino, int PQty)
{
fstream file;
File.open(“STOCK.DAT”,ios::binary|ios::in|ios::out);
Stock S;
int Success=0;
while (Success==0 && File.read((char*)&S, sizeof(S)))
{
if (Pino==S.GetIno())
{
S.Purchase(PQty);
File.seekp(Success); //Statement 1
File.write((char*) &S, sizeof(S)); //statement 2
Success++;
}
}
if (Success==1)
cout<<“Purchase Updated”<<endl;
else
cout<<”Wrong Item No”<<endl;
File.close( );
}
(i) Write statement 1 to position the file pointer to the appropriate place, so that the data updation is
done for the required item.
(ii) Write statement 2 to perform the write operation so that the updation is done in the binary file.
Ans. Statement 1 - File.seekp(Success);
Statement 2 - File.write((char*) &S, sizeof(S));
(b) Write a function in C++ to read the content of a text file “DELHI.TXT” and display all those lines on screen, 2
which are either starting with ‘D’ or starting with ‘M’.
Ans. #include<fstream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("out.txt");
char str[80]; int count=0;
clrscr();
while(!fin.eof())
{
fin.getline(str,80);
if(str[0]=='D' || str[0]=='M')
{
cout<<str<<endl;
}
count++;
}
9|Page
cout<<"Number of lines in file is "<<count;
fin.close();
getch();
return 0;
}
(c) Write a function in C++ to search for the details (Phoneno and Calls) of those Phones, which have more 3
than 800 calls from a binary file “phones.dat”. Assuming that this binary file contains records/objects of
class Phone, which is defined below.
class Phone
{
char Phoneno[10]; int Calls;
public:
void Get( ) { gets(Phoneno); cin>>Calls; }
void Billing( ) { cout<<Phoneno<<”#”<<Calls<<endl; }
int GetCalls( )
{
return Calls;
}
};
(Ans) void search ()
{
Phone pObj;
ifstream ifs;
ifs.open("phones.dat",ios::binary);
while(ifs.read((char*)&pObj,sizeof(pObj)))
{
if(pObj.GetCalls()>=800)
pObj.Billing();
}
ifs.close();
}
5 (a) Give a suitable example of a table with sample data and illustrate Primary and Alternate Keys in it. 2
Ans. Primary Key: Primary key is a set of one or more fields/columns of a table that uniquely identify a record in
database table. It cannot accept null, duplicate values. Only one Candidate Key can be Primary Key.
Alternate key: Alternate key is a key that can be work as a primary key. Basically it is a candidate key that
currently is not primary key.
Example: In below table AdmissionNo becomes Alternate Keys when we define RegistrationNo as Primary Key.
Student Registration Table:
RegistrationNo AdmissionNo Name Phone Gender DOB
CBSE4554 215647 Mihir Ranjan 9568452325 Male 1992-04-15
CBSE6985 265894 Amita Guha 8456985445 Female 1993-03-24
CBSE5668 458961 Rajesh Singh 9654212440 Male 1992-12-04
CBSE3654 469799 Mohit Patel 7421589652 Male 1992-05-16
Primary Key – Registration Number
Alternate Key –Admission No
Consider the following tables CARDEN and CUSTOMER and answer (b) and (c) parts of question:
TABLE: CARDEN
Ccode CarName Make Color Capacity Charges
501 A-Star Suzuki RED 3 14
503 Indigo Tata SILVER 3 12
502 Innova Toyota WHITE 7 15
509 SX4 Suzuki SILVER 4 14

10 | P a g e
510 C Class Mercedes RED 4 35
TABLE: CUSTOMER
CCode Cname Ccode
1001 Hemant Sahu 501
1002 Raj Lal 509
1002 Feroza Shah 503
1004 Ketan Dhal 502
Write SQL commands for the following statements: 4
(b) (i) To display the names of all the silver colored Cars.
(ii) To display name of car, make and capacity of cars in descending order of their sitting capacity.
(iii) To display the highest charges at which a vehicle can be hired from CARDEN.
(iv) To display the customer name and the corresponding name of the cars hired by them.
Ans. (i) SELECT CarName FROM carden WHERE Color LIKE 'Silver';
(ii) SELECT CarName,Make,Capacity FROM carden ORDER BY Capacity;
(iii) SELECT MAX(Charges) FROM carden;
(iv) SELECT Cname,CarName FROM carden,customer WHERE
carden.Ccode=customer.Ccode;
(c) Give the output of the following SQL queries: 2
(i) SELECT COUNT(DISTINCT Make) FROM CARDEN;
(ii) SELECT MAX(Charges),MIN(Charges) FROM CARDEN;
(iii) SELECT COUNT(*),Make FROM CARDEN;
(iv) SELECT CarName FROM CARDEN WHERE Capacity=4;
Ans. (i) COUNT(DISTINCT Make)
4
(ii) MAX(Charges)
MIN(Charges) 35 12
(iii) COUNT(*) Make
5 Suzuki
(iv) CarName
SX4
C Class
6 (a) Verify the following using truth table: 2
(i) X.X’=0
(ii) X+1=1
Ans.
X X’ X.X’ X+1
0 1 0 1
0 1 0 1
1 0 0 1
1 0 0 1
(b) Write the equivalent Boolean Expression for the following Logic Circuit: 2

11 | P a g e
X Y Z F
0 0 0 1
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

12 | P a g e
Ans.  Easy to extend
 In star topology, 4 computers can be connected with each other through a server.

(e) Workalot consultants are setting up a secured network for their office campus at Gurgaon for their day-to-day 4
office and web-based activities. They are planning to have connectivity between 3 buildings and the head office
situated in Mumbai. Answer the questions (i) to(iv) after going through the building positions in the campus
and other details, which are given below:

(i) Suggest the most suitable place (i.e. building) to house the server of this organization. Also give a reason
to justify your suggested location.
(ii) Suggest a cable layout of connection between the buildings inside the campus.
(iii) Suggest the placement of the following device with justification:
(1) Switch
(2) Repeater
(iv) The organization is planning to provide a high speed link with its head office situated in MUMBAI using a
wired connection. Which of the following cables will be most suitable for this job?
(1) Optical Fiber
(2) Co-axial Cable
(3) Ethernet Cable

13 | P a g e
Ans. RED building because maximum number of computers are there
(ei) OR
BLUE building because closest to all other building (minimum cable length required)
Ans.
(eii) Gurgaon Campus
Building
“GREEN”

Building Building
“BLUE” “RED”

Ans. Switch. By using 1 switch per building we can use maximum numbers of computers to connect them in
(eiii) network.
Ans. Optical Fiber
(eiv)
(f) Give one suitable example of each URL and Domain Name. 1
Ans. URL - http://www.cbsecsnip.in/index.php
Domain - cbsecsnip
(g) Name two Proprietary software along with their application. 1
Ans. (i) Microsoft Office – Microsoft Office belongs to Microsoft Corporation. This software is used for office
automation and also can be used other than office productivity at personal level. Microsoft Office contains
following other applications like Microsoft Word, Microsoft Excel, Microsoft PowerPoint, etc.
(ii) Oracle – Oracle Corporation is the owner of Oracle software. Oracle is one of most popular RDBMS
software in world.

14 | P a g e
COMPUTER SCIENCE
Sample Paper – I

Time allowed: 3 hours Max. Marks: 70


Instructions: (i) All the questions are compulsory.
(ii) Programming Language: C++

1.
(a) What is the difference between Object Oriented Programming and Procedural
Programming? 2

(b) Write the names of the header files to which the following belong: 1
(i) frexp() (ii) isalnum()

(c) Rewrite the following program after removing the syntactical errors (if any). Underline
each correction. 2

#include <iostream.h>
struct Pixels
{ int Color,Style;}
void ShowPoint(Pixels P)
{ cout<<P.Color,P.Style<<endl;}
void main()
{
Pixels Point1=(5,3);
ShowPoint(Point1);
Pixels Point2=Point1;
Color.Point1+=2;
ShowPoint(Point2);
}

(d) Find the output of the following program: 3


#include <iostream.h>
void Changethecontent(int Arr[], int Count)
{
for (int C=1;C<Count;C++)
Arr[C-1]+=Arr[C];
}
void main()
{
int A[]={3,4,5},B[]={10,20,30,40},C[]={900,1200};
Changethecontent(A,3);
Changethecontent(B,4);
Changethecontent(C,2);
for (int L=0;L<3;L++) cout<<A[L]<<’#’;
cout<<endl;
for (L=0;L<4;L++) cout<<B[L] <<’#’;
cout<<endl;
for (L=0;L<2;L++) cout<<C[L] <<’#’;
}

(e) Find the output of the following program: 2

1
#include <iostream.h>
struct Game
{
char Magic[20];int Score;
};
void main()
{
Game M={“Tiger”,500};
char *Choice;
Choice=M.Magic;
Choice[4]=’P’;
Choice[2]=’L’;
M.Score+=50;
cout<<M.Magic<<M.Score<<endl;
Game N=M;
N.Magic[0]=’A’;N.Magic[3]=’J’;
N.Score-=120;
cout<<N.Magic<<N.Score<<endl;
}

(f) In the following program, if the value of N given by the user is 20, what maximum and
minimum values the program could possibly display? 2

#include <iostream.h>
#include <stdlib.h>
void main()
{
int N,Guessnum;
randomize();
cin>>N;
Guessnum=random(N-10)+10;
cout<<Guessnum<<endl;
}
2.
(a) What do you understand by Polymorphism? Give a suitable example of the same. 2

(b) Answer the questions (i) and (ii) after going through the following program: 2
class Match
{
int Time;
public:
Match() //Function 1
{
Time=0;
cout<<”Match commences”<<end1;
}
void Details() //Function 2
{
cout<<”Inter Section Basketball Match”<<end1;
}

Match(int Duration) //Function 3


{
Time=Duration;
cout<<”Another Match begins now”<<end1;
}

2
Match(Match &M) //Function 4
{
Time=M.Duration;
cout<<”Like Previous Match ”<<end1;
}

};

i) Which category of constructor - Function 4 belongs to and what is the purpose of


using it?

ii) Write statements that would call the member Functions 1 and 3

(b) Define a class in C++ with following description: 4


Private Members
 A data member Flight number of type integer
 A data member Destination of type string
 A data member Distance of type float
 A data member Fuel of type float
 A member function CALFUEL() to calculate the value of Fuel as per the following
criteria
Distance Fuel
<=1000 500
more than 1000 and <=2000 1100
more than 2000 2200
Public Members
 A function FEEDINFO() to allow user to enter values for Flight Number,
Destination, Distance & call function CALFUEL() to calculate the quantity of Fuel
 A function SHOWINFO() to allow user to view the content of all the data
members

(c) Answer the questions (i) to (iv) based on the following: 4


class CUSTOMER
{
int Cust_no;
char Cust_Name[20];
protected:
void Register();
public:
CUSTOMER();
void Status();
};
class SALESMAN
{
int Salesman_no;
char Salesman_Name[20];
protected:
float Salary;
public:
SALESMAN();
void Enter();
void Show();
};
class SHOP : private CUSTOMER , public SALESMAN
{
char Voucher_No[10];

3
char Sales_Date[8];
public:
SHOP();
void Sales_Entry();
void Sales_Detail();
};

(i) Write the names of data members which are accessible from objects belonging to
class CUSTOMER.
(ii) Write the names of all the member functions which are accessible from objects
belonging to class SALESMAN.
(iii) Write the names of all the members which are accessible from member functions of
class SHOP.
(iv) How many bytes will be required by an object belonging to class SHOP?

3.
(a) Write a function in C++ to combine the contents of two equi-sized arrays A and B by
computing their corresponding elements with the formula 2*A[i]+3*B[i]; where value i
varies from 0 to N-1 and transfer the resultant content in the third same sized array.
4

(b) An array P[20][30] is stored in the memory along the column with each of the element
occupying 4 bytes, find out the memory location for the element P[5][15], if an element
P[2][20] is stored at the memory location 5000. 4

(c) Write a function in C++ to perform Push operation on a dynamically allocated Stack
containing real numbers. 4

(d) Write a function in C++ to find sum of rows from a two dimensional array. 2

(e) Evaluate the following postfix notation of expression: 2


True, False, AND, True, True, NOT, OR, AND

4.
(a) Observe the program segment given below carefully and fill the blanks marked as
Statement 1 and Statement 2 using seekg() and tellg() functions for performing the
required task. 1

#include <fstream.h>
class Employee
{
int Eno;char Ename[20];
public:
//Function to count the total number of records
int Countrec();
};
int Item::Countrec()
{
fstream File;
File.open(“EMP.DAT”,ios::binary|ios::in);
______________________ //Statement 1

int Bytes = ______________________ //Statement 2

int Count = Bytes / sizeof(Item);


File.close();

4
return Count;
}

5
(b) Write a function in C++ to count the number of alphabets present in a text file
“NOTES.TXT”. 2

(b) Write a function in C++ to add new objects at the bottom of a binary file
“STUDENT.DAT”, assuming the binary file is containing the objects of the following class.
3
class STUD
{
int Rno;
char Name[20];
public:
void Enter(){cin>>Rno;gets(Name);}
void Display(){cout<<Rno<<Name<<endl;}
};

void Addnew()
{
fstream FIL;
FIL.open(“STUDENT.DAT”,ios::binary|ios::app);
STUD S;
char CH;
do
{
S.Enter();
FIL.write((char*)&S,sizeof(S));
cout<<”More(Y/N)?”;cin>>CH;
}
while(CH!=’Y’);
FIL.close();
}

5.
(a) What do you understand by Primary Key & Candidate Keys? 2

(b) Consider the following tables GAMES and PLAYER. Write SQL commands for the
statements (i) to (iv) and give outputs for SQL queries (v) to (viii) 6

Table: GAMES
GCode GameName Number PrizeMoney ScheduleDate
101 Carom Board 2 5000 23-Jan-2004
102 Badminton 2 12000 12-Dec-2003
103 Table Tennis 4 8000 14-Feb-2004
105 Chess 2 9000 01-Jan-2004
108 Lawn Tennis 4 25000 19-Mar-2004

Table: PLAYER
PCode Name Gcode
1 Nabi Ahmad 101
2 Ravi Sahai 108
3 Jatin 101
4 Nazneen 103

(i) To display the name of all Games with their Gcodes

6
(ii) To display details of those games which are having PrizeMoney more than 7000.

(iii) To display the content of the GAMES table in ascending order of ScheduleDate.

(iv) To display sum of PrizeMoney for each of the Number of participation groupings (as
shown in column Number 2 or 4)

(v) SELECT COUNT(DISTINCT Number) FROM GAMES;

(vi)SELECT MAX(ScheduleDate),MIN(ScheduleDate) FROM GAMES;

(vii) SELECT SUM(PrizeMoney) FROM GAMES;

(viii) SELECT DISTINCT Gcode FROM PLAYER;

6.
(a) State and algebraically verify Absorbtion Laws. 2

(b) Write the equivalent Boolean Expression for the following Logic Circuit 2

(c) Write the SOP form of a Boolean function G, which is represented in a truth table as
follows: 1

P Q R G
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 1
1 1 1 1

7
(d) Reduce the following Boolean Expression using K-Map: 3
F(U,V,W,Z)=(0,1,2,4,5,6,8,10)

7.
a) Define the term Bandwidth. Give unit of Bandwidth. 1

b) Expand the following terminologies: 1


(i) HTML (ii) XML

c) Define the term firewall. 1

d) What is the importance of URL in networking? 1

e)
Ravya Industries has set up its new center at Kaka Nagar for its office and web
based activities. The company compound has 4 buildings as shown in the
diagram below:

Fazz
Raj
Building
Building

Jazz
Harsh Building
Building

Center to center distances between various buildings is as follows:


Harsh Building to Raj Building 50 m
Raz Building to Fazz Building 60 m
Fazz Building to Jazz Building 25 m
Jazz Building to Harsh Building 170 m
Harsh Building to Fazz Building 125 m
Raj Building to Jazz Building 90 m

Number of Computers in each of the buildings is follows:


Harsh Building 15
Raj Building 150
Fazz Building 15
Jazz Bulding 25

e1) Suggest a cable layout of connections between the buildings. 1

e2) Suggest the most suitable place (i.e. building) to house the server of this
organisation with a suitable reason. 1

8
e3) Suggest the placement of the following devices with justification: 1
(i) Internet Connecting Device/Modem
(ii) Switch

e4) The organisation is planning to link its sale counter situated in various parts of
the same city, which type of network out of LAN, MAN or WAN will be
formed? Justify your answer. 1

9
Computer Science (Code 083)
Sample Paper with Solution Set –I
Max. Marks: 70 Duration: 3 Hours
1.
(a) What is the difference between Object Oriented Programming and Procedural
Programming? 2

Answer:
Object Oriented Programming Procedural Programming
 Emphasis on Data  Emphasis on doing things (functions)
 Follows Bottom-Up approach in  Follows Top-down approach in
program design program design
 Data hiding feature prevents accidental  Presence of Global variables
change in data increase chances of accidental
change in data
 Features like data encapsulation,  Such features are not available
polymorphism, inheritance are present

(1/2 Mark for each point of difference – to maximum of 2 marks)

(d) Write the names of the header files to which the following belong: 1
(i) frexp() (ii) isalnum()
Answer:
(i) math.h (ii) ctype.h

(1/2 Mark for mentioning name of each header file)

(e) Rewrite the following program after removing the syntactical errors (if any). Underline
each correction. 2

#include <iostream.h>
struct Pixels
{ int Color,Style;}
void ShowPoint(Pixels P)
{ cout<<P.Color,P.Style<<endl;}
void main()
{
Pixels Point1=(5,3);
ShowPoint(Point1);
Pixels Point2=Point1;
Color.Point1+=2;
ShowPoint(Point2);
}
Answer:
#include <iostream.h>
struct Pixels
{ int Color,Style;};
void ShowPoint(Pixels P)
{ cout<<P.Color<<P.Style<<endl;}
void main()
{
Pixels Point1={5,3};
ShowPoint(Point1);
Pixels Point2=Point1;

10
Point1.Color+=2;
ShowPoint(Point2);
}

(1/2 Mark for correcting each error)


OR
(1 Mark for identifying all the 4 errors with no correction)

(d) Find the output of the following program: 3


#include <iostream.h>
void Changethecontent(int Arr[], int Count)
{
for (int C=1;C<Count;C++)
Arr[C-1]+=Arr[C];
}
void main()
{
int A[]={3,4,5},B[]={10,20,30,40},C[]={900,1200};
Changethecontent(A,3);
Changethecontent(B,4);
Changethecontent(C,2);
for (int L=0;L<3;L++) cout<<A[L]<<’#’;
cout<<endl;
for (L=0;L<4;L++) cout<<B[L] <<’#’;
cout<<endl;
for (L=0;L<2;L++) cout<<C[L] <<’#’;
}
Answer:
7#9#5#
30#50#70#40#
2100#1200#
(1 Mark for each correct line of output)
Note:
Deduct ½ Mark for not showing : in the output
Deduct ½ Mark for not considering endl

(e) Find the output of the following program: 2


#include <iostream.h>
struct Game
{
char Magic[20];int Score;
};
void main()
{
Game M={“Tiger”,500};
char *Choice;
Choice=M.Magic;
Choice[4]=’P’;
Choice[2]=’L’;
M.Score+=50;
cout<<M.Magic<<M.Score<<endl;
Game N=M;
N.Magic[0]=’A’;N.Magic[3]=’J’;
N.Score-=120;
cout<<N.Magic<<N.Score<<endl;
}

11
Answer:
TiLeP550
AiLJP430

(1 Mark for each line of output)

(g) In the following program, if the value of N given by the user is 20, what maximum and
minimum values the program could possibly display? 2

#include <iostream.h>
#include <stdlib.h>
void main()
{
int N,Guessnum;
randomize();
cin>>N;
Guessnum=random(N-10)+10;
cout<<Guessnum<<endl;
}

Answer:
Maximum Value: 19 Minimum Value: 10

(1 Mark for writing correct minimum value)


(1 Mark for writing correct maximum value)

2.
(a) What do you understand by Polymorphism? Give a suitable example of the same. 2
Answer:
Polymorphism: It is a method of using the same operator or function (method) to work
using different sets of input. Function overloading is one of the example of polymorphism,
where more than one function carrying same name behave differently with different set of
parameters passed to them.

void Display()
{
cout<<”Hello!”<<endl;
}
void Display(int N)
{
cout<<2*N+5<<endl;
}

(1 Mark for definition)


(1 Mark for example)
OR
(Full 2 marks for explaining both with the help of an example)

(c) Answer the questions (i) and (ii) after going through the following program: 2

class Match
{
int Time;
public:
Match() //Function 1

12
{
Time=0;
cout<<”Match commences”<<end1;
}
void Details() //Function 2
{
cout<<”Inter Section Basketball Match”<<end1;
}

Match(int Duration) //Function 3


{
Time=Duration;
cout<<”Another Match begins now”<<end1;
}

Match(Match &M) //Function 4


{
Time=M.Duration;
cout<<”Like Previous Match ”<<end1;
}

};

iii) Which category of constructor - Function 4 belongs to and what is the purpose of
using it?
Answer:
Copy Constructor, it is invoked when an object is created and initialised with
values of an already existing object.

( ½ Mark for mentioning “Constructor”)


( ½ Mark for correctly answering to remaining part of the question)

iv) Write statements that would call the member Functions 1 and 3
Answer:
Match M1; //for Function 1
Match M2(90); //for Function 3

( ½ Mark for each example)

(d) Define a class in C++ with following description: 4


Private Members
 A data member Flight number of type integer
 A data member Destination of type string
 A data member Distance of type float
 A data member Fuel of type float
 A member function CALFUEL() to calculate the value of Fuel as per the following
criteria
Distance Fuel
<=1000 500
more than 1000 and <=2000 1100
more than 2000 2200

13
Public Members
 A function FEEDINFO() to allow user to enter values for Flight Number,
Destination, Distance & call function CALFUEL() to calculate the quantity of Fuel
 A function SHOWINFO() to allow user to view the content of all the data
members
Answer:
class FLIGHT
{
int Fno;
char Destination[20];
float Distance, Fuel;
void CALFUEL();
public:
void FEEDINFO();
void SHOWINFO();
};
void FLIGHT::CALFUEL()
{
if (Distance<1000)
Fuel=500;
else
if (Distance<2000)
Fuel=1100;
else
Fuel=2200;
}
void FLIGHT::FEEDINFO()
{
cout<<”Flight No :”;cin>>Fno;
cout<<”Destination :”;gets(Destination);
cout<<”Distance :”;cin>>Distance;
CALFUEL();
}
void FLIGHT::SHOWINFO()
{
cout<<”Flight No :”<<Fno<<endl;
cout<<”Destination :”<<Destination<<endl;
cout<<”Distance :”<<Distance<<endl;;
cout<<”Fuel :”<<Fuel<<endl;;
}

(1 Mark for correctly declaring Data Members)


(1 Mark for correctly defining CALFUEL())
( ½ Mark for correctly defining FEEDINFO())
( ½ Mark for calling CALFUEL() from FEEDINFO())
( ½ Mark for correctly defining SHOWINFO())
( ½ Mark for correct syntax of class)

(e) Answer the questions (i) to (iv) based on the following: 4


class CUSTOMER
{
int Cust_no;
char Cust_Name[20];
protected:
void Register();
public:

14
CUSTOMER();
void Status();
};
class SALESMAN
{
int Salesman_no;
char Salesman_Name[20];
protected:
float Salary;
public:
SALESMAN();
void Enter();
void Show();
};
class SHOP : private CUSTOMER , public SALESMAN
{
char Voucher_No[10];
char Sales_Date[8];
public:
SHOP();
void Sales_Entry();
void Sales_Detail();
};

(vi) Write the names of data members which are accessible from objects belonging to
class CUSTOMER.
(vii) Write the names of all the member functions which are accessible from objects
belonging to class SALESMAN.
(viii) Write the names of all the members which are accessible from member functions
of class SHOP.
(ix) How many bytes will be required by an object belonging to class SHOP?
Answer:
(i) None of data members are accessible from objects belonging to class CUSTOMER.
(ii) Enter(), Show()
(iii) Data members: Voucher_No, Sales_Date, Salary
Member function: Sales_Entry(), Sales_Details(), Enter(), Show(), Register(), Status()
(iv) 66

( 1 Mark for each correct answer)


Note:
No marks to be given for partial answers

3.
(a) Write a function in C++ to combine the contents of two equi-sized arrays A and B by
computing their corresponding elements with the formula 2*A[i]+3*B[i]; where value i
varies from 0 to N-1 and transfer the resultant content in the third same sized array.
4
Answer:
void AddNSave(int A[],int B[],int C[],int N)
{
for (int i=0;i<N;i++)
C[i]=2*A[i]+3*B[i];
}

(1 Mark for function header with desired parameters)


(1 Mark for correct formation of loop)

15
(1 Mark for the formula)
(1 Mark for transferring elements in the resultant array)

(f) An array P[20][30] is stored in the memory along the column with each of the element
occupying 4 bytes, find out the memory location for the element P[5][15], if an element
P[2][20] is stored at the memory location 5000. 4
Answer:
Given,
W=4
N=20
M=30
Loc(P[2][20])=5000
Column Major Formula:
Loc(P[I][J]) =Base(P)+W*(N*J+I)
Loc(P[2][20]) =Base(P)+4*(20*20+2)
5000 =Base(P)+4*(400+2)
Base(P) =5000- 1608
Base(P) =3392

Loc(P[5][15]) =3392+4*(20*15+5)
=3392+4*(300+5)
=3392+1220
=4612
(1/2 Mark for correct formula/substitution of values in formula)
(1 ½ Mark for correctly calculating Base Address)
(2 Mark for correctly calculating address of desired location)

(g) Write a function in C++ to perform Push operation on a dynamically allocated Stack
containing real numbers. 4
Answer:
struct NODE
{
float Data; NODE *Link;
};
class STACK
{
NODE *Top;
public:
STACK();
void Push();
void Pop();
};
void STACK::Push()
{
NODE *Temp;
Temp=new NODE;
cin>>Temp->Data;
Temp->Link=Top;
Top=Temp;
}
( ½ Mark for appropriate function header)
( ½ Mark for declaring a Temporary pointer - TEMP)
(1 Mark for new operation)
(1 Mark for Temp->Link to Top)
(1 Mark for assigning Top as Temp)

16
(h) Write a function in C++ to find sum of rows from a two dimensional array. 2
Answer:
void MatAdd(int A[100][100],int N,int M)
{
for (int R=0;R<N;R++)
{
int SumR=0;
for (int C=0;C<M;C++)
SumR+=A[C][R];
cout<<SumR<<endl;
}
}

( ½ Mark for initialization of desired variables)


(1 Mark for loops)
( ½ Mark for statement to add rows elements)

(i) Evaluate the following postfix notation of expression: 2


True, False, AND, True, True, NOT, OR, AND
Answer:
Step 1: Push

True
Step 2: Push

False
True
Step 3: AND Push
Pop Pop
Op2=True Op1=False
Op2=True
True False
Step 4: Push

True
False
Step 5: Push

True
True
False
Step 6: NOT Push
Pop
Op2=True False
True True
False False
Step 7: OR Push
Pop Pop
Op2=False Op1=True
True Op2=False True

17
False False False
Step 8: AND Push
Pop Pop
Op2=True Op1=False
Op2=True
False False
Step 9: Pop

Result
False

( 1½ Mark for showing stack position for operations NOT,OR and AND)
( ½ Mark for correctly evaluating the final result)

4.
(a) Observe the program segment given below carefully and fill the blanks marked as
Statement 1 and Statement 2 using seekg() and tellg() functions for performing the
required task. 1

#include <fstream.h>
class Employee
{
int Eno;char Ename[20];
public:
//Function to count the total number of records
int Countrec();
};
int Item::Countrec()
{
fstream File;
File.open(“EMP.DAT”,ios::binary|ios::in);
______________________ //Statement 1

int Bytes = ______________________ //Statement 2

int Count = Bytes / sizeof(Item);


File.close();
return Count;
}

Answer:
File.seekg(0,ios::end); //Statement 1
File.tellg(); //Statement 2

( ½ Mark for each correct statement)

18
(b) Write a function in C++ to count the number of alphabets present in a text file
“NOTES.TXT”. 2
Answer:
void CountAlphabet()
{
ifstream FIL(“NOTES.TXT”);
int CALPHA=0;
char CH=FIL.get();
while (!FIL.eof())
{
if (isalpha(CH)) CALPHA++;
CH=FIL.get();
}
cout<<”No. of Alphabets:”<<CALPHA<<endl;
FIL.close();
}

(½ mark for opening the file in „in‟ mode)


(½ mark for correct use of eof)
(½ mark for reading each character)
(½ mark for correct increment)

(c) Write a function in C++ to add new objects at the bottom of a binary file
“STUDENT.DAT”, assuming the binary file is containing the objects of the following class.
3
class STUD
{
int Rno;
char Name[20];
public:
void Enter(){cin>>Rno;gets(Name);}
void Display(){cout<<Rno<<Name<<endl;}
};
Answer:
void Addnew()
{
fstream FIL;
FIL.open(“STUDENT.DAT”,ios::binary|ios::app);
STUD S;
char CH;
do
{
S.Enter();
FIL.write((char*)&S,sizeof(S));
cout<<”More(Y/N)?”;cin>>CH;
}
while(CH!=’Y’);
FIL.close();
}

(½ mark for opening the file in „app‟ mode)


(½ mark for declaration of desired variables)
(½ mark for calling the member function Enter correctly)
(1 mark for writing the content of object to the binary file)
(½ mark for forming the appropriate loop)

19
5.
(a) What do you understand by Primary Key & Candidate Keys? 2
Answer:
An attribute or set attributes which are used to identify a tuple uniquely is known as
Primary Key. If a table has more than one such attributes which identify a tuple uniquely
than all such attributes are known as Candidate Keys.

(b) Consider the following tables GAMES and PLAYER. Write SQL commands for the
statements (i) to (iv) and give outputs for SQL queries (v) to (viii) 6

Table: GAMES
GCode GameName Number PrizeMoney ScheduleDate
101 Carom Board 2 5000 23-Jan-2004
102 Badminton 2 12000 12-Dec-2003
103 Table Tennis 4 8000 14-Feb-2004
105 Chess 2 9000 01-Jan-2004
108 Lawn Tennis 4 25000 19-Mar-2004

Table: PLAYER
PCode Name Gcode
1 Nabi Ahmad 101
2 Ravi Sahai 108
3 Jatin 101
4 Nazneen 103

(i) To display the name of all Games with their Gcodes


Answer:
SELECT GameName,Gcode FROM GAMES;
(1 mark for correct SELECTion of columns)

(ii) To display details of those games which are having PrizeMoney more than 7000.
Answer:
SELECT * FROM GAMES WHERE PrizeMoney>7000
( ½ mark for correct SELECTion of columns)
( ½ mark for correct use of WHERE)

(iii) To display the content of the GAMES table in ascending order of ScheduleDate.
Answer:
SELECT * FROM GAMES ORDER BY ScheduleDate;
( ½ mark for correct SELECTion of columns)
( ½ mark for correct use of ORDER BY)

(iv) To display sum of PrizeMoney for each of the Number of participation groupings (as
shown in column Number 2 or 4)
Answer:
SELECT SUM(PrizeMoney),Number FROM GAMES GROUP BY Number;
( ½ mark for correct SELECTion of columns)
( ½ mark for correct use of GROUP BY)

(v) SELECT COUNT(DISTINCT Number) FROM GAMES;


Answer:
2
( ½ mark for correct output)

20
(vi)SELECT MAX(ScheduleDate),MIN(ScheduleDate) FROM GAMES;
Answer:
19-Mar-2004 12-Dec-2003
( ½ mark for correct output)

(vii) SELECT SUM(PrizeMoney) FROM GAMES;


Answer:
59000
( ½ mark for correct output)

(viii) SELECT DISTINCT Gcode FROM PLAYER;


Answer:
101
103
108
( ½ mark for correct output)

6.
(a) State and algebraically verify Absorbtion Laws. 2
Answer:
X+X.Y = X
L.H.S = X+X.Y
= X.1+X.Y
= X.(1+Y)
= X.1
= X
= R.H.S

X+X’.Y = X+Y
L.H.S. = X+X’.Y
= (X+X’).(X+Y)
= 1.(X+Y)
= X+Y
= R.H.S

(1 mark for stating the correct law)


(1 mark for the appropriate verification using algebraic method)

(b) Write the equivalent Boolean Expression for the following Logic Circuit 2

Answer:
F(U,V)=U’.V+U.V’
(Full 2 marks for obtaining the correct Boolean Expression for the Logic Circuit)
OR
(1 mark correctly interpreting Product terms)

21
(e) Write the SOP form of a Boolean function G, which is represented in a truth table as
follows: 1
Answer:
P Q R G
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 1
1 1 1 1

G(P,Q,R) = P’.Q.R’+P.Q’.R’+P.Q.R’+P.Q.R

(1 mark for correct SOP representation)

(f) Reduce the following Boolean Expression using K-Map: 3


F(U,V,W,Z)=(0,1,2,4,5,6,8,10)
Answer:

U’V’ U’V UV UV’


W’Z’ 1
0 4 12 8
W’Z 1 1
1 5 13 9
WZ 1 1 1 1
3 7 15 11
WZ’ 1
2 6 14 10

F(U,V,W,Z)=UV+WZ+UZ

(1 mark for correctly drawing K-Map with 1s represented on right places)


(1 mark for minimizing each Quad)
(1 mark for writing the complete Boolean Expression)

7.
b) Define the term Bandwidth. Give unit of Bandwidth. 1
Answer:
Bandwidth is the capability of a medium to transmit an amount of information
over a distance. Bandwidth of a medium is generally measured in bits per second
(bps) or more commonly in kilobits per second (kbps)

( ½ Mark for correct definition and ½ Mark for correct unit)

b) Expand the following terminologies: 1


(i) HTML (ii) XML
Answer:
(i) Hypertext Markup Language
(ii) Extended Markup Language

( ½ Mark for each correct expansion)

22
e) Define the term firewall. 1
Answer:
Firewall is a feature used for Network Security. In a Network there is always
danger of information leaking out or leaking in. Firewall is a feature which forces
all information entering or leaving the network to pass through a check to make
sure that there is no unauthorized usage of the network.
(1 Mark for correct definition)

f) What is the importance of URL in networking? 1


Answer:
URL stands for Uniform Resource Locator. Each page that is created for Web
browsing is assigned a URL that effectively serves as the page’s worldwide
name or address. URL’s have three parts: the protocol , the DNS name of the
machine on which the page is located and a local name uniquely indicating the
specific page(generally the filename).

(1 Mark for correct significance)

e)
Ravya Industries has set up its new center at Kaka Nagar for its office and web
based activities. The company compound has 4 buildings as shown in the
diagram below:

Fazz
Raj
Building
Building

Jazz
Harsh Building
Building

Center to center distances between various buildings is as follows:


Harsh Building to Raj Building 50 m
Raz Building to Fazz Building 60 m
Fazz Building to Jazz Building 25 m
Jazz Building to Harsh Building 170 m
Harsh Building to Fazz Building 125 m
Raj Building to Jazz Building 90 m

Number of Computers in each of the buildings is follows:


Harsh Building 15
Raj Building 150
Fazz Building 15
Jazz Bulding 25

23
e1) Suggest a cable layout of connections between the buildings. 1
Answer:
Layout 1:

Fazz
Raj
Building
Building

Jazz
Harsh Building
Building

Layout 2: Since the distance between Fazz Building and Jazz Building is quite
short

Fazz
Raj
Building
Building

Jazz
Harsh Building
Building

(1 Mark for appropriate layout)

e2) Suggest the most suitable place (i.e. building) to house the server of this
organisation with a suitable reason. 1
Answer:
The most suitable place / block to house the server of this organisation would
be Raj Building, as this block contains the maximum number of computers,
thus decreasing the cabling cost for most of the computers as well as
increasing the efficiency of the maximum computers in the network.

(1 mark for correct placement)

24
e3) Suggest the placement of the following devices with justification: 1
(iii) Internet Connecting Device/Modem
(iv) Switch
Answer:
(i) Raj Building
(ii) In both the layouts, a hub/switch each would be needed in all the
buildings, to interconnect the group of cables from the different
computers in each block
( ½ Mark for placement of each device correctly)

e4) The organisation is planning to link its sale counter situated in various parts of
the same city, which type of network out of LAN, MAN or WAN will be
formed? Justify your answer. 1
Answer:
The type of network that shall be formed to link the sale counters situated in
various parts of the same city would be a MAN, because MAN (Metropolitan
Area Networks) are the networks that link computer facilities within a city.
( ½ mark for correct type and ½ mark for correct justification)

Free Download
CBSE QUESTION PAPERS, C++ PROJECT, C++ PRACTICAL QUESTION &
ANSWERS http://www.cppforschool.com

25
P.X-=Step;
1. C++ REVISION TOUR P.Y+=Step;
P.Z–=Step;
2010 Delhi: }
void main ( )
1. (a) What is the difference between {
automatic type conversion and type POINT P1={15, 25, 5}, P2={10, 30, 20};
casting? Also, give a suitable C++ code to StepIn(P1);
illustrate both. 2 StepOut(P2,4);
cout<<P1.X<<“,”<<P1.Y<<“,”<<P1.Z<<en
Ans. Automatic Type Conversion: it is dl;
an implicit process of conversion of a cout<<P2.X<<“,”<<P2.Y<<“,”<<P2.Z<<en
data from one type to another. dl;
For example StepIn(P2,12);
int N = 65; cout<<P2.X<<“,”<<P2.Y<<“,”<<P2.Z<<en
char C = N; // Automatic type dl;
conversion }
cout<<C; Ans.
OUTPUT: 16, 24, 6
A 6, 34, 16
Type Casting: It is an explicit process of
18, 22, 28
conversion of a data from one type to
(e) Find the output of the following
another. For example
program : 2
int A=1, B=2;
#include <iostream.h>
float C = (float)A/B; //Type Casting
#include <ctype.h>
S)

cout<<C;
void ChangeIt(char Text[ ], char C)
C

OUTPUT:
T

{
G

0.5
(P

for (int K=0;Text[K]!='\0';K++)


ar

{
m
Ku

(b) Which C++ header file(s) will be if (Text[K]>=’F’ && Text[K]<=’L’)


er

essentially required to be included to Text[K]=tolower (Text[K]);


nd

run/ execute the following C++ code?


re

else
Vi

1 if (Text[K]=’E’ || Text[K]==’e’)
void main( ) Text[K]==C;
{ else
int Eno=123, char Ename[ ]=”Rehan if (K%2==O)
Swamp”; Text[K]=toupper(Text[K]);
cout<<setw(5)<<Eno<<setw(25)<<EName<< else
endl;
Text[K]=Text[K-l];
}
}
Ans. (i) iostream.h (ii) iomanip.h
}
void main ( )
(d) Find the output of the following
{
program : 3
char OldText[ ]=”pOwERALone”;
#inc1ude <iostream.h>
ChangeIt(OldText,’%’);
struct POINT
cout<<“New
{
TEXT:”<<OldText<<endl;
int X, Y, Z;
}
};
Ans.
void StepIn(POINT & P, int Step=1)
{ New TEXT : PPW %
P.X+=Step; RR11N%
P.Y-=Step;
P.Z+=Step; (f) The following code is from a game,
} which generates a set of 4 random
void StepOut(POINT & P, int Step=1) numbers. Yallav is playing this game, help
{ him to identify the correct option(s) out
2 XII Computer
of the four choices given below as the }
possible set of such numbers generated
from the program code so that he wins (b) Which C++ header file(s) will be
the game. Justify your answer. essentially required to be included to
2 run/execute the following C++ code:
#include <iostream.h> 1
#include <stdlib.h> void main()
const int LOW=15; {
void main ( ) int Rno=24; char Name [] =” Amen
{ Singhania”;
randomize( ) ; cout<<setw(lO)<<Rno<<setw(20)<<Name<<
int POINT=5, Number; endl;
for (int 1=1;I<=4;I++) }
{ Ans.
Number=LOW+random(POINT) iostream.h
; iomanip.h
cout<<Number<<“:” ;
POINT--; (d) Find the output of the following
} program: 3
} #include <iostream.h>
(i) 19:16:15:18: struct THREE_D
(ii) 14:18:15:16: { int X,Y,Z;
(iii) 19:16:14:18 };
(iv) 19:16:15:16: void MoveIn(THREE_D &T, int Step=l)
Ans. {
(iv) 19:16:15:16: T.X+=Step;
T.Y-=Step;
S)

Justification is as follows:
T.Z+=Step;
C

I POINT Number
T

}
G

Minimum Maximum
(P

void MoveOut(THREE_D &T, int Step=l)


ar

1 5 15 19
{
m

2 4 15 18
Ku

T.X-=Step;
3 3 15 17
er

T.Y+=Step;
nd

4 2 15 16
re

T.Z-=Step;
The only option that satisfies these values
Vi

}
is option (iv).
void main ()
{
2010 Outside Delhi: THREE_D Tl={lO,20,5},T2={30,lO,40};
MoveIn(T1);
1. (a) What is the difference between call MoveOut(T2,5) ;
by value and call by reference? Also, give cout<<Tl.X<<“,”<<Tl.Y<<“,”<<T1.Z<<en
a suitable C++ code to illustrate both. dl;
2 cout<<T2.X<<“,”<<T2.Y<<“,”<<T2.Z<<e
Ans. ndl;
Call by value: The formal parameter MoveIn(T2,l0);
makes a copy of actual parameter. It does cout<<T2.X<<“,”<<T2.y<<“,”<<T2.Z<<e
not make the changes In actual ndl;
parameter If the changes are done In }
formal parameters. Ans.
Call by reference: The formal parameter 11, 19, 6
Is an alias of actual parameter.
Thechanges made In the formal 25, 15, 35
parameter are reflected In actual 35, 5, 45
parameter. It is preceded by &.
void Caloulato(int A,int & B )// A is oall (e) Find. the output of the following
by value, program: 2
{ // B is call by roforonco
A++; #include <iostream.h>
a+=A; #include <ctype.h>
3 XII Computer
void MyCode (char Msg [], char CH) 1 5 25 29
{ 2 4 25 28
for (int (Cnt=O;Msg[Cnt]!=’\0';Cnt++) 3 3 25 27
{ 4 2 25 26
if (Msg[Cnt]>=’B’ && Msg[Cnt]<=’G’) The only option that satisfies these values
Msg[Cnt]=tolower(Msg[Cnt]); is option (iv).
else
if (Msg[Cnt]==’A’|| Msg[Cnt]==’a’) 2009 Delhi:
Msg[Cnt]=CH;
else 1. (a) What is the difference between call
if (Cnt%2==0) by value and call by reference? Give an
Msg[Cnt]=toupper(Msg[Cnt]); example in C++ to illustrate both. 2
else Ans
Msg[Cnt]=Msg[Cnt-l]; Call by value is used to create a
} temporary copy of the data coming from
} the actual parameter into the formal
void main () parameter. The changes done in the
{ function in formal parameter are not
char MyText [] =” ApEACeDriVE”; reflected back in the calling environment.
MyCode(MyText,’@’); It does
cout<<“NEW TEXT:”<<MyText<<endl; not use ‘&’ sign.
} Call by reference is used to share the
Ans. same memory location for actual and
NEW TEXT :@@e@ccddIIe formal parameters and so changes done
in the function are reflected back in the
(f) The following code is from a game, calling environment. It uses ‘&’ sign.
S)

which generates a set of 4 random void Compute(int A, int &B)


C

numbers. Praful is playing this game, help {


T
G

him to identify the correct option(s) out A++;


(P
ar

of the four choices given below as the B++;


m

possible set of such numbers generated cout<<”In the function”<<endl;


Ku

from the program code so that he wins cout<<”A=”<<A<<“&”<<“B=”<<B<<end


er
nd

the game. Justify your answer. 2 l;


re

#include <iostream.h>
Vi

}
#include <stdlib.h> void main ()
const int LOW=25; {
void main () int I=50,J=25;
{ cout<<”Before function call “<<endl;
randomize() ; cout<<”I=”<<I<<”&”<<”J=”<<J <<endl;
int P01NT=5,Number; Compute (I,J) ;
for (int I=1;I<=4;I++) cout<<”After function call “<<endl;
{ cout<<I=”<<I<<”&”<<”J=”<<J <<endl;
Number=LOW+random(POINT); }
cout<<Number<<“:”; OUTPUT
P0INT--; Before function call
} I=50&J=25
} In the function
(i) 29:26:25:28: A=51&B=26
(ii) 24:28:25:26: After function call
(iii) 29:26:24:28: I=50&J=26
(iv) 29:26:25:26:
Ans.
(iv) 29:26:25:26: 1(b) Write the names of the header files
to which the following belong:
Justification is as follows: 1
I POINT Number (i) puts ( ) (ii) sin ( )
Minimum Ans (i) stdio.h (ii) math. h
Maximum
4 XII Computer
1.(e) Find the output of the following as Formal Parameter, It is used to accept
program:2 the data from actual parameter.
#include <iostream.h> void Seventimes(int A)//A is formal
#include <ctype.h> parameter
void Encode (char Info [ ], int N) ; {
void main ( ) cout<<7*A;
{ }
char Memo [ ] = “Justnow” ; void main ()
Encode (Memo, 2) ; {
cout<<Memo<<endl ; int P=6;
} Seventimes(P);//p is actual
void Encode (char Info [ ], int N) parameter
{ }
for (int I = 0 ; Info[I] !=‘\0’ ; 1++) Other answer for the same question
if (1%2= =0)
Info[I] = Info[I] –N ; Ans) The parameters in the function call
else if (islower(Info[I])) statement (or calling function) are called
Info[I] = toupper(Info[I]) ; as Actual Parameters.
else The parameters in the function
Info[I] = Info[I] +N ; definition (or called function) are called
} as Formal Parameters.
Ans Eg:
HuqTlOu void manip(int x, int y)
{ ---
(f) Study the following program and ---
select the possible output from it : }
void main( )
S)

2
C

#include <iostream.h> {
T
G

#include <stdlib.h> int a,b;


(P

----
ar

const int LIMIT = 4 ;


m

void main ( ) manip(a,b);


Ku

{ }
er
nd

randomize( ) ; Here a,b are Actual Parameters and


re

int Points; x,y are Formal Parameters.


Vi

Points = 100 + random(LIMIT) ;


for (int P=Points ; P>=100 ; P– –) 1.(b) Write the names of the header files
cout<<P<<“#” ; to which the following belong:
cout<<endl; 1
} (i) setw( ) (ii) sqrt( )
(i) 103#102#101#100# Ans
(ii) 100#101#102#103# (i) iomanip.h (ii) math.h
(iii) 100#101#102#103#104#
(iv) 104#103#102#101#100# 1.(e) Find the output of the following
Ans program:2
#include <iostream.h>
(i) 103#102#101#100# #include <ctype.h>
void Secret (char Mig[ ], int N);
2009 Outside Delhi: void main ( )
{ char SMS[ ] = “rEPorTmE” ;
1. (a) What is the difference between Secret{SMS,2);
Actual Parameter and Formal Parameter? cout<<SMS<<end1;
Give an example in C++ to illustrate both }
types of parameters. void Secret(char Msg[ ], int N)
2 {
Ans A parameter used in the function call for (int C=0; Msg[C] !=’ \0' ;C++)
is known as Actual Parameter. It is used if (C%2==0)
to send the data to function. A parameter Msg[C] = Msg[C]+N;
used in the function definition is known else if (isupper(Msg[C]))

5 XII Computer
Msg[C] = tolower(Msg[C]); void main( )
else { First = 10, Second = 20;
Msg[C] = Msg[C]-N; Jumpto(First;Second);
} Jumpto(Second);
Ans }
teRmttoe void Jumpto(int N1, int N2 = 20)
{ N1=N1+N2;
(f) Study the following program and count<<N1>>N2;
select the possible output from it : }
2 Ans)#include<iostream.h>
#include <iostream.h> void Jumpto(int N1,int N2=20);
#include <stdlib.h> //Prototype missing
const int MAX=3 ; void main( )
void main ( ) { int First = 10, Second = 20;
{ randomize( ) ; //Data type missing
int Number ; Jumpto(First,Second);
Number = 50 + random{MAX) ; //Comma to come instead of ;
for (int P=Number; P>=50; P– –) Jumpto(Second);
cout<<p<< “ # ” ; }
cout<<endl; void Jumpto(int N1, int N2)
} { N1=N1+N2;
(i) 53#52#51#50# cout<<N1<<N2;
(ii) 50#51#52# //Output operator << required
(iii) 50#51# }
(iv) 51#50#
Ans d)Find the output of the following
program;3
S)

(iv) 51#50#
C

#include<iostream.h>
T

(Solution: MAX value is 3


G

#include<ctype.h>
(P

That’s why random(MAX) can produce 0


void main( )
ar

or 1 or 2. (random(N)will produce
m

{ char Text[ ] = “Mind@work!”;


Ku

no.between 1 to n-1)
for(int I=0; Text[I]!=’\0’;I++)
er

The Number value may be 50 or 51 or 52.


nd

{ if(!isalpha(Text[I]))
The P value starts from Number, upto 50,
re

Text[I]=’*’;
Vi

each time decreases by 1.


else if(isupper(Text[I]))
So Possible outputs are as follows:
Text[I]=Text[I]+1;
52#51#50#
else
51#50#
Text[I] = Text[I+1];
50#
}
As the output 51#50# is available in
cout<<Text;
given answers, so 51#50# is the answer.)
}
Ans: Text[ ] =
2008 Delhi:
1.b)Name the header files that shall be
needed for the following code: When I=0
1 Since Text[0] is ‘M’, Upper Case Letter,
void main( ) (isupper(Text[I]) will becomes true.
{ char String[ ] = “Peace”; So Text[I] =Text[I]+1
cout << setw(2)<<String; So Text[0]=Text[0]+1
} Text[0] =77(ASCII Value of M) + 1 = 78
Ans) iomanip.h, iostream.h =N(78 is ASCII Value of N)
Now the String Text[ ] =
1. c)Rewrite the following program after
removing the syntactical error(s) if any.
Underline each correction.
2
#include<iostream.h> When I=1

6 XII Computer
Since Text[1] is ‘i’, Which is a character,
but which is not Upper case,
else part will be executed.
Ie Text[I]=Text[I+1] When I=6
Here Text[1]=Text[1+1] Since Text[6] is ‘o’, Which is a character,
=Text[2] but which is not Upper case, else part
Ie ‘n’ will be stored in place of ‘i’ will be executed.
Now the String Text[ ] = Ie Text[I]=Text[I+1]
Here Text[6]=Text[6+1]
=Text[7]
Ie ‘r’ will be stored in place of ‘o’
Now the String Text[ ] =
When I=2
Since Text[2] is ‘n’, Which is a character,
but which is not Upper case, else part will
be executed.
Ie Text[I]=Text[I+1] When I=7
Here Text[2]=Text[2+1] Since Text[7] is ‘r’, Which is a character,
=Text[3] but which is not Upper case, else part
Ie ‘d’ will be stored in place of ‘n’ will be executed.
Now the String Text[ ] = Ie Text[I]=Text[I+1]
Here Text[7]=Text[7+1]=Text[8]
Ie ‘k’ will be stored in place of ‘r’
Now the String Text[ ] =
When I=3
Since Text[3] is ‘d’, Which is a character,
S)

but which is not Upper case, else part will


C

be executed. When I=8


T
G

Ie Text[I]=Text[I+1] Since Text[8] is ‘k’, Which is a character,


(P

but which is not Upper case, else part will


ar

Here Text[3]=Text[3+1]
m

=Text[4] be executed. Ie Text[I]=Text[I+1]


Ku

Ie ‘@’ will be stored in place of ‘d’ Here Text[8]=Text[8+1]


er
nd

Now the String Text[ ] = =Text[9]


re

Ie ‘!’ will be stored in place of ‘k’


Vi

Now the String Text[ ] =

When I=4
Since Text[4] is ‘@’, Since which is not an
When I=9
alphabet,
Since Text[9] is ‘!’, Since which is not an
(!isalpha(Text[I])) will becomes true.
alphabet, (!isalpha(Text[I])) will becomes
Ie if(!isalpha(Text[I]))
true.
Text[I]=’*’;
Ie if(!isalpha(Text[I]))
Ie Text[4]=’*’
Text[I]=’*’;
Ie ‘*’ will be stored in place of ‘@’
Ie Text[9]=’*’
Now the String Text[ ] =
Ie ‘*’ will be stored in place of ‘!’
Now the String Text[ ] =

When I=5
Since Text[5] is ‘W’, Upper Case Letter,
(isupper(Text[I]) will becomes true.
So Text[I] =Text[I]+1 Output: Nnd@*Xrk!*
So Text[5]=Text[5]+1
Text[5] =87(ASCII Value of W) + 1 = 88
e) Find the output of the following
=X(88 is ASCII Value of X)
program: 2
Now the String Text[ ] =
#include<iostream.h>
7 XII Computer
void main( ) identifier gets replaced by the specified
{ int U=10,V=20; value by the compiler, before the code is
for(int I=1;I<=2;I++) turned into binary. This means that the
{ cout<<”[1]”<<U++<<”&”<<V – 5 compiler makes the substitution when
<<endl; you compile the application.
cout<<”[2]”<<++V<<”&”<<U + 2 Eg: #define number 100
<<endl; In this case every instance of “number”
} will be replaced by the actual number
}A 100 in your code, and this means the final
ns: Output: compiled program will have the number
[1]10&15 100 (in binary).
[2]21&13 #define with different types of data:
[1]11&16
[2]22&14 • The #define preprocessor allows
u s to define symbolic names and
f) In the following program, find the constants.
correct possible output(s) from the Eg: #define PI 3.14159
options: 2 • The #define allows you to make
#include<stdlib.h> text substitutions before
#include<iostream.h> compiling the program.
void main( ) Eg: #define MAX 70
{ randomize( ); Before compilation, if the C++
char City[][10]= preprocessor finds MAX as one
{“DEL”,”CHN”,”KOL”,”BOM”,”BNG”}; word, in the source code, it
int Fly; replaces it with the number 70.
for(int I=0; I<3;I++) • The #define preprocessor can be
S)
C

{ Fly=random(2) + 1; used in the creation of macros


T
G

cout<<City[Fly]<<”:”; (code substitution).


(P

} Eg: #define SQUARE(x) x*x


ar
m

}
Ku

Outputs: Before compilation, if the C++


er
nd

(i) DEL : CHN : KOL: preprocessor finds SQUARE(x), where x


re

(i) CHN: KOL : CHN: is any value in the source code, it


Vi

(ii) KOL : BOM : BNG: replaces it with its square (ie x*x). Here
(iii) KOL : CHN : KOL: a macro substitutes text only; It does not
check for data types.
Ans)Since random(2) gives either 0 or 1, On the other hand, when we use
Fly value will be either 1 or 2. const and the application runs, memory
(random(n) gives you any number is allocated for the constant and the value
between 0 to n-1) gets replaced when the application is run.
City[1] is “CHN”. City[2] is “KOL”. Syntax: const type variable_name=value;
Since I value from 0 to 2 (ie<3), 3
iterations will takes place. Eg: const int a=10;
So the possible output consists 3 strings The value of a constant is
separated by :, each of them may be fixed and in the above example, the value
either “CHN” or “KOL”. for a in entire program is 10 only. You
cannot change the value of a, since it is
So the possible output will be declared as constant.
(ii) CHN : KOL : CHN:
(iv) KOL :CHN : KOL: Difference between #define and const
in declaration:.
1.a) What is the difference between 1.#define: #define symbolic_constant
#define and const? Explain with suitable value.
example. 2 Eg: #define number 100 //No
Ans: While they both serve a similar semicolon ,no equal to symbol.
purpose, #define and const act 2.const: const type
differently. When using #define the variable_name=value;

8 XII Computer
Eg: const number=100; //Semicolon, equal Mystring[I]=Mystring[I]+1;
to symbol. else
Mystring[I] =Mystring[I+1];
2008 Outside Delhi: }
cout<<Mystring;}
1.b) Name the header files that shall be Ans: Output: hat@*PVUQVU*
needed for the following code:
1 e) Find the output of the following
void main( ) program: 2
{ #include<iostream.h>
char word[]=”Exam”; void main( )
cout<<setw(20)<<word; { int A=5,B=10;
} for(int I=1;I<=2;I++)
Ans: iostream.h, iomanip.h { cout<<”Line1”<<A++<<”&”<<B-2
<<endl;
1.c) Rewrite the following program after cout<<”Line2”<<++B<<”&”<<A +3
removing the syntax error(s) if any. <<endl;
Underline each correction. }
2 }
#include<iostream.h> Ans: Output:
void main( )
{ Line15&8
One=10,Two=20; Line211&9
Callme(One;Two); Line16&9
Callme(Two); Line212&10
}
void Callme(int Arg1,int Arg2)
S)

f) In the following program, find the


C

{
T

correct possible output(s) from the


G

Arg1=Arg1+Arg2;
(P

options: 2
Count<<Arg1>>Arg2;
ar

#include<stdlib.h>
m

}
Ku

#include<iostream.h>
Ans:
er

void main( )
nd

void Callme(int Arg1,int Arg2=20);


{
re

#include<iostream.h>
Vi

randomize( );
void main( )
char Area[ ][10]
{
={“NORTH”,”SOUTH”,”EAST”,”WE
int One=10,Two=20;
ST”};
Callme(One,Two); //Given ; instead
int ToGo;
of ,
for(int I=0; I<3;I++)
Callme(Two);
{
}
ToGo=random(2) + 1;
void Callme(int Arg1,int Arg2)
cout<<Area[ToGo]<<”:”;
{
}
Arg1=Arg1+Arg2;
}
cout<<Arg1<<Arg2;
Ans: Outputs:
}
(i) SOUTH : EAST : SOUTH :
(ii) NORTH : SOUTH : EAST :
1.d)Find the output of the following
(iii) SOUTH : EAST : WEST :
program:3
(iv) SOUTH : EAST : EAST :
#include<iostream.h>
Ans)Since random(2) gives either 0 or 1,
#include<ctype.h>
ToGo value will be either 1 or 2.
void main( )
(random(n) gives you any number
{
between 0 to n-1)
char Mystring[ ] = "what@OUTPUT!";
Area[1] is “SOUTH”. Area[2] is “EAST”.
for(int I=0; Mystring[I]!='\0';I++)
Since I value from 0 to 2 (ie<3), 3
{ if(!isalpha(Mystring[I]))
iterations will takes place.
Mystring[I]='*';
else if(isupper(Mystring[I]))

9 XII Computer
So the possible output consists 3 strings 1.a) Differenctiate between a Run Time
separated by :, each of them may be Error and Syntax Error. Also give
either “SOUTH” or “EAST”. suitable examples of each in c++.
So the possible output will be 2
(i) SOUTH : EAST : SOUTH : Ans: Run Time Errors: Errors that occur
(iv) SOUTH : EAST : EAST : during the execution of a program are
called as run time errors. It is caused of
1.a) What is the purpose of using a some illegal operation taking place or
typedef command in C++?Explain with inavailability of desired or required
suitable example 2 conditions for the execution of the
Ans: C++ allows you to define program. For instance, if a program is
explicitly new data type names by using trying to open a file which does not exist
the keyword typedef. Using typedef does or it could not be opened, it results into
not actually create a new data class, an execution error. Similarly, if enough
rather it defines a new name for an memory is not available or an expression
existing type. This can increase the is trying to divide a number by zero are
portability of a program as only the run-time errors.
typedef statements would have to be Eg: Division by zero. c=a/b ;
changed. Typedef makes your code User will give the values of a and b at the
easier to read and understand. Using time of program execution.
typedef can also aid in self documenting If he give the value of b as ‘0’ , then
your code by allowing descriptive names division by zero, ie a run time error
for the standard data types. occurs.
The syntax of the typedef statement is Syntax Errors:Syntax errors occur when
typedef type name; rules of a programming languages
Where type is any C++ data type and (syntax) is misused. Ie when a
name is the new name for this type. This grammatical rule of C++ is violated.
S)
C

defines another name for the standard Eg (i) c=a+b


T
G

type of C++. For example, you could In this statement, since there is no
(P

create a new name for float values by semicolon at the end of the statement,
ar
m

using the following statement: there will occurs a syntax error.


Ku

typedef float amount; (ii)cin<<a;


er

This statement tells the compiler to


nd

In this statement, since stream insertion


re

recognize amount as an alternative name operator (<<) has given instead of stream
Vi

for float. Now you could create float extraction operation(>>), there will
variables using amount. occurs a syntax error.
amount loan, saving, installment;
Using typedef does not replace the 1.b) Name the header file(s) that shall be
standard C++ data type name with the needed for successful compilation of the
new name, rather the new name is in following C++ code.
addition to the existing name. You still 1
can create float variables using float. void main( )
Once a new name has been defined by { char String[20];
typedef, it can be used as a type for gets(String);
another typedef also. strcat(String,”CBSE”);
Eg: typedef amount money; puts(String);
Now, this statement tells the }
compiler to recognize money as another Ans) stdio.h string.h
name for amount, which itself is another
name for float. Typedef does not create 1. c) Rewrite the following program after
any new data types rather provides an removing the syntactical error(s) if any.
alternative name for standard types. Underline each correction.
Reference provides an alias name for a 2
variable and typedef provides an alias #include<iostream.h>
name for a data type. const int Max 10;
void main()
2007 Delhi : { int Numbers[Max];
Numbers = {20,50,10,30,40};

10 XII Computer
for(Loc=Max-1;Loc>=10;Loc--) 1.a) Differentiate between a Logical
cout>>Numbers[Loc]; Error and Syntax Error. Also give
} suitable examples of each in C++.
Ans) 2
#include<iostream.h> Ans: Logical Error: A logical error is that
const int Max=10;//Constant Variable error which causes a program to produce
‘Max’ //must be initialized.Declaration incorrect or undesired output.
Syntax Error An incorrectly implemented algorithm or
void main( ) use of a variable before its initialization,
{ int Numbers[Max]={20,50,10,30,40}; or unmarked end for a loop, or wrong
for(Loc=Max-1;Loc>=0;Loc--) parameters passed are causes logical
cout>>Numbers[Loc]; errors. These must be handled carefully.
} For instance, if we are trying to print the
table of a number 5 and if we say
e)Find the output of the following counter=1;
program. 3 while(counter>8)
#include<iostream.h> { cout<<n*counter;
void Withdef(int HisNum=30) counter=counter+1;
{ for(int I=20;I<=HisNum;I+=5) }
cout<<I<<”,”; Here the loop would not be executed
cout<<endl; even once as the condition (counter>8) is
} not fulfilled at all. Therefore, no output
void Control(int &MyNum) will be produced. Such an error is logical
{ MyNum+=10; error.
Withdef(MyNum); Syntax Error: Syntax errors occur when
} rules of a programming languages
void main() (syntax) is misused. Ie when a
S)
C

{ int YourNum=20; grammatical rule of C++ is violated.


T
G

Control(YourNum); Eg (i) c=a+b


(P

Withdef(); In this statement, since there is no


ar
m

cout<<”Number=”<<YourNum<<endl; semicolon at the end of the statement,


Ku

} there will occurs a syntax error.


er
nd

Ans: Output: (ii)cin<<a; In this statement, since


re

20,25,30, stream insertion operator (<<) has given


Vi

instead of stream extraction


20,25,30, operation(>>), there will occurs a syntax
Number=30 error.

f)In the following C++ program what is 1.b) Name the header file(s) that shall be
the expected value of MyMarks from needed for successful compilation of the
options (i) to (iv)given below. Justify following C++ code.
answer. 2 1
#include<stdlib.h> void main( )
#include<iostream.h> {
void main( ) char Text[40];
{ strcpy(Text,”AISSCE”);
randomize( ); puts(Text);
int }
Marks[]={99,92,94,96,93,95},MyMarks; Ans:
MyMarks = Marks [1+random(2)]; string.h, stdio.h
cout<<MyMarks<<endl;
} 1.c) Rewrite the following program after
(i)99 (ii)94 (iii)96 (iv) None of the above. removing the syntactical error(s), if any.
Ans: Output: Underline each correction. 2
(ii) 94 #include<iostream.h>
const int Size 5;
2007 Outside Delhi: void main( )
{

11 XII Computer
int Array[Size]; (i) None of the above.
Array={50,40,30,20,10};
for(Ctr=0;Ctr<Size;Ctr++)
cout>>Array[Ctr]; 2006 Delhi:
}
Ans) 1.a) Name the header file to which the
#include<iostream.h> following below:
const int Size=5; 1
void main( ) (i) abs( ) (ii) isupper( )
{ Ans) (i) abs( ) - math.h, stdlib.h,
int Array[Size]; complex.h
Array={50,40,30,20,10}; (ii)isupper( ) - ctype.h
for(Ctr=0;Ctr<Size;Ctr++)
cout<<Array[Ctr]; 1.e) Find the output of the following
} program 2 #include<iostream.h>
void main( )
1.e)Find the output of the following { long NUM=1234543;
program3 int F=0,S=0;
#include<iostream.h> do
void Indirect(int Temp=20) { int R=NUM % 10;
{ if (R %2 != 0)
for(int I=10;I<=Temp;I+=5) F += R;
cout<<I<<”,”; else
cout<<endl; S += R;
} NUM / = 10;
void Direct(int &Num) } while (NUM>0);
{ Num+=10;
S)

cout<<F-S;
C

Indirect(Num);
2
T

} Ans: Output:
G

}
(P

void main( )
ar

1.b) Illustrate the use of #define in C++


m

{ int Number=20;
Ku

Direct(Number); to define a macro.


er

2
nd

Indirect( );
Ans: The #define preprocessor can be
re

cout<<”Number =”<<Number<<endl;
Vi

} used in the creation of macros (code


Ans: Output: substitution).
Eg: #define SQUARE(x) x*x
10,15,20,25,30, Before compilation, if the C++
10,15,20, preprocessor finds SQUARE(x),
Number =30 where x is any value in the source
code, it replaces it with its square (ie x*x).
f) In the following C++ program what is Here a macro substitutes text only; It
the does not check for data types.
expected value of Mysore from options (i)
to (iv) given below.Justify your answer. 1.C) Rewrite the following program after
2 removing the syntactical error(s), if
#include<stdlib.h> any.Underline each correction.
#include<iostream.h> 2
void main( ) #include<iostream.h>
{ randomize( ); void main( )
int Score[ ] = { struct STUDENT
{25,20,34,56,72,63},Myscore; {
cout<<Myscore<<endl; char stu_name[20];
} char stu_sex;
(i) 25 (ii) 34 (iii) 20 (iv) None of the int stu_age=17;
above. }student;
gets(stu_name);
Ans: Expected Output: gets(stu_sex);
}
12 XII Computer
addr address;
Ans: #include<iostream.h> float basic;
#include<stdio.h> }worker;
void main( )
{ struct STUDENT 2006 Outside Delhi:
{ char stu_name[20];
char stu_sex; 1.a) Name the header file to which the following
int stu_age; belong: 1
//Initialization of variables inside a (i) pow ( ) (ii)random( )
structure is not allowed. Ans:
}student; (i) abs( ) - math.h, stdlib.h, complex.h
gets(student.stu_name); (ii)random( ) - stdlib.h
cin>>student.stu_sex);
//A single character cannot be read using 1.e)Find the output of the following
gets program 2 #include<iostream.h
} void main( )
{ long Number=7583241;
1.f) What are Nested Structures? Give an int First = 0, Second =0;
example. do
2 { int R=Number%10;
Ans: Nested structures are structures as if(R%2 ==0)
member of another structure. For First += R;
example, the date of birth is astructure else
within the structure of a student as Second += R;
shown below. These types of structures Number / = 10;
are known as nested structures. } while (Number > 0);
cout<<First-Second;
S)
C

}
T
G

Eg1: Ans: Output -2


(P

struct date
ar
m

{ int dd;
Ku

1.C) Rewrite the following program after


int mm;
er

removing the syntactical error(s), if any.


nd

int yy;
Underline each correction.
re

};
Vi

2
struct student
#include<iostream.h>
{ char name[20];
void main( )
int roll;
{ struct movie
date dob;
{ char movie_name[20];
int marks;
char movie_type;
};
int ticket_cost=100;
The member of a nested structure is
}MOVIE;
referenced from the outermost to
gets(movie_name);
innermost with the help of dot operators.
gets(movie_type);
student stud;
}
Then the members of the nested
Ans:#include<iostream.h>
structure can be accessed as
#include<stdio.h>
stud.dob.mm=10;
void main( )
Eg2:
{ struct movie
struct addr
{ char movie_name[20];
{ int houseno;
char movie_type;
char area[26];
int ticket_cost;
char city[26]; //Initialization of variables inside a structure is not
char state[26]; allowed.
}; }MOVIE;
struct emp gets(MOVIE.movie_name);
{ int empno; cin>>MOVIE.movie_type;
char name[26]; //A single character cannot be read
char design[16]; using gets
}
13 XII Computer
2005 Delhi: Program to illustrate the call by
Reference method of function
invoking:
1.a) Differentiate between a Call by Value #include<iostream.h>
and Call by Reference, giving suitable #include<conio.h>
examples of each. int change(int&);
2 void main( )
Ans: Call by value: In call by value { clrscr( );
method, the called function creates a new int orig=10;
set of variables and copies the values of cout<<”\nThe original value
arguments into them. The function does is”<<orig<<”\n”;
not have access to the original variables cout<<”\nReturn value of function
(actual parameters) and can only work change()is
“<<change(orig)<<”\n”;
on the copies of values it created. Passing
cout<<”\nThe value after function change() is
arguments by value is useful when the over”<<orig<<”\n;
original values are not to be modified. getch();
In call by reference method, a }
reference to the actual argument int change(int &duplicate)
(original variable) is passed to the called { duplicate=20;
function. (Reference is an alias for a return duplicate;
predefined variable. Ie the same variable }
value can be accessed by any of the two
names: the original variable’s name and Output:
the reference name.) Thus, in call by The original value is 10
reference method, the changes are Return value of function change() is 20
reflected back to the original values. The The value after function change() is over
S)

call by reference method is useful in


C

20
T

situations where the values of the


G
(P

original variables are to be changed using 1. b) Name the header files to which the
ar

a function.
m

following belong:
Ku

1
er

Program to illustrate the call by value (i) abs( ) (ii) strcmp( )


nd
re

method of function invoking: Ans) (i) abs( ) - stdlib.h, math.h,


Vi

#include<iostream.h> complex.h
#include<conio.h> (ii) strcmp( ) - string.h
int change(int);
void main( ) 1. c) Rewrite the following program after
{ clrscr( ); removing the syntactical error(s), if any.
int orig=10; Underline each correction.
cout<<”\nThe original value 2 #include<iostream.h>
is”<<orig<<”\n”; const int Multiple 3;
cout<<”\nReturn value of function void main( )
change()is {
“<<change(orig)<<”\n”; value = 15;
cout<<”\nThe value after function for(int Counter = 1;Counter = <5;Counter ++,
change() is Value -= 2)
over”<<orig<<”\n; if(Value%Multiple = = 0)
getch(); cout<<Value * Multiple;
} cout<<end1;
int change(int duplicate) else
{ duplicate=20; cout<<Value + Multiple <<endl; }
return duplicate; Answer:
} #include<iostream.h>
Ans: Output: const int Multiple=3;
The original value is 10 void main( )
Return value of function change() is 20 {
The value after function change() is over
10 int Value = 15;
14 XII Computer
for(int Counter = 1;Counter <=5;Counter ++, cin>>Num;
Value -= 2) Rndnum = random(Num) + 5;
if(Value%Multiple == 0) for(int N = 1;N<=Rndnum;N++)
{ cout<<Value * Multiple; cout<<N<<” “;
cout<<endl; }
} Output Options:
else (i) 1 2 3 4 (ii) 1 2
cout<<Value + Multiple <<endl; (iii) 1 2 3 4 5 6 7 8 9
} (iv) 1 2 3
Ans: Expected Output:
1.e) Find the output of the following
program 2 (iii) 1 2 3 4 5 6 7
#include<iostream.h> 8 9
#include<string.h>
#include<ctype.h> 1.d) Find the output of the following
void Convert(char Str[ ],int Len) program:
{
for(int Count=0;Count<Len;Count++) #include<iostream.h>
{ if(isupper(Str[Count])) struct MyBox
Str[Count]=tolower(Str[Count]); { int Length,Breadth,Height;
else if (islower(Str[Count])) };
Str[Count]=toupper(Str[Count]); void Dimension(MyBox M)
else if(isdigit(Str[Count])) { cout<<M.Length<<”x”<<M.Breadth<
Str[Count]=Str[Count]+1; <”x”;
else Str[Count]=’*’; cout<<M.Height<<endl;
} }
} void main( )
S)

void main( ) { MyBox B1={10,15,5},B2,B3;


C
T

{ ++B1.Height;
G
(P

char Text[ ]=”CBSE Exam 2005”; Dimension(B1);


ar

int Size = strlen(Text); B3=B1;


m
Ku

Convert(Text,Size); ++B3.Length;
er

cout<<Text<<endl; B3.Breadth++;
nd

for(int C=0,R=Size – 1;C<=Size/2;C+ Dimension(B3);


re
Vi

+,R--) B2=B3;
{ char Temp=Text[C]; B2.Height+=5;
Text[C]=Text[R]; B2.Length--;
Text[R]=Temp; Dimension(B2);
} }
cout<<Text<<endl;
} 2005 Outside Delhi :
Ans: Output:
cbse*eXAM*3116 1.b) Name the header files to which the
6113*MXAe*esbc following belong: 1
(i) puts( ) (ii)isalnum( )
1. f) Observe the following program Ans)(i) puts( ) - stdio.h
SCORE.CPP carefully, if the value of Num (isalnum( ) - ctype.h
entered by the user is 5, choose the
correct possible output(s) from the 1.c) Rewrite the following program after
options from (i) to (iv), and justify your removing the syntactical error(s), if any.
option. Underline each correction.
2 2
//Program: SCORE.CPP #include<iostream.h>
#include<stdlib.h> const int dividor 5;
#include<iostream.h> void main( )
void main( ) { Number = 15;
{ randomize( ); for(int Count=1;Count=<5;Count++,Number
int Num,Rndnum; -= 3)

15 XII Computer
if(Number % dividor = = 0) entered by the user is 14, choose the
cout<<Number / Dividor; correct possible output(s) from the
cout<<endl; options from (i) to (iv), and justify your
else option.
cout<<Number + Dividor <<endl; 2
Ans: //Program:GAME.CPP
#include<iostream.h> #include<stdlib.h>
const int dividor= 5; #include<iostream.h>
void main( ) void main( )
{ { randomize( );
int Number = 15; int Num,Rndnum;
for(int Count=1;Count<=5;Count++,Number cin>>Num;
-= 3) Rndnum=random(Num)+7;
if(Number % dividor = = 0) for(int N=1;N<=Rndnum;N++)
{ cout<<Number / Dividor; cout<<N<<” “;
cout<<endl; }
} Output Options:
else (i) 1 2 3 (ii) 1 2 3 4 5 6 7 8 9 10
cout<<Number + Dividor <<endl; 11
} (iii) 1 2 3 4 5 (iv) 1 2 3 4
Ans: Expected Output
1.e) Find the output of the following (ii) 1 2 3 4 5 6 7 8 9 10
program 2
#include<iostream.h> 11
#include<string.h>
#include<ctype.h> 1.d) Find the output of the following
void Change(char Msg[],int Len) program:
S)

{ for(int Count=0;Count<Len;Count++) #include<iostream.h>


C
T

{ if(islower(Msg[Count])) struct Package


G
(P

Msg[Count] = { int Length,Breadth,Height;


ar

toupper(Msg[Count]); };
m
Ku

else if(isupper(Msg[Count])) void Occupies(Package M)


er

Msg[Count] = { cout<<M.Length<<”x”<<M.Breadth<
nd

<”x”;
re

tolower(Msg[Count]);
Vi

else if (isdigit(Msg[Count])) cout<<M.Height<<endl;


Msg[Count]=Msg[Count]+1; }
else Msg[Count] = ‘*’; void main( )
} { Package P1={100,150,50},P2,P3;
} ++P1.Height;
void main( ) Occupies(P1);
{ char Message[ ]=”2005 Tests ahead”; P3=P1;
int Size=strlen(Message); ++P3.Lengh;
Change(Message,Size); P3.Breadth++;
cout<<Message<<endl; Occupies(P3);
for(int C=0,R=Size – 1; C<=Size/2;C+ P2=P3;
+,R--) P2.Height+=50;
{ char Temp=Message[C]; P2.Length--;
Message[C]=Message[R]; Occupies(P2);
Message[R]=Temp; }
}
cout<<Message<<endl; 2004 Annual Paper:
}
Ans: Output: 1.b) Write the names of the header files
3116*tESTS*AHEAD to which the following belong:
DAEHA*SSTEt*6113 (i) gets( ) (ii) strcmp( ) (iii)abs( )
(iv)isalnum( )
1.f) Observe the following program
GAME.CPP carefully, if the value of Num Ans: (i)gets( ) - stdio.h

16 XII Computer
(ii)strcmp( ) - string.h else
(iii)abs( ) - math.h, { sum=sum-f/(pow(x1,c));
stdlib.h,complex.h }
(iv)isalnum( ) - ctype.h }
return sum;
1.e) What will be the output of the }
following program
#include<iostream.h> 1.c) Rewrite the corrected code for the
void main( ) following program. Underline each
{ int var1=5,var2=10; correction if any.
for(int i=1,i<=2;i++)
{ cout<<var1++<<’\t’<< - - var2<<endl; #include<iostream.h>
cout<<var2- -<<’\t’<<+ + var1<<endl; structure Supergym
} { int member number;
} char membername[20];
Ans: Output: char membertype[]=”HIG”;
5 9 };
void main( )
9 7 { Supergym person1,person2;
7 7 cin>>”Member Number: “;
7 9 cin>>person1.membhernumber;
cout<<”Member Name: “;
f)Write definition for a function cin>>person1.membername;
SumSequence( ) in C++ with two person1.member type = “MIG”;
arguments/ parameters – double X and person2=person1;
int n. The function should return a value cin>>”Member Number;“
of type double and it should perform sum <<person2.membernumber;
S)
C

of the following series. cin<<”Member Name”


T
G

1/x- 3!/x2 + 5!/x3 – 7!/x4 + 9!/x5 - <<person2.membername;


(P

------upto n terms. cin<<”Member Number:”


ar
m

Note: The symbol ! represents Factorial <<person2.membertype;


Ku

of a number ie 5!= 1 X 2 X 3 X 4 X 5. }
er
nd

#include<iostream.h>
re

#include<math.h> Ans:#include<iostream.h>
Vi

#include<conio.h> #include<string.h>
double SumSequence(int x1,int n1); struct Supergym
void main() { int membernumber;
{ int x; char membername[20];
int n; char membertype[4];
clrscr(); };
cout<<"Enter the vaue of X and N"; void main( )
cin>>x>>n; { Supergym person1,person2;
cout<<”\nThe sum of the series = cin>>"Member Number: ";
“<<SumSequence(x,n);
getch(); cin>>person1.membernumber;
} cout<<"Member Name: ";
double SumSequence(int x1,int n1) cin>>person1.membername;
{ double sum=0;
int c=0; strcpy(person1.membertype,"MIG");
for(int i=1;i<=(2*n1);i=i+2) person2=person1;
{ int f=1; cin>>"Member Number;"
for(int j=1;j<=i;j++) >>person2.membernumber;
{ f=f*j; cin>>"Member Name"
} >>person2.membername;
c=c+1; cin>>"Member Number:"
if(c%2==1) >>person2.membertype;
{ sum=sum+f/(pow(x1,c)); }
}

17 XII Computer
2003 Annual Paper: switch(I)
{ case 0:
1.a) What is the difference between case 3:cout<<P[I]*Q<<endl; break;
global variables and local variables? Give case 1:
an example to illustrate the same. case 2: cout<<P[I]+Q;
2 }
Ans: The local variables are the variables }
defined within any function (or block)
and are hence accessible only within the 1.e) Write the output of the following
block in which they are declared. In program:
contrast to local variables, variables #include<iostream.h>
declared outside of all the functions in a int Execute(int M)
program are called global variables. { if(M%3==0)
These variables are defined outside of return M*3;
any function, so they are accessible to all else
functions. These functions perform return M+10;
various operations on the data. They are }
also known as External Variables. void Output(int B=2)
Eg: #include<iostream.h> { for(int T=0;T<B;T++)
int a,b; cout<<Execute(T)<<”*”;
void main() cout<<endl;
{ float f; }
---; void main( )
---; { Output(4);
} Output( );
In the above program segment, a and b Output(3);
}
S)

are global variables, we can access a and


C

b from any function. f is local variable to


T
G

function main( ), we can access f from f) Write a C++ function SUMFUN( )


(P

having two parameters Y(of type double)


ar

main( ) only.
m

and m(of type integer) with a result type


Ku

1.b) Name the header file, to which the as double to find the sum of the series
er
nd

following built-in function belongs: given below:


re

Y + Y3 / 2! + Y5 /3! + ------ + Y 2m-1 /


Vi

(i) strcmp( ) (ii)getc( )


1 m!
Ans: (i) strcmp( ) - string.h
(ii)getc( ) - stdio.h #include<iostream.h>
#include<math.h>
1.c) Rewrite the following program after #include<conio.h>
removing all the syntax error(s) if any.2 double SUMFUN(int y1,int m1);
#include<iostream.h> void main()
void main( ) { int y;
{ int P[ ]={90,10,24,15};Q,Number=4; int m;
Q=9; clrscr();
for[int I=Number-1;I>=0,I--] cout<<"Enter the vaue of Y and M";
switch(I) cin>>y>>m;
{ case 0; cout<<”\nThe sum of the series =
case 3:cout>>P[I]*Q<<endl;break; “<<SUMFUN(y,m);
case 1: getch();
case 2: cout<<P[I]+Q; }
} double SUMFUN(int y1,int m1)
} { double sum=0;
Ans: double upper;
#include<iostream.h> for(int i=1;i<=m1;i++)
void main( ) { int f=1;
{ int P[ ]={90,10,24,15},Q,Number=4; for(int j=1;j<=i;j++)
Q=9; { f=f*j;
for(int I=Number-1;I>=0;I--) }

18 XII Computer
upper=pow(y1,(i*2-1)); cin>>x;
sum=sum+upper/f; for( int y=0;y<10;y++)
} cout<<x+y;
return sum; }
}
1.d)Write the output of the following
1.d) Give the output of the following program2
program: void main( )
#include<iostream.h> { int x=5,y=5;
struct Pixel cout<<x- -;
{ int C,R; cout<<”,”;
}; cout<- - x;
void Display(Pixel P) cout<<”,”;
{ cout<<y- -<<”,”<<- -y;
cout<<”col”<<P.C<<”Row”<<P.R<< }
endl; Ans: Output:
} 5,3,4,4
void main( )
{ 1.e)Write the output of the following
Pixel X={40,50},Y,Z; program 3
Z=X; #include<iostream.h>
X.C+=10; void X(int &A,int &B)
Y=X; { A=A+B;
Y.R+=20; B=A-B;
Z.C-=15; A=A-B;
Display(X); }
Display(Y);
S)

void main( )
C

Display(Z); { int a=4,b=18;


T
G

} X(a,b);
(P
ar

cout<<a<<”,”<<b;
m

2002: }
Ku

Ans: Output:
er
nd

18,4
re

1.b)Name the header files of C++ to


Vi

which the following functions belong:


2 f)Write a function called zero_Small()
(i)get( ) (ii)open( ) that has two integer arguments being
(iii)abs( ) (iv)strcat( ) passed by reference and sets the smaller
Ans: (i)get( ) - iostream.h of the two numbers to 0. Write the main
(ii)open( ) - fstream.h program to access this function.
(iii)abs( ) - math.h, stdlib.h 4
(iv)strcat( ) - string.h #include<iostream.h>
#include<conio.h>
1.c)Find the syntax error(s), if any, in the void zero_Small(int &A,int &B)
following program. { if(A<B)
2 A=0;
else
#include<iostream.h> B=0;
void main( ) }
{ int x; void main( )
cin>>x; { clrscr();
for( int y=0,y<10,y++) int a,b;
cout<<x+y; cout<<”Enter any two values…”;
} cin>>a>>b;
cout<<"Initial values of a and b are ";
Ans: cout<<a<<" "<<b<<endl;
#include<iostream.h> zero_Small(a,b);
void main( ) cout<<endl<<"The final values of a and
{ int x; b are ";
19 XII Computer
cout<<a<<","<<b; getch();
cout<<endl; }
cout<<"\nPress any key to continue..."; double SUMFIN(int x1,int n1)
getch(); { double sum=0;
} int c=0;
for(int i=1;i<=(2*n1);i=i+2)
2001: { c=c+1;
if(c%2==1)
1.b) Name the header file to be included { sum=sum+(pow(x1,i))/i;
for the use of the following built in }
functions: else
(i)getc( ) (ii)strcat() { sum=sum-(pow(x1,i))/i;
1 }
Ans: }
(i) getc( ) - stdio.h return sum;
(ii) strcat( ) - string.h }

1.e) Give the output of the following 1.e)Give the output of the following
program: program. 3
#include<iostream.h>
#include<conio.h> #include<iostream.h>
int g=20; #include<conio.h>
void func(int &x,int y) int g=20;
{ x=x-y; void func(int &x,int y)
y=x*10; { x=x-y;
cout<<x<<’,’<<y<<’\n’; y=x*10;
cout<<x<<’,’<<y<<’\n’;
S)

}
C

void main( ) }
T
G

{ int g=7; void main( )


(P

{ int g=7;
ar

func(g,::g);
m

cout<<g<<’,’<<::g<<’\n’; func(g,::g);
Ku

func(::g,g); cout<<g<<’,’<<::g<<’\n’;
er
nd

cout<<g<<’,’<<::g<<’\n’; func(::g,g);
re

} cout<<g<<’,’<<::g<<’\n’;
Vi

Ans: Output: }
-13,-130
2000:
-13,20
33,330 1.b) Name the header file, to which
-13,33 following built in function belong:
2
1.f) Write a function named SUMFIN( ), (i) isupper( ) ( ii)setw()
with arguments x, N, which returns the (iii)exp( ) (iv)strcmp( )
sum of N terms of the following series.: Ans) (i) isupper( ) - ctype.h
4 (ii)setw( ) - iomanip.h
x – x^3/3 + x^5/5 – x^7/7 + x^9/9 (iii)exp( ) - math.h
#include<iostream.h> (iv)strcmp( ) - string.h
#include<math.h>
#include<conio.h> 1.c)Will the following program execute
double SUMFIN(int x1,int n1); successfully?If not, state the eason(s) 2
void main() #include<stdio.h>
{ int x; void main( )
int n; { int s1,s2,num;
clrscr(); s1=s2=0;
cout<<"Enter the vaue of X and N"; for(x=0;x<11;x++)
cin>>x>>n; { cin<<num;
cout<<”\nThe sum of Series = if(num>0)s1+=num;else
“<<SUMFIN(x,n); s2=/num;
20 XII Computer
} q=func(p);
cout<<s1<<s2; cout<<p<<q<<endl;
} }
Ans: The program will not execute Ans: Output: 2023
successfully.
Because some syntax errors are there in
1023
the program. They are 1111
(i)cin and cout, stream objects used but
iostream.h header file is not included in f) Write a function seqsum( ) in C++ with
the program. two arguments, double x and int n. The
(ii)x is not declared, it should be declared function should return a value of type
as int. double and it should find the sum of the
(iii)With cin, we should use >> instead of following series. 4
<<. 1+ x/2! + x2/4! + x3/6! + x4/8! + x5/10! + ----+
xn/(2n)!
(iv)The shorthand operator /=, is given
#include<iostream.h>
wrongly as =/.
#include<math.h>
#include<conio.h>
So the corrected program is as follows:
double seqsum(int x1,int m1);
#include<iostream.h>
void main()
void main( )
{ int x;
{ int s1,s2,num;
int m;
s1=s2=0;
clrscr();
for(int x=0;x<11;x++)
cout<<"Enter the vaue of X and M";
{ cin>>num;
cin>>x>>m;
if(num>0)s1+=num;else s2/=num;
cout<<"\nThe sum of the series =
}
"<<seqsum(x,m);
cout<<s1<<s2;
S)

getch();
C

}
}
T
G
(P

double seqsum(int x1,int m1)


d)Give the output of the following
ar

{ double sum=1;
m

program segment(Assuming all required


Ku

for(int i=1;i<=m1;i++)
header files are included in the program):
er

{ int f=1;
nd

2
for(int j=1;j<=2*i;j++)
re

char *NAME=”a ProFiLe”;


Vi

{ f=f*j;
for(int x=0;x<strlen(NAME);x++)
}
if(islower(NAME[x]))
sum=sum+pow(x1,i)/f;
NAME[x]=toupper(NAME[x]);
}
else if(isupper(NAME[x]))
return sum;
if(x%2!=0)
}
NAME[x]=tolower(NAME[x-1]);
else
NAME[x]--; 1999 Annual Paper:
cout<<NAME<<endl;
1.a) Why main( ) function is so special.
Ans: Output: AOROoIiE Give two reasons?
1
1.e)Write the output of the following Ans: Execution of the program starts and
program3 ends at main( ). The main( ) is the driver
#include<iostream.h> function of the program. If it is not
int func(int &x,int y=10) present in a program, no execution can
{ if(x%y==0) return ++x;else return y- take place.
-;
} 1.b) Name the header file of C++ to which
void main( ) following functions belong. (i)strcat( )
{ int p=20,q=23; (ii) scanf( ) (iii) getchar( )
q=func(p,q); (iv)clrscr( )
cout<<p<<q<<endl; Ans: (i)strcat( ) - string.h
p=func(q); (ii)scanf( ) - stdio.h
cout<<p<<q<<endl; (iii)getchar( ) - stdio.h
21 XII Computer
(iv)clrscr( ) - conio.h x=n/10;
y=n%10;
1.c) Find the syntax error(s), if any, in the binary(x);
following program: binary(y);
#include<iostream.h> getch( );
main( ) }
{ int x[5],*y,z[5];
for(i=0;i<5;i++) 1998 Annual Paper:
{ x[i]=i;
z[i]=i+3; 1.b)Name the header files, to which the
y=z; following built in functions belongs to:
x=y; (i)cos( ) (ii)setw( )
} (iii)toupper( ) (iv)strcpy( )
} Ans: (i) cos( ) - math.h
Ans (i) Line No 5: Undefined symbol ‘i’. (ii) setw( ) - iomanip.h
The variable ‘i’ is not declared in the (iii) toupper( ) - ctype.h
program. (iv) strcpy( ) - string.h
(ii)Line No 10:Assign the value of a
pointer to an integer variable. Ie error in 1.c)Find the syntax error(s), if any, in the
x=y. following program:
include<iostream.h>
1.e) Write the output of the following void main( )
program. { int R; W=90;
#include<iostream.h> while W>60
static int i=100; { R=W-50;
void abc( ) switch(W)
{ static int i=8;
S)

{ 20:cout<<”Lower Range”<<endl;
C

cout<<”first =”<<I; 30:cout<<”Middle Range “<<endl;


T
G

} 40:cout<<”Higher Range”<<endl;
(P

main( )
ar

} }
m

{ static int i=2; }


Ku

abc( ); Ans:
er
nd

cout<<”second =”<<i<<endl; (i) Line 1: It should be,


re

}
Vi

#include<iostream.h>
Ans: Output: (ii) Line 4:Variables should be
First =8second =2 separated using commas.
It should be int R,W=90;
1.f) Write a C++ function that converts a (iii) Line 5:Test expression
2-digit octal number into binary number should be in braces. It
and prints the binary equivalent. should be while (W>60)
#include<iostream.h> (iv) Line 10:It should be case
#include<conio.h> 20;
void binary(int a) (v) Line 11:It should be case
//member function for conversion 30;
{ int i,b[5]; //integer array 6 (vi) Line 13:It should be case
for(i=3;i>=1;i--) 40;
{ b[i]=a%2;
a=a/2; So the corrected version of the program is as
follows:
}
#include<iostream.h>
for(i=1;i<=3;i++)
void main( )
cout<<b[i];
{ int R, W=90;
}
while (W>60)
void main()
{R=W-50;
{ int n,x,y;
switch(W)
clrscr( );
{ case 20:cout<<”Lower Range”<<endl;
cout<<"Enter a two digit octal number:
case 30:cout<<”Middle Range
";
“<<endl;
cin>>n;
22 XII Computer
case 40:cout<<”Higher Range”<<endl; {
} } clrscr( );
} float x1;
int n1;
1.d) Give the output of the following program cout<<"\nEnter the value of X and N";
segment: char *NAME=”IntRAneT”; cin>>x1>>n1;
for(int x=0;x<strlen(NAME); x++) cout<<"\nThe Sum of the Series
if(islower(NAME[x]) ..."<<sum_series(x1,n1);
NAME[x]=toupper(NAME[x])); getch( ); }
else if(isupper(NAME[x]))
if(x%2==0) Model Paper 1 for 2008-09
NAME[x]=tolower(NAME[x]);
else
Batch:
NAME[x]=NAME[x-1];
Q1. (a) What is the difference between
puts(NAME);
Global Variable and Local Variable?
Ans: Output: INTTaNEE 2
Answer:
1.f) Write the output of the following Global Variable Local Variable
program: • It is a variable, • It is a variable,
#include<iostream.h> which is declared which is declared
void Execute(int &X,int Y=200) outside all the with in a function
{ int TEMP=X+Y; functions or with in a
X+=TEMP; compound
if(Y!=200) statement
cout<<TEMP<<X<<Y<<endl;
• It is accessible • It is accessible
}
throughout the only within a
S)

void main( )
program function/compoun
C

{ int A=50,B=20;
T

d statement in
G

Execute(B);
(P

which it is
ar

cout<<A<<B<<endl;
declared
m

Execute(A,B);
Ku

#include <iostream.h>
cout<<A<<B<<endl;
er

float NUM=900; //NUM is a global variable


nd

}
re

void LOCAL(int T)
Vi

{ int Total=0; //Total is a local variable


1.f) Write a C++ function having two
for (int I=0;I<T;I++)
value parameters X and N with result
Total+=I;
type float to find the sum of series given
cout<<NUM+Total;
below:
1 + x1/2! + x2/3! + x3/4! + x4/5! + - - - - - - xn/
}
(n+1)! void main()
#include<iostream.h> { LOCAL(45);
#include<conio.h> }
#include<math.h>
float sum_series(float X,int N) //function 1.b)Write the names of the header files to
being declared which the following belong:
{ float sum=0,term; 1
int fact,f; (i) strcmp() (ii) fabs()
sum+=1; Answer: (i)string.h (ii) math.h
for(int i=1;i<=N;i++)
{ fact=1; 1(d) Find the output of the following
for(f=1;f<=(i+1);f++) program:
fact*=f; 3
term=pow(X,i)/fact; #include <iostream.h>
sum+=term; struct PLAY
} {
return(sum); int Score, Bonus;
} };
void main( ) void Calculate(PLAY &P, int N=10)
{
23 XII Computer
P.Score++; Guessme=random(N)+10;
P.Bonus+=N; cout<<Guessme<<endl;
} }
void main() Answer:
{ Maximum Value:24 Minimum
PLAY PL={10,15}; Value:10
Calculate(PL,5);
Model Paper 2 for 2008-09
cout<<PL.Score<<”:”<<PL.Bonus<<endl; Batch:
Calculate(PL);
1.b)Write the names of the header files to
cout<<PL.Score<<”:”<<PL.Bonus<<endl; which the following belong:
Calculate(PL,15); 1
(i) frexp() (ii) isalnum()
cout<<PL.Score<<”:”<<PL.Bonus<<endl; Answer:
} (i) math.h (ii) ctype.h
Answer:
11:20 1.d)Find the output of the following
program3
12:30 #include <iostream.h>
13:45 void Changethecontent(int Arr[], int
Count)
1.e)Find the output of the following {
program 2 for (int C=1;C<Count;C++)
Arr[C-1]+=Arr[C];
#include <iostream.h> }
S)
C

#include <ctype.h> void main()


T
G

void Encrypt(char T[]) {


(P

{ for (int i=0;T[i]!='\0';i+=2) int A[ ]={3,4,5},B[ ]={10,20,30,40},C[ ]


ar
m

if (T[i]=='A' || T[i]=='E') ={900,1200};


Ku

T[i]='#'; Changethecontent(A,3);
er

Changethecontent(B,4);
nd

else if (islower(T[i]))
re

T[i]=toupper(T[i]); Changethecontent(C,2);
Vi

else for (int L=0;L<3;L++)


T[i]='@'; cout<<A[L]<<’#’;
} cout<<endl;
void main() for (L=0;L<4;L++)
{ char Text[]="SaVE EArtH"; cout<<B[L] <<’#’;
//The two words in the string Textare cout<<endl;
separated by single space for (L=0;L<2;L++)
Encrypt(Text); cout<<C[L] <<’#’;
cout<<Text<<endl; }
}
Answer: Answer:
7#9#5#
@a@E@E#rTH
30#50#70#40#
2100#1200#
1.f)In the following program, if the value
of N given by the user is 15, what
1.(e)Find the output of the following
maximum and minimum values the
program:2
program could possibly display?
#include <iostream.h>
2
struct Game
#include <iostream.h>
{
#include <stdlib.h>
char Magic[20];int Score;
void main()
};
{ int N,Guessme;
void main()
randomize();
{
cin>>N;
24 XII Computer
Game M={“Tiger”,500};
char *Choice; #include <iostream.h>
Choice=M.Magic; float NUM=900; //NUM is a global
Choice[4]=’P’; variable
Choice[2]=’L’; void LOCAL(int T)
M.Score+=50; {
cout<<M.Magic<<M.Score<<endl; int Total=0; //Total is a local
Game N=M; variable
N.Magic[0]=’A’;N.Magic[3]=’J’; for (int I=0;I<T;I++)
N.Score-=120; Total+=I;
cout<<N.Magic<<N.Score<<endl; cout<<NUM+Total;
} }
Answer: void main()
TiLeP550 {
LOCAL(45);
AiLJP430 }

1.f)In the following program, if the value 1.b) Which C++ header file(s) will be
of N given by the user is 20, what essentially required to be included to
maximum and minimum values the run /execute the following C++ code:
program could possibly display? 1
2 void main()
#include <iostream.h> {
#include <stdlib.h> char Msg[ ]="Sunset Gardens";
void main() for (int I=5;I<strlen(Msg);I++)
{ int N,Guessnum; puts(Msg);
randomize(); }
S)

cin>>N;
C

A) (i) string.h (ii) stdio.h


T

Guessnum=random(N-10)+10;
G
(P

cout<<Guessnum<<endl; 1. d) Find the output of the following


ar

}
m

program:3
Ku

Answer: #include <iostream.h>


er

Maximum Value:19 Minimum


nd

struct GAME
re

Value:10 {
Vi

int Score, Bonus;


};
Sample Paper 1 for 2009-10: void Play(GAME &g, int N=10)
{
1.a) What is the difference between g.Score++;
Global Variable and Local Variable? Also, g.Bonus+=N;
give }
a suitable C++ code to illustrate both. void main()
2 {
Ans) Global Variable: GAME G={110,50};
* It is a variable which is declared outside Play(G,10);
all the cout<<G.Score<<":"<<G.Bonus<<endl
Functions ;
* It is accessible throughout the program Play(G);
cout<<G.Score<<":"<<G.Bonus<<endl
;
Local Variable: Play(G,15);
* It is a variable which is declared with in cout<<G.Score<<":"<<G.Bonus<<endl
a ;
function or with in a compound }
statement A)
* It is accessible only within a function/ 111:60 3
compound statement in which it is 112:70
declared
25 XII Computer
113:85 1.(a) What is the difference between
Actual Parameter and Formal
Parameters? Also, give a suitable C++
e) Find the output of the following code to illustrate both 2
program: 2
#include <iostream.h> A) Actual Parameter Formal Parameter 2
void Secret(char Str[ ]) * It is a parameter, which is used in
{ function call to send the value from
for (int L=0;Str[L]!='\0';L++); calling environment
for (int C=0;C<L/2;C++) * It is a parameter, which is used in
if (Str[C]=='A' || Str[C]=='E') function header, to receive the value
Str[C]='#'; from actual parameter
else
{ #include <iostream.h>
char Temp=Str[C]; void Calc(int T) //T is formal parameter
Str[C]=Str[L-C-1]; {
Str[L-C-1]=Temp; cout<<5*T;
} }
} void main()
void main() {
{ int A=45;
char Message[ ]="ArabSagar"; Calc(A);//A is actual parameter
Secret(Message); }
cout<<Message<<endl;
} (b) Write the names of the header files to
which the following belong:
1
S)

A) #agaSbarr
C

(i) frexp() (ii) isalnum()


T
G

A) (i) math.h (ii) ctype.h


(P
ar

f) In the following program, if the value of


m

(c) Rewrite the following program after


Ku

Guess entered by the user is 65, what will


removing the syntactical errors (if any).
er

be the expected output(s) from the


nd

Underline each correction.


following options (i), (ii), (iii) and (iv)?
re

2
Vi

2
#include <iostream.h>
#include <iostream.h>
#include <stdlib.h>
struct Pixels
void main()
{ int Color,Style;}
{
void ShowPoint(Pixels P)
int Guess;
{ cout<<P.Color,P.Style<<endl;}
randomize();
void main()
cin>>Guess;
{
for (int I=1;I<=4;I++)
Pixels Point1=(5,3);
{
ShowPoint(Point1);
New=Guess+random(I);
Pixels Point2=Point1;
cout<<(char)New;
Color.Point1+=2;
}
ShowPoint(Point2);
}
}
(i) ABBC
(ii) ACBA
Ans:
(iii) BCDA
#include <iostream.h> 2
(iv) CABD
struct Pixels
A)
{
(i) ABBC int Color,Style;
};
Sample Paper 2 for 2009-10 void ShowPoint(Pixels P)
Batch: {
cout<<P.Color<<P.Style<<endl;

26 XII Computer
} cout<<N.Magic<<N.Score<<endl;
void main() }
{ A)
Pixels Point1={5,3}; TiLeP550
ShowPoint(Point1);
Pixels Point2=Point1;
AiLJP430
Point1.Color+=2;
(f) In the following program, if the value
ShowPoint(Point2);
of N given by the user is 20, what
}
maximum and minimum values the
program could possibly display?
2
(d) Find the output of the following
program: 3
#include <iostream.h>
#include <iostream.h>
#include <stdlib.h>
void Changethecontent(int Arr[ ], int
Count)
{
void main()
for (int C=1;C<Count;C++)
{
Arr[C-1]+=Arr[C];
int N,Guessnum;
}
randomize();
void main()
cin>>N;
{
int Guessnum=random(N-10)+10;
A[]={3,4,5},B[]={10,20,30,40},C[]={900,1200} cout<<Guessnum<<endl;
; }
Changethecontent(A,3); A)
Changethecontent(B,4); Maximum Value: 19 Minimum Value: 10
S)

Changethecontent(C,2);
C
T

for (int L=0;L<3;L++) cout<<A[L]<<'#'; Header files – Important Functions.


G
(P

cout<<endl; From Old Papers


ar

for (L=0;L<4;L++) cout<<B[L] <<'#'; Name the header files that shall be
m
Ku

cout<<endl; needed for the following


er

for (L=0;L<2;L++) cout<<C[L] <<'#'; 2009 Outside Delhi:


nd
re

} (i) setw( ) – iomanip.h


Vi

Ans: (ii) sqrt( ) – math.h


7#9#5# 2008 Delhi & OD:
Due to cout, include iostream.h
30#50#70#40# Due to setw( ), include iomanip.h
2100#1200# 2007 Delhi & OD:
Due to strcat( ), include string.h
(e) Find the output of the following Due to gets( ), include stdio.h
program: 2 2006 Delhi:
#include <iostream.h> (i) abs( ) - math.h, stdlib.h
struct Game (ii) isupper( ) – ctype.h
{ 2006 Outside Delhi
char Magic[20];int Score; (i) abs( ) - math.h, stdlib.h
}; (ii) random( ) - stdlib.h
void main() 2005 Delhi:
{ (i) abs( ) - stdlib.h, math.h
Game M={"Tiger",500}; (ii) strcmp( ) - string.h
char *Choice; 2005 OD:
Choice=M.Magic; (i) puts( ) - stdio.h
Choice[4]='P'; (ii) isalnum( ) - ctype.h
Choice[2]='L'; 2004 :
M.Score+=50; (i) gets( ) - stdio.h
cout<<M.Magic<<M.Score<<endl; (ii) strcmp( ) - string.h
Game N=M; (iii) abs( ) - math.h, stdlib.h
N.Magic[0]='A';N.Magic[3]='J'; (iv) isalnum( ) - ctype.h
N.Score-=120;
27 XII Computer
2003: bad( ) eof( ) fail( ) good( )
(i) strcmp( ) - string.h clear( )
(ii) getc( ) - stdio.h
2002: stdio.h (Many of the functions starting
(i) get( ) - iostream.h with f)
(ii) open( ) - fstream.h printf( ) scanf( )
(iii) abs( ) - math.h, stdlib.h fflush( ) fgetc( ) fgetchar( ) fgets( )
(iv) strcat( ) - string.h fopen( ) fprintf( ) fputc( ) fputchar( )
2001: fputs( ) fread( ) freopen( ) fscanf( ) fseek(
(i) getc( ) - stdio.h ) fsetpos( ) fwrite( ) ftell( )
(ii) strcat( ) - string.h fwrite( ) getc( ) getchar( ) gets( ) getw(
2000: ) putc( ) putchar( ) puts( ) putw( )
(i) isupper( ) - ctype.h remove( ) rename( )
(ii) setw( ) - iomanip.h
(iii) exp( ) - math.h conio.h
(iv) strcmp( ) - string.h clrscr( ) getch( ) gotoxy( ) cprintf( )
1999:
(i) strcat( ) - string.h dos.h
(ii) scanf( ) - stdio.h sound( ) nosound( ) delay( )
(iii) getchar( ) - stdio.h
(iv) clrscr( ) - conio.h process.h
1998: exit(0)
(i) cos( ) - math.h
(ii) setw( ) - iomanip.h math.h
(iii) toupper( ) - ctype.h acos( ) acosl( ), etc, etc div( ) exp( )
(iv) strcpy( ) - string.h ceil( ) ceill( ) fabs( ) floor( ) fmod( )
log( ) pow( ) modf( ) poly( ) sqrt( )
S)

Model Paper 1:
C

(i) strcmp( ) – string.h


T
G

(ii) fabs( ) – math.h “ The fear of the


(P

Lord
ar

Model Paper 2:
m

(i) frexp( ) – math.h is the beginning of wisdom”


Ku

(ii) isalnum( ) – ctype.h


er
nd

***All the best My Dear Children***


re
Vi

ctype.h (Character functions)


isalnum( ), isalpha( ), isdigit( ), islower( ), 2.OBJECT ORIENTED
isupper( ), tolower( ), toupper( ) PROGRAMMING
&
string.h (Generally starts with str) 3. FUNCTION OVERLOADING
strcat( ), strcmp( ), strcpy( ), strlent( ),
strchr( ), stricmp( ), strlwr( ), strew( ),
strupr( ) 2010 Delhi:
iomanip.h 2. (a) What do you understand by
setw( ), setprecision( ), endl, flush( ). Polymorphism? Also, give an example in
C++
stdlib.h to illustrate the same.
abs( ), labs( ), free( ), random( ), atof( ), 2
atoi( ), atol( ),strtol( ), strtod( ), Ans. The process of using an -operator or
calloc( ),malloc(), realloc( ) a function in different ways for different
set of inputs given is known- as
iostream.h polymorphism. Function overloading is-
(cout,cin – these are streams available in an example of polymorphism, where the
iostream.h) functions having same name with
get( ) getline( ) read( ) write( ) different set of parameters perform
put( ) different operations.
open( ) close( ) flush( ) Example:
seekg( ) seekp( ) tellg( ) tellp( ) void Disp ( ) //Function 1
{ cout<<“Hello”<<endl;
28 XII Computer
} When a function is having more than one
void Disp(int N) //Function 2 definition and differentiable by the
{ for(int I=1;I<=N;I++) number/type of parameters is known as
cout<<I<<endl; function overloading
} Example:
void Disp (int N,int M) //Function 3 void Disp() //Function 1
{ for (int I=N;I<=M; I++) { cout<<”Hello”<<endl;
cout<<N<<“x”<<I<<“=”<<N*I<<en }
dl; void Disp(int N) // Function 2
} { for (int I=1;I<=N;I++)
void main ( ) cout<<I<<end1;
{ int x=5, y=10; }
Disp(x); //Function 2 called- void main ()
Prints { int x=5;
// numbers from 1 to 5 Disp(x);//call for Function 2 -
Disp(x,y) ; //Function 3 called- Prints
Prints //numbers from 1 to 5
//from multiples of 5 ranging from 5 to Disp(); //call for Function 1 - Prints
10 Hello
Disp () ; //Function 1 called- }
Prints Hello
} 2005 Delhi:
2.a) Define the term Data Hiding in the
2010 Outside Delhi: context of Object Oriented Programming.
2. (a) What do you understand by Data Give a suitable example using a C++code
Encapsulation and Data Hiding ?’ Also, to illustrate the same2
S)

give an example in C++ to illustrate both. Ans: A class groups its members into
C

2 three sections: private, protected and


T
G

Ans. Data Encapsulation: Wrapping up public. The private and protected


(P
ar

of data and functions together in a single members remain hidden from outside
m

unit is known as Data Encapsulation. In a world. Thus through private and


Ku

class, we wrap up the data and functions protected members, a class enforces data
er
nd

together in a single unit. – hiding. (The outside world is given only the
re

Data Hiding: Keeping the data in essential and necessary information through
Vi

private/protected visibility mode of the public members, rest of the things remain
class hidden, which is nothing but abstraction. The
to prevent it from accidental change is act of representing only essential features
without including background details is
known as Data Hiding.
known as abstraction.)
class Computer Eg: class ABC
{ char CPU[lO] ;int RNM; //Data { private: int a,b;
Hiding protected: int c,d;
public: //Data public: int e,f;
Encapeulation void disp( )
void STOCK(); {
void SHOW(); ----
}; }
-----
}
2009 Outside Delhi: In the above class public members(ie
e,f and disp( )) only will be available to
2. (a) What is function overloading? Give outside the class.. The other private
an example in C++ to illustrate function members (a,b), protected members (c,d)
overloading. will not be available to outside the class.
2 This concept is called data hiding.
Ans Function overloading is an example
of polymorphism, where the functions
having same name with different set of
2005 Outside Delhi:
parameters perform different operations.
OR
29 XII Computer
2.a) Define the term Data Encapsulation Ans:Polymorphism is the attribute that
in the context of Object Oriented allows one interface to be used with
Programming. Give a suitable example different situation.C++ implements
using a C++ code to illustrate the same. polymorphism through virtual functions,
2 through overloaded functions and
Ans: Encapsulation is wrapping up of overloaded operators.
characteristics and behavior into one A virtual function is used to specify
unit. While implementing encapsulation, the interface in abstract class, but its
following things are taken care: implementation details are made
a) Anything that an object does not available by the concrete class(es).
know or An overloaded function refers to a
cannot do is excluded from the function having (one name and) more
objects. than one distinct meanings. Similarly,
b)Encapsulation is used to hide when two or more distinct meanings are
unimportant defined for an operator, it is said to be an
implementation details from other ‘overloaded operator’. It is the compiler’s
objects. job to select the specific action as it
c)Packaging an object’s variables within applies to each situation.
the protective custody of its methods Eg: The program in the next answer.
is called encapsulation and this task is
accomplished through classes. Ie the 2003:
data and associated functions are
wrapped up in one unit called
class. 2.a) What do you understand by function
A class binds together data and overloading? Give an example illustrating
its associated functions under one unit its use in a c++ program.
thereby enforcing encapsulation.
S)

Ans: A function name having several


C

Eg:class Rectangle
T

definitions that are differentiable by the


G

{ private: float len,bre,area;


(P

public: void readData( ) number or types of their arguments, is


ar

{ cout<<”\nEnter the length and known as an overloaded function and this


m
Ku

breadth..”; process is known as function overloading.


er

cin>>len>>bre; Function overloading not only


nd

}
re

implements polymorphism but also


Vi

void calculate( )
reduces number of comparisons in a
{ area=len*bre;
}
program and thereby makes the program
void display( ) run faster.
{ cout<<”\nThe area of the rectangle =
“<<area; Example program illustrating function
} overloading:
};
Eg: Here in the above class the data //Program to find out area of a circle or
members ie len,bre,area and the member area of //rectangle using function
functions ie readData( ), calculate( ), overloading.
display( ) are bind together in a class
named as Rectangle. Ie The member #include<iostream.h>
functions can access any data member in #include<conio.h>
the class. void area(float r)
Benefits with encapsulation: {
(i) Modularity. cout<<”\nThe area of the circle =
(ii) Information hiding. “<<3.1415*r*r; }
void area(float l,float b)
2004: {
cout<<”\nThe area of the rectangle
1.a) What is polymorphism? Give an =
example in C ++ to show its “<<l*b; }
implementation in C++. void main( )
{
float rad,len,bre;
30 XII Computer
int n; Model Paper 1 for 2008-09
clrscr( );
cout<<”\n1. Area of a Circle…”;
Batch:
cout<<”\n2. Area of a Rectangle…”;
Q2.(a) What do you understand by
cout<<”\n\nEnter your choice: “;
Data Encapsulation and Data Hiding?
cin>>n;
2
switch(n)
Answer:
{
case 1: cout<<”\nEnter the radius: Data Encapsulation: Wrapping up
“; of data and function together in a
cin>>rad; single unit is known as Data
area(rad); Encapsulation. In a class, we wrap
break; up the data and function together
case 2: cout<<”\nEnter the length in a single unit.
and breadth: “; Data Hiding: Keeping the data in
cin>>len>>bre; private visibility mode of the class
area(len,bre); to prevent it from accidental
break; change is known as Data Hiding.
default: cout<<”\nYou have to
enter class Computer
either 1 or 2”; {
} //end of switch char CPU[10]; Data Hiding
getch( ); int RAM;
} public:
void STOCK();
void SHOW();
2000: };
Data Encapsulation
S)
C

1.a) Illustrate the concept of function


T

Model Paper 2 for 2008-09


G

overloading with the help of an example.


(P

Batch:
ar

1
m

Ans: The above answer.


Ku

1. (a) What is the difference between


er
nd

1998: Object Oriented Programming and


re
Vi

Procedural Programming?
1.a) Define the following terms: 2
(i) Inheritance (ii)Encapsulation.
Ans:a) Inheritance: The capability of Answer:
one class to inherit properties from
another class is called as inheritance.The Object Oriented Procedural Programming
class inheritance, lets you generate a Programming
model that is closer to the real world. • Emphasis on Data • Emphasis on doing
things (functions)
The class inheritance lets you derive new
• Follows Bottom-Up • Follows Top-down
classes (derived class) from old ones
approach in approach in program
(base class), with the derived class program design design
inheriting the properties, including the • Data hiding feature • Presence of Global
methods of the old class. prevents accidental variables increase
Uses of Inheritance: change in data chances of accidental
i)Capability to express the inheritance change in data
relationship which ensures the closeness • Features like data • Such features are not
with the real world models. encapsulation, available
ii) Reusability. polymorphism,
iii)Transitive nature of inheritance. inheritance are
b) Encapsulation: The wrapping up of present
data and functions into a single unit
(class) is called as encapsulation. 2.(a)What do you understand by
Polymorphism? Give a suitable example
of the same.
2
31 XII Computer
Answer: (method) to work using different set of
Polymorphism: It is a method of inputs. Function overloading is one of the
using the same operator or examples of polymor-phism, where more
function (method) to work using than one function carrying same name
different sets of input. Function behave differently with different set of
overloading is one of the example parameters passed to them.
of polymorphism, where more
than one function carrying same void Display()
name behave differently with {
different set of parameters cout<<"Hello!"<<endl;
passed to them. }
void Display() void Display(int N)
{ {
cout<<”Hello!”<<endl; cout<<2*N+5<<endl;
} }
void Display(int N) “The moment which is lost,
{ is lost for ever.
cout<<2*N+5<<endl; So utilize the time
} properly”

Sample Paper 1 for 2009-10 4.CLASSES AND OBJECTS


Batch:
2010 Delhi:
2.a) What do you understand by Data
Encapsulation and Data Hiding? Also, 1.(c) Rewrite the following c++ program
S)
C

give a suitable C++ code to illustrate both. code after removing the syntax error(s)
T
G

2 (if any). Underline each correction.


(P

2
ar
m

A) Data Encapsulation: Wrapping up of include <iostream.h>


Ku

data and functions together in a single class TRAIN


er

{
nd

unit is known as Data Encapsulation. In a


re

class, we wrap up the data and functions long TrainNo;


Vi

togetherin a single unit. char Description[25];


public
Data Hiding: Keeping the data in private void Entry ( )
visibility mode of the class to prevent it {
fromaccidental change is known as Data cin >>TrainNo; gets(Description);
Hiding. }
class Computer Void Display ( )
{ {
char CPU[10];int RAM; //Data Hiding cout<<TrainNo<<“:”<<Description<<endl
public: //Data ;
Encapsulation }
void STOCK(); };
void SHOW(); void main( )
}; {
TRAIN T;
Sample Paper for 2009-10 Entry. T( ); Display. T( );
}
Batch: Ans.
#include<iostream.h>
2.a) What do you understand by #include<stdio.h>
Polymorphism? Give a suitable example class TRAIN
of the same. 2 {
long TrainNo;
Ans) Polymorphism: It is a method of char Description [25];
using the same operator or function
32 XII Computer
public: GetOffer() ;
void Entry () }
{ void ShowItern ( )
cin>>TrainNo; gets {
(Description); cout<<Code<<Iname<<Price<<Qty<<
} Offer;
void Display () };
{ void ITEM: : GetOffer ()
cout<<TrainNo<<“:”<<Description<< {
end1; if (Qty<=50)
} Offer = 0;
}; else if (Qty <=100)
void main () Offer = 5; / /OR Offer =
{ 0.05;
TRAIN T; else
T.Entry(); Offer = 10; / /OR Offer =
T.Display(); 0.1;
} }

2.c) Define a class ITEM in C++ with 2010 Outside Delhi:


following description:
4 1. (c) Rewrite the following C++ program
Private Members code after removing the syntax error(s)
_ Code of type integer (Item Code) (if any). Underline each correction.
_ Iname of type string (Item Name) 2
_ Price of type float (Price of each item) include <iostream.h>
_ Qty of type integer (Quantity of item in class FLIGHT
S)

stock)
C

{
T

_ Offer of type float (Offer percentage on the


G

long FlightCode;
(P

item)
char Description[25];
ar

_ A member function GetOffer() to


m

public
Ku

calculate Offer percentage as per the


void AddInfo ( )
er

following rule:
nd

{
re

If Qty<=50 Offer is 0
cin>>FlightCode; gets (Description) ;
Vi

If 50<Qty<=100 Offer is 5
{
If Qty>100 Offer is 10
void ShowInfo ()
Public Members
(
_ A function GetStock() to allow user to
cout<<FlightCode<<“:”<<Description<<e
enter values for Code, Iname, Price, Qty
ndl;
and call function GetOffer() to calculate
}
the offer
};
_ A function ShowItem() to allow user to
void main()
view the content of all the data members
{
Ans.
FLIGHT F;
class ITEM
AddInfo.F(); ShowInfo.F();
{
}
int Code;
Ans.
char Iname [20] ;
#include <iostream.h> / / Error 1
float Price;
#include <stdio.h> / / Error 2
int Qty;
class FLIGHT
float Offer;
{
void GetOffer() ;
long FlightCode;
public:
//not required if gets( ) is re-placed
void GetStock ()
with
{
//cin.getline( ) or cin
cin>>Code;
char Description[25];
gets (Iname) ;
// OR cin.getline (Iname, 80) ; OR cin>>Iname;
public : / / Error 3
cin>>Price>>Qty; void AddInfo ( )
33 XII Computer
{ void STOCK::FindDisc()
cin>>FlightCode; gets (Description) ; {
} if (Qty<=50)
void ShowInfo ( ) Discount=0;
{ else if (Qty<=100)
cout<<FlightCode<<”:”<<Description Discount=5; // =0.05;
<<endl; Else
} Discount=10; // =0.1;
}; }
void main ( ) void STOCK::ShowAll()
{ {
FLIGHT F; cout<<ICode<<’\t’<<Item<<’\t’<<Price<<’\t’<
F.AddInfo( ) ; <Qty
F. ShowInfo ( ) ; / / Error 4 <<’\t’<<Discount<<endl;
} }

2(c) Define a class STOCK in C++ with 2009 Delhi:


following description:
4 (c) Define a class RESORT in C++ with
Private Members following description:
_ ICode of type integer (Item Code) 4
_ Item of type string (Item Name)
_ Price of type float (Price of each item) Private Members
_ Qty of type integer (Quantity in stock) _ Rno //Data member to store Room No
_ Discount of type float (Discount percentage on _ Name //Data member to store
the item)
customer name
_ A member function FindDisc() to _ Charges //Data member to store per day
S)

calculate discount as per the following


C

charges
T

rule:
G

_ Days //Data member to store number of days of


(P

If Qty<=50 Discount is 0 stay


ar

If 50<Qty<=100 Discount is 5 _ COMPUTE( ) //A function to calculate’


m
Ku

If Qty>100 Discount is 10 and return Amount as Days*Charges and


er

Public Members if the value of Days*Charges is more than


nd
re

_ A function Buy() to allow user to enter 11000


Vi

values for ICode, Item, Price, Qty and call then as 1.02*Days*Charges
function FindDisc() to calculate the
Discount. Public Members
_ A function ShowAll() to allow user to _ Getinfo ( ) //A function to enter the
view the content of all the data members. content
Ans. Rno, Name ,Charges and Days
_ Dispinfo ( ) //A function to display Rno,
class STOCK Name,
{ Charges,Days and Amount (Amount
int ICode,Qty; to be
char Item[20]; displayed by calling function
float Price,Discount; COMPUTE ( ) )
void FindDisc();
public:
void Buy();
void ShowAll();
}; Ans
void STOCK::Buy() class RESORT
{ {
cin>>ICode; int Rno;
gets(Item); char Name [20];
cin>>Price; float Charges;
cin»Qty; int Days;
FindDisc(); float COMPUTE();
}
34 XII Computer
public: MyStudent( )
void Getinfo() ; {
void Dispinfo(); StudentId = 1001;
}; }
void RESORT::Getinfo() void Register( )
{ {
cin>>Rno; cin>>StudentId;
gets (Name); gets (Name);
cin>>Charges; }
cin>>Days; void Display ()
} {
void RESORT::Dispinfo() cout«StudentId<<”:“<<Name<<e
{ ndl;
cout<<Rno<<” “<<Name<<“ “<<Charges<<” }
“<<Days<< COMPUTE()<<endl; };
} void main ()
float RESORT::COMPUTE(} {
{ MyStudent MS;
float Amount = Charges*Days; MS. Register ();
if (Amount>11000) MS. Display () ;
Amount = }
1.02*Days*Charges;
return Amount; 2. (c) Define a class HOTEL in C++ with
} the following description:
4
2009 Outside Delhi: Private Members:
_ Rno //Data member to store Room No
S)
C

1.(c) Rewrite the following program after _ Name //Data member to store customer
T
G

removing the syntactical errors (if any). name


(P

Underline each correction. _ Tariff //Data member to store per day


ar
m

2 charges
Ku

include <iostream.h> _ NOD //Data member to store number of days of


er
nd

include <stdio.h> stay


re

class MyStudent _ CALC( ) /*A function to calculate and


Vi

{ return Amount as NOD*Tariff and if the


int StudentId = 1001; value of NOD*Tariff is more than 10000
char Name [20] ; then as
public 1.05*NOD*Tariff */
MyStudent( ){ } Public Members
void Register ( ) {cin>>StudentId; gets _ Checkin ( ) / / A function to enter the
(Name) ;} content
void Display ( ) {cout<<StudentId<< “:” Rno, Name, Tariff and NOD
<<Name<<end1;} _ Checkout( ) / / A function to display
}; Rno,
void main ( ) Name, Tariff,NOD and Amount
{ (Amount to
MyStudent MS ; be displayed by calling function
Register.MS( ) ; CALC( ))
MS.Display( ) ; Ans
} class HOTEL
Ans {
# include <iostream.h> int Rno;
# include <stdio.h> char Name[20];
class MyStudent float Tariff;
{ int NOD;
int StudentId; float CALC() ;
char Name[20]; public:
public : void Checkin() ;

35 XII Computer
void Checkout() ; void Register( )
}; { cin>>StudentId;
float HOTEL::CALC() gets(Name);
{ }
float Amount = Tariff*NOD; void Display( )
if (Amount>10000) { cout<<StudentId<<":"<<Name<<endl
Amount = ;
1.05*NOD*Tariff; }
return Amount; };
} void main( )
void HOTEL::Checkin() { MyStudent MS;
{ MS.Register( );
cin>>Rno; MS.Display( );
gets (Name); }
cin>>Tariff;
cin>>NOD; 2008 Delhi:
}
void HOTEL::Checkout() 2.a) Differentiate between public and
{ private visibility modes in context of
cout<<Rno<<” “<<Name<<“
Object Oriented Programming using a
“<<Tariff<<”
“<<NOD<<CALC suitable example illustrating each.
()<<endl;
} Ans: public and private visibility
modes in context of OOP:
1.c) Rewrite the following program after The visibility mode (private or public or
removing the syntactical errors (if any). protected) in the definition of the derived
S)

Underline each correction. class specifies whether the features of the


C

base class are privately derived or


T

2
G

publicly derived or protected derived.


(P
ar

include <iostream.h> The visibility modes basically control the


m

access specifier to be for inheritable


Ku

include <stdio.h>
members of base class, in the derived
er

class MyStudent
nd

{ int StudentId=1001; class.


re
Vi

char Name[20];
public Public visibility mode: The public
MyStudent( ) { } derivation means that the derived class
void Register( ) can access the public and protected
{ cin>>StudentId; members of the base class but not the
gets(Name); private members of the base class. With
} publicly derived class, the public
void Display( ) members of the base class become the
{ cout<<StudentId<<”:”<<Name<<endl public members of the derived class, and
; the protected members of the base class
} become the protected members of the
}; derived class.
void main( )
{ MyStudent MS; Private visibility mode: The private
Register.MS( ); derivation means, the derived class can
MS.Display( ); access the public and private members of
} the base class privately. With privately
Ans: derived class, the public and protected
#include <iostream.h> members of the base class become
#include <stdio.h> private members of the derived class.
class MyStudent That means the inherited members can
{ int StudentId; be accessed only through member
char Name[20]; functions of the derived class.
public:
MyStudent( ) { }
36 XII Computer
Visibilit Inheritable Inheritabl Private derived class, the public and protected
y Mode public e member ofmembers of the base class become
member protected base classprivate members of the derived class.
becomes ( in member are not That means the inherited members can
derived becomes directly be accessed only through member
class) (in derived accessiblefunctions of the derived class.
class) to derivedProtected visibility mode: The
public Public protected class. protected derivation means that the
private Private private derived class can access the public and
e private members of the base class
protectedly. With protectedly derived
public and private access specifiers in
class, the public and protected members
context of OOP: public access specifier is
of the base calss become protected
used to define any method or a variable
members of the derived class. That
which may be accessed by any member
means the inherited members are now
function of the same class and also from
not available to the outside world and
outside the class. Private access specifier
can be accessed only through the
is used to make any variable or a method
member functions of the derived class
which has a limited access within the
and the classes based upon the derived
class only.The concept of data hiding is
classes. These members can be inherited
implemented through the private access
further if any classes are inheriting from
specifier only.
the derived class.
Eg:
class student Visibility Inheritabl Inheritabl Private
{ private: Mode e public e member of
int rno; member protected base class
char name[21]; becomes member are not
( in becomes directly
S)

public:
C

int age; derived (in derived accessible


T
G

class) class) to derived


(P

void input( );
class.
ar

void display( ); protected Protected protected


m
Ku

} private Private private


er

Here, since rno and name are declared in private and protected access specifiers
nd

private, they can be accessed only inside in context of OOP:


re
Vi

the class. Since age,input( ) and private access specifier is used to make
display() are declared in public, they can any variable or a method which has a
be accessed from outside class also. limited access within the class only.
At the time of inheritance, these variables
2008 Outside Delhi: cannot be accessed (inherited) to the
derived class.
2.a) Differentiate between private and protected access specifier is used to make
protected visibility modes in context of any variable or a method which has a
object oriented programming using a limited access within the class only (here
suitable example illustrating each. like private). But at the time of
Ans: private and protected visibility inheritance, these variables can be
modes in context of OOP: inherited to the derived class.
The visibility mode (private or public or Except regarding inheritance, both access
protected) in the definition of the derived specifiers ie private and protected will
class specifies whether the features of the work same.
base class are privately derived or Eg:
publicly derived or protected derived. class student
The visibility modes basically control the { private:
access specifier to be for inheritable int rno;
members of base class, in the derived char name[21];
class. protected:
Private visibility mode: The private int age;
derivation means, the derived class can void input( );
access the public and private members of void display( );
the base class privately. With privately }
37 XII Computer
Here, since rno and name are declared in };
private, they can be accessed only inside void ADMISSION::Draw_Nos( )
the class. Since age,input( ) and display() { //Dear Students, a test for you.
are declared in protected, they also can Complete this member function.
be accessed only inside the class but they
can be inherited, where as private }
members (rno and name) cannot be
inherited. 2006 Outside Delhi:
2006 Delhi: 1.b) Illustrate the use of Inline function in
C++ with the help of an example.
2.c) Define a class named ADMISSION in 2
C++ with the following descriptions:
Ans: INLINE FUNCTIONS: The inline
Private Members: functions are a C++ enhancement
AD_NO integer(Ranges 10 – 2000) designed to speed up programs. The
NAME Array of characters(String) coding of normal functions and inline
CLASS Character functions is similar except that inline
FEES Float functions definitions start with the
keyword inline.
Public Members: The working of inline functions:
Function Read_Data( ) to read an object After writing any program, it is
of ADMISSION type. Function Display( ) first compiled to get an executable code,
to display the details of an object. which consists of a set of machine
Function Draw-Nos.( ) to choose 2 language instructions. When this
students randomly. And display the executable code is executed, the
S)

details. Use random function to generate operating system loads these instructions
C

into the computer’s memory, so that each


T

admission nos. to match with AD_NO.


G

instruction is stored in a specific memory


(P

Ans:
ar

class ADMISSION location. Thus, each instruction has a


m

particular memory address.


Ku

{ int AD_NO;
After loading the executable
er

char NAME[31];
nd

program in the computer memory, these


re

char CLASS;
Vi

float FEES; instructions are executed step by step.


public: When a function call instruction is
void Read_Data( ) encountered, the program stores the
{ cout<<"\nEnter the Admission memory address of the instruction
Number: "; immediately following the function call
cin>>AD_NO; statement, loads the function being called
cout<<"\nEnter the Student Name: "; into the memory, copies argument values,
gets(NAME); jumps to the memory location of the
cout<<"\nEnter the Class: "; called function, executes the function
cin>>CLASS; code, stores the return value of the
cout<<"\nEnter the Fees: "; function, and then jumps back to the
cin>>FEES; address of the instruction that was saved
} just before executing the called function.
void Display() With inline code, the compiler
{ cout<<"\nThe Admission Number of replaces the function call statement with
the the function code itself (this process is
student: "<<AD_NO; called expansion) and then compiles the
cout<<"\nThe name of the Student: “ entire code. Thus, with inline functions,
<<NAME; the compiler does not have to jump to
cout<<"\nThe Class of the Student:” another location to execute the function,
<<CLASS; and then jump back as the code of the
cout<<"\nThe Fees of the Student: “ called function is already available to the
<<FEES; calling program.
} Inline functions run a little faster
void Draw_Nos(); than the normal functions as function
38 XII Computer
calling overheads are saved, however Function Draw_Nos( ) to choose and
there is a memory penalty. If 10 times an display the details of 2 houses selected
inline function is called, there will be 10 randomly from an array of 10 objects of
copies of the function inserted into the type HOUSING. Use random function to
code. generate the registration nos. to match
A function can be declared inline with REG_NO from the array.
by placing the keyword inline before it.
An inline function definition should be Ans:
placed above all the functions that call it. class HOUSING
The functions should be inlined only { int REG_NO;
when they are small. Since for large char NAME[31];
functions, they will become memory char TYPE;
penalty. float COST;
public:
The inlining does not work for void Read_Data( )
following situations: { cout<<"\nEnter the House
a. For functions that return values and Registration
are having a loop or a switch or a goto. Number: ";
b. For functions not returning values, if a cin>>REG_NO;
return statement exists. cout<<"\nEnter the House Name: ";
c. If functions contain static variables. gets(NAME);
d. If the function is recursive(a function cout<<"\nEnter the House Type: ";
that calls itself). cin>>TYPE;
cout<<"\nEnter the House Cost: ";
Inlining and the member functions: cin>>COST;
The member function of a class, if }
defined within the class definition, are void Display()
S)
C

inlined by default. Therefore, only very { cout<<"\nThe Registration Number of


T
G

small member functions should be the


(P

defined within the class definition. House: "<<REG_NO;


ar
m

The member functions defined cout<<"\nThe name of the House: “


Ku

outside the class definition can be made <<NAME;


er
nd

explicitly inline by placing the keyword cout<<"\nThe Type of the House:


re

inline before their definition. "<<TYPE;


Vi

Inline functions are best for small cout<<"\nThe Cost of the House:
functions that are called often.The "<<COST;
compiler may even ignore your attempt }
to linline a function if it consists more void Draw_Nos();
than 50 lines of code. };
void HOUSING::Draw_Nos( )
2. c) Define a class named HOUSING in C+ { //Dear Students, a test for you.
+ with the following descriptions: Complete this member function.
4
}
Private Members:
REG_NO integer(Ranges 10- 2004 :
1000)
NAME Array of 2.b) Declare a class myfolder with the
characters(String) following specifications:
TYPE Character
COST Float Private members of the class:
Filenames an array of strig of
Public Members: size[10][25]
Function Read_Data( ) to rread an object (to represent all the names of files inside
of HOUSING type. myfolder)
Function Display( ) to display the details Availspace long
of an object. (to represent total number of bytes
available in myfolder)
39 XII Computer
Usedspace long name of the function must be the full
(to represent total number of bytes used name including the class name as well.
in myfolder) When a member function is defined
inside the class, the name of the function
Public members of the class: is similar to an ordinary function but it
Newfileentry() : A function to accept will become an inline function.
values of Filenames, Availspace and
Usedspace from user. 2.b) Define a class Student for the
Retavailspace(): A function that returns following specifications.
the value of total kilobytes available Private members of the Student are:
(1 kilobyte=1024 bytes) roll_no integer
Showfiles( ): A function that displays the name array of characters of size 20
names of all the files in myfolder class_st array of characters of size 8
marks array of integers of size 5
Ans: Percentage float
class myfolder Calculate( ) that calculates overall
{ char Filenames[10][25]; percentage marks and returns the
long Availspace; percentage
long Usedspace; Public Members of the Student are:
public: Readmarks reads mark and invoke the
void Newfileentry( ) calculate function
{ Displaymarks prints the data.
cout<<"\nEnter any 10 file names: ";
for(int i=0;i<=9;i++) Ans:
{cout<<"\nEnter the "<<i+1<<" file class Student
name: "; { int roll_no;
gets(Filenames[i]); char name[20];
S)
C

} char class_st[8];
T
G

cout<<"\nEnter the Available Space (In int marks[5];


(P

Kilobytes): "; float percentage;


ar
m

cin>>Availspace; float calculate( )


Ku

cout<<"\nEnter the Used Space (In { percentage=(marks[0]+marks[1]+ma


er
nd

Kilobytes): "; rks[2]+


re

cin>>Usedspace; marks[3]+marks[4])/5;
Vi

} return percentage;
long RetavailSpace( ) }
{ ret Availspace; public:
} void Readmarks( )
void Showfiles( ) { cout<<”\nEnter any 5 subject marks;
{ cout<<"\nThe names of the files in cin>>marks[0]>>marks[1]>>marks[2]
myfolder object...."; >>
for(i=0;i<=9;i++) marks[3]>>marks[4];
{ puts(Filenames[i]); calculate( );
cout<<endl; }
} void Displaymarks( )
} { cout<<”\nThe Roll Number of the
Student: “<<roll_no;
2002: cout<<”\nThe Name of the Student:”
<<name;
2.a) What do you understand about a cout<<”\nThe class of the Student: “
member function? How does a member <<class_st;
function differ from an ordinary cout<<”\n5 subject marks of the
function? student…\n”;
Ans: A member function is a function cout<<marks[0]<<”\t”<<marks[1]<<”
declared within a class. It is said to be \t”<<
defined in two ways. Ie Outside the class marks[2]<<”\t”;
and inside the class. When a member cout<<marks[3]<<”\t”<<marks[4]<<”
function is defined outside the class, the \n”;

40 XII Computer
cout<<”Percentage =”<<percentage; cout<<”\nWithdraw is not
} possible”;
}; else
{ bal_amount=bal_amount-
2001: w_amount;
cout<<”\nThe balance is
2.b) Declare a class to represent bank “<<bal_amount-w_amount;
account of 10 customers with the }
following data members. Name of the }
depositor, account number, type of void display( )
account (S for Savings and C for Current), { cout<<”\nName of the depositor: “
Balance amount. The class also contains <<name;
member functions to do the following: cout<<”\nAccount Number:
(i)To initialize data members. “<<acc_no;
(ii) To deposit money cout<<”\nAccount Type:
(iii)To withdraw money after checking “<<acc_type;
the balance (minimum balance is cout<<”\nThe balance amount is
Rs.1000) “<<bal_amount;
(iv) To display the data members. }
[Note:You are also required to give };
detailed function definitions.]
class Bank 2000 :
{ char name[15];
int acc_no; 2.b) Define a class worker with the
char acc_type; following specification.
float bal_amount; 4
S)

public: Private member of class worker:


C

void readData( ) wname 25characters


T
G

{ cout<<”\nEnter the name: “; hrwrk,wgrate float (hours worked and


(P
ar

gets(name); wagerate per hour)


m

cout<<”\nEnter the account totwage float(hrwrk*wgrate)


Ku

number: “; cakcwg() A function to find


er
nd

cin>>acc_no; hrwrk*wgrate
re
Vi

cout<<”\nEnter the account type: “; with float return type


cin>>acc_type; Public members of class worker:
cout<<”\nEnter the amount to In_data( ): A function to accept values
deposit: “; for wno, wname, hrrwrk, wgrate and
cin>>bal_amount; invoke calcwg( ) to calculate totpay.
} Out_data( ): A function to display all the
void deposit( ) data members on the screen you should
{ float deposit; give definitions of functions.
cout<<”\nEnter your account class worker
number: “; { char wname[25];
cin>>acc_no; float hrwrk,wgrate;
cout<<”\nEnter the amount to float totwage;
deposit: “; float cakcwg( )
cin>>deposit; { return hrwrk*wgrate;
bal_amount=bal_amount + deposit; }
} public:
void withdraw( ) void In_data( )
{ float w_amount; { cout<<”\nEnter Worker
cout<<”\nEnter your account number,name,
number: “; hours worked and wage rate”;
cin>>acc_no; cin>>wno;
cout<<”\nEnter amount to gets(wname);
withdraw”; cin>>hrwrk>>wgrate;
cin>>w_amount; calcwg( );
if((bal_amount-w_amount)<1000) }
41 XII Computer
void Out_data( ) Allowance: "<<HRA;
{ cout<<”\nThe Worker Number: cout<<"\nThe Salary:
“<<wno; "<<Salary;
cout<<”\nThe Name of the worker: }
“<<wname; };
cout<<”\nNumber of hours worked by
the 1998:
worker: “<<hrwrk;
cout<<”\nThe Wage Rate of the 2.b) Define a class student with the
Worker: following specifications:
“<<wgrate; Private members of class student:
cout<<”\nThe total wages of the Admno integer
worker: Sname 20 character
“<<totwage; English float
} Math float
Science float
1999 : Total float
Ctotal( ) A function to
2.b) Define a class Teacher with the calculate English + math + science with
following class specification: float return type

Private members: Public member functions of class


Name 20 characters student:
Subject 10 characters Takedata( ):Function to accept values for
Basic, DA, HRA float admno,sname, English, math, science and
Salary float invoke ctotal to calculate total.
Showdata( ):Function to display all the
S)

Calculate( ) function computes the


C

salary and returns it. Salary is sum of Basic, data members on the screen.
T
G

DA and HRA
(P

class student
ar
m

Public members: { int Admno;


Ku

ReadData( ): Function accepts the data char Sname[20];


er
nd

values and invoke the calculate function. float English,Math,Science,Total;


re

DisplayData( ):Function prints the data float Ctotal()


Vi

on the screen. { Total=English+math+science;


return Total;
class Teacher }
{ char Name[20]; public:
char subject[10]; void Takedata()
float Basic,DA,HRA,Salary; { cout<<”\nEnter the admission
float Calculate( ) number,name of the student: “;
{ Salary=Basic+DA+HRA; cin>>Admno;
return Salary; gets(sname);
} cout<<”\nEnter English, Maths,
public: Science Marks: “;
void ReadData( ) cin>>English>>Math>>Science;
{ cout<<"\nEnter Basic, Dearness Ctotal( );
Allowance and “ }
cout<<” House Rent Allowance: void Showdata( )
"; { cout<<”\nThe admission number
cin>>Basic>>DA>>HRA; of
Calculate(); the student: “<<Admno;
} cout<<”\nThe name of the
void DisplayData( ) student:
{ cout<<"\nThe Basic : "<<Basic; “<<Sname;
cout<<"\nThe Dearness cout<<”\nEnglish , Maths and
Allowance: "<<DA; Science Marks are…”;
cout<<"\nThe House Rent
42 XII Computer
cout<<english<<”\t”<<math<<”\ centers as
t” (NoCandidates/100+1)
<<science<<”\n”; Public Members
cout<<”\nTotal marks of the • A function SCHEDULE() to
student: “<<Total; allow user to enter values
}; for TestCode, Description,
NoCandidate & call
Model Paper 1 for 2008-09 function CALCNTR() to
calculate the number of
Batch:
Centres
b)Rewrite the following program after
• A function DISPTEST() to
removing the syntactical errors (if any).
allow user to view the
Underline each correction.
content of all the data
2
members
#include [iostream.h]
Answer:
class PAYITNOW
{ class TEST
int Charge; { int TestCode;
PUBLIC: char Description[20];
void Raise(){cin>>Charge;} int
void Show{cout<<Charge;} NoCandidate,CenterReqd;
}; void CALCNTR();
void main() public:
{ void SCHEDULE();
PAYITNOW P; void DISPTEST();
P.Raise(); };
Show(); void TEST::CALCNTR()
S)

} {
C
T

Answer:
G

CenterReqd=NoCandidate/100 +
(P

#include <iostream.h>
1;
ar

class PAYITNOW
m

}
Ku

{ int Charge;
void TEST::SCHEDULE()
er

public:
nd

{cout<<”Test Code :”;


void Raise(){cin>>Charge;}
re

cin>>TestCode;
Vi

void Show(){cout<<Charge;}
cout<<”Description :”;
};
gets(Description);
void main()
cout<<”Number :”;
{ PAYITNOW P;
cin>>NoCandidate;
P.Raise();
CALCNTR();
P.Show();
}
}
void TEST::DISPTEST()
{
Model Paper 1 for 2008-09 cout<<”Test
Batch: Code :”<<TestCode<<endl;
2.e)Define a class TEST in C++ with cout<<”Description :”<<Description<
<endl;
following description:
cout<<”Number :”<<NoCandidate<
4 <endl;;
Private Members cout<<”Centres :”<<CenterReqd<<
a. TestCode of type integer endl;;
b. Description of type string }
c. NoCandidate of type
integer
d. CenterReqd (number of
Model Paper 2 for 2008-09
centers required) of type Batch:
integer
e. A member function 2.d)Define a class in C++ with following
CALCNTR() to calculate description:
and return the number of 4
43 XII Computer
Private Members cout<<”Destination :”<<Destination<
*A data member Flight number of type <endl;
integer cout<<”Distance :”<<Distance<<en
*A data member Destination of type dl;;
string cout<<”Fuel :”<<Fuel<<endl;;
*A data member Distance of type float }
*A data member Fuel of type float
*A member function CALFUEL() to
calculate the value of Fuel as per the Sample Paper 1 for 2009-10
following criteria Batch:
Distance 1.C ) Rewrite the following program after
Fuel removing the syntactical errors (if any).
<=1000 Underline each correction.
500 2
more than 1000 and <=2000 #include [iostream.h]
1100 class MEMBER
more than 2000 {
2200 int Mno;float Fees;
Public Members PUBLIC:
*A function FEEDINFO() to allow user to void Register(){cin>>Mno>>Fees;}
enter values for Flight Number, void Display{cout<<Mno<<" :
Destination, Distance & call function "<<Fees<<endl;}
CALFUEL() to calculate the quantity of };
Fuel void main()
*A function SHOWINFO() to allow user to {
view the content of all the data members MEMBER M;
Answer:
S)

Register();
C

class FLIGHT M.Display();


T
G

{ int Fno; }
(P

char Destination[20];
ar

A)
m

float Distance, Fuel; #include <iostream.h>


Ku

void CALFUEL(); class MEMBER


er
nd

public: { int Mno;float Fees;


re

void FEEDINFO();
Vi

public:
void SHOWINFO(); void Register()
}; {
void FLIGHT::CALFUEL() cin>>Mno>>Fees;
{ if (Distance<1000) }
Fuel=500; void Display()
else {
if (Distance<2000) cout<<Mno<<":"<<Fees<<end
l;
Fuel=1100; }
else };
void main()
Fuel=2200; {
} MEMBER M;
void FLIGHT::FEEDINFO() M.Register();
{cout<<”Flight No :”;cin>>Fno; M.Display();
cout<<”Destination :”;gets(Destinatio }
n);
cout<<”Distance :”;cin>>Distance;
2.c) Define a class TEST in C++ with
CALFUEL();
following description:
}
4
void FLIGHT::SHOWINFO()
Private Members
{
• TestCode of type integer
cout<<”Flight No :”<<Fno<<endl;
• Description of type string
• NoCandidate of type integer
44 XII Computer
• CenterReqd (number of centers • A data member Destination of type
required) of type integer string
• A member function CALCNTR() to • A data member Distance of type float
calculate and return the number of • A data member Fuel of type float
centers as • A member function CALFUEL() to
(NoCandidates/100+1) calculate the value of Fuel as per the
Public Members following criteria
• A function SCHEDULE() to allow user to Distance
enter values for TestCode, Fuel
Description, NoCandidate & call function <=1000
CALCNTR() to calculate the number of 500
Centres more than 1000 and <=2000
• A function DISPTEST() to allow user to 1100
view the content of all the data members more than 2000
A) 2200
class TEST Public Members
{ " A function FEEDINFO() to allow user to
int TestCode; enter values for Flight Number,
char Description[20]; Destination, Distance & call function
int NoCandidate,CenterReqd; CALFUEL() to calculate the quantity of
void CALCNTR(); Fuel
public: " A function SHOWINFO() to allow user to
void SCHEDULE(); view the content of all the data members
void DISPTEST(); A)
}; class FLIGHT
void TEST::CALCNTR() {
{ int Fno;
S)
C

CenterReqd=NoCandidate/100 + 1; char Destination[20];


T
G

} float Distance, Fuel;


(P

void TEST::SCHEDULE() void CALFUEL();


ar
m

{ public:
Ku

cout<<"Test Code :";cin>>TestCode; void FEEDINFO();


er
nd

cout<<"Description :";gets(Description void SHOWINFO();


re

); };
Vi

cout<<"Number :";cin>>NoCandidate; void FLIGHT::CALFUEL()


CALCNTR(); {
} if (Distance<=1000)
{ Fuel=500;
cout<<"Test else
Code :"<<TestCode<<endl; if (Distance<=2000)
cout<<"Description :"<<Description<< Fuel=1100;
endl; else
cout<<"Number :"<<NoCandidate<<en Fuel=2200;
dl;; }
cout<<"Centres :"<<CenterReqd<<endl void FLIGHT::FEEDINFO()
;; {
} cout<<"Flight No :";cin>>Fno;
cout<<"Destination :";gets(Destinati
Sample Paper 2 for 2009-10 on);
cout<<"Distance :";cin>>Distance;
Batch: CALFUEL();
}
2.c) Define a class in C++ with following
void FLIGHT::SHOWINFO()
description:
{
4
cout<<"Flight No :"<<Fno<<endl;
Private Members
cout<<"Destination :"<<Destination
• A data member Flight number of type
<<endl;
integer

45 XII Computer
cout<<"Distance :"<<Distance<<end the outside world (outside their class). A
l;; Constructor is used to initialize the
cout<<"Fuel :"<<Fuel<<endl;; objects of the class being created
} (automatically called by the compiler).

Difference between a constructor and


an ordinary member function:

Constructor Member
Function
Name Name of the Class Any Valid
Identifier
Purpose Initialize the For any general
object when it is purpose
being created
Call Implicit Explicit
Return Should not keep Must be there at
type least void

Declaration and Definition:

A constructor is a member
function of a class with the same name as
that of its class name. A constructor is
defined like other member functions of a
class. It can be defined either inside the
5.CONSTRUCTORS & class definition or outside the class
S)
C

DESTRUCTORS definition.
T
G
(P
ar

MATERIAL
m

Eg: class X
Ku

Constructor: A member function with { int i;


er
nd

the same name as its class is called public:


re

int j,k;
Vi

Constructor and it is used to initialize the


objects of that class type with a legal X( ) //Constructor
initial value. {
i = j = k = 0;
If a class has a constructor, each }
object of that class will be initialized ------
before any use is made of the object. //Other members
------
Need for Constructors: A variable, an };
array or a structure in C++ can be
initialized at the time of their declaration. This simple constructor (X::X ( ) )
is as an inline member function.
Eg: int a=10; Constructors can be written as outline
int a[3]= {5,10,15}; functions also as it is shown below:
struct student
{ class X
int rno; {
float m1,m2,m3; int i ;
}; public:
student s1={1,55.0,90.5,80.0}; int j, k ;
X ( ); //Only
But this type of initialization does constructor declaration.
not work for a class because the class ------ //Other
members have their associated access members
specifiers. They might not be available to ------

46 XII Computer
}; having multiple constructors is called as
X :: X ( ) //Constructor constructor overloading.
defined outside
{ A constructor can also
i = j = k = 0; have default arguments. A constructor
} with default arguments is equivalent to a
default constructor.
Generally constructor will be
defined under public section, which can Eg: class Rectangle
be available to non members also. But it {
can also be defined under private or float l,b,a;
protected. A private or protected public:
constructor is not available to the non- Rectangle ( float len = 5.0, float bre =
member functions. Ie With a private or 5.0)
protected constructor, you cannot create //Constructor with Default arguments
an object of the same class in a non- {
member function. l = len;
b = bre;
There are three types of constructors }
-----
a) Non-parameterized or -----
Default Constructor };
b) Parameterized Constructor
c) Copy Constructors void main( )
{
a) Default constructor: Rectangle first(7.0,9.5);
Rectangle second;
S)
C

A constructor that accepts no //Takes default argument values.


T
G

parameter is called the default Equivalent to second(5.0,5.0)


(P

constructor. ----
ar
m

With a default constructor, objects are ----


Ku

created just the same way as variables of }


er
nd

other data types are created.


re

The default constructors are very


Vi

class X useful when you want to create objects


{ without having to type the initial objects
int i ; every time with pre specified initial
public: values or if you want to create array of
int j, k ; objects of your class type. You can’t
------ create an array of objects unless your
//Members Functions class has a default constructor (implicitly
------ or explicitly defined).
};
b) Parameterized Constructor:
Eg: X ob1;
Student s1; A constructor that take
arguments, is called as parameterized
If a class has no explicit constructor.
constructor defined, the compiler will The parameterized constructor allow us
supply a default constructor. This to initialize the various data elements of
implicitly declared default constructor is different objects with different values
an inline public members of its class. when they are created. This is achieved
Declaring a constructor with arguments by passing different values as arguments
hides the default constructor. to the constructor function when the
objects are created.
There can be a default
constructor as well as another Eg: class Rectangle
constructor with arguments for a class, { float l,b,a;

47 XII Computer
public:
Rectangle ( float len , float bre ) void test ( )
//Parameterized Constructor. {
{ l = len; Sample S1(2,5);
b = bre; //An object S1 created
} S1.print ( );
----- //Data values of S1 printed
----- Sample (4,9).print ( );
}; //Data values of a temporary
//sample instance printed
void main( ) }
{
Rectangle first(7.0,9.5); The primitive (fundamental)
---- types also have their own constructors.
---- When no values are provided, they use
} their default constructors but when you
provide initial values, the newly created
With a parameterized instance is initialized with the provided
constructor, the initial values must be value.
passed at the time of object created. This Eg: int a,b,c;
can be done in two manners: //Default constructor used
int i(3), j(4), k(5); //i,j,k
(i)By calling the constructor implicitly initialized
(implicit call)
Eg: Rectangle first(8.5,3.9); c) Copy Constructor:
(ii)By calling the construct or explicitly
(Explicit call) A copy constructor is a
S)
C

Eg: Rectangle first = Rectangle constructor of the form


T
G

(8.5,3.9); classname(classname &). The compiler


(P

will use the copy constructor whenever


ar
m

Temporary Instances: you initialize an instance using values of


Ku

another instance of same type.


er
nd

A temporary instance lives in the


re

memory as long it is being used or Eg:


Vi

referenced in an expression and after this


it dies. A temporary instance will not Sample S1; //Default constructor
have any name. The explicit call to a used
constructor also allows you to create a Sample S2=S1; //Copy constructor used.
temporary instance or temporary object. Also Sample S2(S1);
The temporary instances are deleted In the above code, for the second
when they are no longer referenced. statement, the compiler will copy the
instance S1 to S2 member by member. If
Eg: class Sample you have not defined a copy constructor,
{ the compiler automatically, creates it and
int i,j; it is public.
public: A copy constructor takes a
sample (int a, int b) reference to an object of the same class
{ an argument.
i=a;
j=b; Eg:
}
void print ( ) class Sample
{ {
cout<<i<<j<<”\n”; int i,j;
} public:
---- Sample (int a, int b)
---- //Constructor
}; {

48 XII Computer
i = a; runtime. The benefit of dynamic
j = b; initialization is that it provides the
} flexibility of assigning initial values at run
Sample (Sample &s) //Copy time.
Constructor
{ Initialization of Const & Reference
i=s.i; Members:
j=s.j; If your class contains a constant and a
cout<<”Copy constructor reference as member field, then you need
Working\n”; to specify that through Member-
} Initialization List.
A constructor can initialize the
void print( ) constituent data members of its class
{ through a mem-initialization list that
cout<<i<<”\t”<<j<<”\n”; appears in the function header of the
} constructor.
-----
----- Eg:
};
class Test
void main( ) {
{ int a ;
Sample S1(4,9); char b;
//S1 initialized first constructor used public:
Sample S2(S1); Test(int i,char j):a(i), b(j);//a(i)
//S1 copied to S2. Copy constructor initializes member a with
called. //value i, b(j)….b
S)
C

Sample S3=S1; with j.


T
G

//S1 coped to S3. Copy constructor called {


(P

//again. ….
ar
m

----- }
Ku

----- }
er
nd

} You can even have a combination of


re

mem-initialization list and initialization


Vi

Why the argument to a copy within constructor body.


constructor is passed by reference:
If we try to pass the argument by Eg:
value to a copy constructor (ie, for a class
X, if we use an X(X) constructor in place class Test
of X(X&), the compiler complaints out of {
memory. The reason is, when an ……
argument is passed by value, a copy of it public:
is constructed. To create a copy of the Test(int i, char j):a(i)
object, the copy constructor works. But {
the copy constructor is creating a copy of b=j;
the object for itself, thus it calls itself. }
Again the called copy constructor …..
requires another copy so again it is };
called. In fact it calls itself again until the
compiler runs out of memory. So, in the And if your class contains a const
copy constructor, the argument must be and /or a reference member, then these
passed by reference, so that to make a members must be initialized through
copy of the passed object, original object mem-initialization list as these cannot be
is directly available. initialized within constructor body.

Dynamic initialization of objects: The Eg:


dynamic initialization means that the
initial values may be provided during struct Sname

49 XII Computer
{ initialized before any use is made
char fname[25]; of the object.
char lname[25]; 3. Constructor functions obey the
} S1; usual access rules. Ie private and
protected constructors are
class Test available only for member and
{ friend functions, however, public
int a,b; constructors are available for all
const int max; //const the functions. Only the functions
member that have access to the
Sname &name; //reference constructor of a class, can create
member an object of the class.
public: 4. No return type (not even void)
Test ( ):max(300),name(S1) can be specified for a constructor.
{ 5. They cannot be inherited, though
a=0; a derived class can call the base
b=10; class constructor.
} 6. A constructor may not be static.
------ 7. Default constructors and copy
}; constructors are generated(by
the compiler) where needed.
Mem-initialization lists are especially Generated constructors are
used in the following four cases: public.
8. Like other c++ functions,
(i)initialization of const members. constructors can also have default
(ii)initialization of reference members. arguments.
(iii)Invoking base class constructor. 9. It is not possible to take the
S)
C

(iv)Initialization of member objects. address of a constructor.


T
G

10. An object of a class with a


(P

Constructor Overloading: constructor cannot be a


ar
m

member of a union.
Ku

The constructor of a class may also be 11. Member functions may be called
er
nd

overloaded so that even with different from within a constructor.


re

number and types of initial values, an 12. A constructor can be used


Vi

object may still be initialized. explicitly to create new objects of


its class type, using the syntax
Default Arguments Versus class-name (expression-list)
Overloading: Eg: Sample
obj1=Sample(13,22.42);
Using default arguments gives the
appearance of overloading, because the DESTRUCTORS
function may be called with an optional
number of arguments. Destructor:
Eg:
Prototype : float amount (float A destructor is used to destroy
principal, int time=2, float rate=0.08); the objects that have been created by a
Can be called as constructor. A destructor destroys the
Amount(2000.0,4,0.10); values of the object being destroyed.
Amount(3520.5,3); A destructor is also a member
Amount(5500.0); function whose name is the same as the
class name but is preceded by tilde(~). A
Special Chracteristics of Constructors: destructor takes no arguments, and no
return types can be specified for it (not
1. Constructor functions are even void). It is automatically called by
invoked automatically when the the compiler when an object is destroyed.
objects are created. A local object, local to a block, is
2. If a class has a constructor, each destroyed when the block gets over; a
object of that class will be global or static object is destroyed when

50 XII Computer
the program terminates. A destructor 4.No argument can be provided to a
cleans up the storage (memory area of destructor, neither does it return any
the object) that is no longer accessible. value.
5. They cannot be inherited.
Eg: 6. A destructor may not be static.
7. It is not possible to take the address of
class Sample a destructor.
{ int i,j; 8. Member functions may be called from
Public: within a destructor.
Sample(int a, int b) //Constructor 9. An object of a class with a destructor
{ cannot be a member of a union.
i=a; j=b;
}
~Sample()
{
cout<<”Destructor at work\n”;
}
------ CONSTRUCTORS AND DESTRUCTORS
------ (PROGRAMS)
};
void main( ) 1.Program to find area of a circle using
{ class, constructor functions and
Sample s1(3,4); destructor.
//Local object s1 constructed with #include<iostream.h>
values 3 #include<conio.h>
// & 4 using Sample ( ) class Circle
----- { float r,a; //r and a are private
S)
C

----/*Automatically s1 is destructed at the public:


T
G

end of the block using destructor Circle()


(P

~Sample( )*/ //Non parameterized or Default


ar
m

} Constructor
Ku

{ r=0.0;
er
nd

Need for Destructors: a=0.0;


re

}
Vi

During construction of any object Circle(float rad)


by the constructor, resources may be //Parameterized Constructor
allocated for use. (for example, a { r = rad;
constructor may7 have opened a file and a = 3.1415*r*r;
a memory area may be allotted to it). }
These allocated resources must be de Circle(Circle &obj) //Copy Constructor
allocated before the object is destroyed.A { r = obj.r;
destructor performs these types of tasks. a = obj.a;
}
Some Characteristics of Destructors: ~Circle()
{ cout<<"\nThe object is being
1. Destructor functions are invoked destroyed....";
automatically when the objects are }
destroyed. void take()
2. If a class has a destructor, each object {
of that class will be deinitialized before cout<<"Enter the value of Radius: ";
the object goes out of scope.(Local cin>>r;
objects at the end of the block defining }
them and global and static objects at the void calculate()
end of the program). {
3. Destructor functions also, obey the a = 3.1415*r*r;
usual access rules as other member }
functions do. void display()

51 XII Computer
{ cout<<"\nThe Radius of the Circle = void readProcess()
"<<r; { cout<<"\nEnter the 3 Subject marks
cout<<"\nThe Area of the Circle = of a
"<<a; student: ";
} cin>>m1>>m2>>m3;
}; total=m1+m2+m3;
void main() avg=total/3;
{ clrscr(); }
Circle c1; /*Default Constructor will be void display()
called implicitly. ie c1.r = 0.0 and c1.a = { cout<<"\nTotal Marks = "<<total;
0.0 */ cout<<"\nAverage Marks = "<<avg;
Circle c2(10.3); }
//Parameterized Constructor will be };
called //implicitly void main()
Circle c3(c2); {
//Copy Constructor will be called clrscr();
implicitly Student S1;
c1.take(); Student S2(50.5,90.0,75.5);
c1.calculate(); Student S3=S2;
c1.display(); S1.readProcess();
c2.display(); S1.display();
c3.display(); S2.readProcess();
getch(); S2.display();
} S3.display(); getch();
}
2. Program to process student data using
class concept, constructors and
S)
C

destructor.
T
G

#include<iostream.h> 2010 Delhi:


(P

#include<conio.h>
ar
m

class Student
Ku

{ float m1,m2,m3,total,avg; (b) Answer the questions (i) and (ii) after
er

going through the following class:


nd

public:
re

Student() 2
Vi

{ m1=0.0; class TEST


m2=0.0; {
m2=0.0; int Regno, Max, Min, Score;
total=0.0; public:
avg=0.0; TEST() //Function 1
} {
Student(float x,float y,float z) Regno= 101;
{ m1=x; Max=100;
m2=y; Min=40;
m3=z; Score=75;
total=m1+m2+m3; }
avg=total/3; TEST(int Pregno,int Pscore)
} //Function 2
Student(Student &Test) {
{ m1=Test.m1; Regno=Pregno;
m2=Test.m2; Max=100;
m3=Test.m3; Min=40;
total=Test.total; Score=Pscore;
avg=Test.avg; }
} ~TEST() //Function 3
~Student() {
{ cout<<"The Object is being cout<<“TEST Over”<<endl;
Destroyed...."; }
} void Display() //Function 4
{
52 XII Computer
cout<<Regno<<“:”<<Max<<“:”<<Min Polymorphism (OR) Constructor
<<endl; Overloading
cout<<“[Score]”<<Score<<endl; (OR) Function Overloading
} (ii) What is Module 3 referred as ? When
}; do you think, Module 3 will be
(i) As per Object Oriented Programming, invoked/called?
which. concept is illustrated by Function Ans.
1 and Function 2 together? Destructor. It is invoked as soon as the
Ans. scope of the object gets over.
Polymorphism (OR) Function
Overloading 2009 Delhi:
(OR) Constructor Overloading
(ii) What is Function 3 specifically
referred as ? When do you think, (c) Rewrite the following program after
Function 3 will be removing the syntactical errors (if any).
invoked/called? Underline each correction. 2
Ans.
Destructor, invoked or called when #include [iostream.h]
scope of an Object #include [stdio.h]
class Employee
{
2010 Outside Delhi: int EmpId=901;
char EName [20] ;
2. (b) Answer the questions (i) and (ii) public
after going through the following class: 2 Employee(){}
class Exam void Joining() {cin>>EmpId; gets
{ (EName);}
S)

int Rno,MaxMarks,MinMarks,Marks; void List () {cout<<EmpId<<” :


C
T

public: “<<EName<<endl;}
G
(P

Exam ( ) //Module 1 };
ar

{ void main ()
m
Ku

Rno=101; {
er

MaxMarks=l00; Employee E;
nd
re

MinMarks=40; Joining.E();
Vi

Marks=75; E.List()
} }
Exam (int Prno, int Pmarks) //Module
2
{ Ans
Rno=Prno; #include <iostream.h>
MaxMarks=l00; #include <stdio.h>
MinMarks=40; class Employee
Marks=Pmarks; { int EmpId;
} char EName[20];
~Exam () //Module 3 public :
{ Employee()
cout<<“Exam Over”<<endl; {
} EmpId=901;
void Show () //Module 4 }
{ void Joining( )
cout<<Rno<<“:”<<MaxMarks<<“:”<<MinMarks<< {
endl; cin>>EmpId;
cout<<“[Marks Got]”<<Marks<<endl; gets (EName);
} }
}; void List ( )
(i) As per Object Oriented Programming, {
which concept is illustrated byModule 1 cout<<EmpId<<”:
and Module 2 together? “<<EName<<endl;
Ans. }
53 XII Computer
}; Q.Disp();
void main () Play R=Q; //Copy constructor
{ ca11
Employee E; [same as P1ay R(Q);]
E.Joining (); R. Disp();
E.List (); }
}
(b) Answer the questions (i) and (ii) after
2.(a)What is copy constructor?Give ane going through the following class:
example in C++ to illustrate copy con- class WORK 2
structor. 2 {
Ans A copy constructor is an overloaded int WorkId;char WorkType ;
constructor function in which (an) public:
object(s) of the same class is/are passed -WORK ( ) //Function 1
as a reference parameter(s). It is used {
when an object’s data value is related to cout<<”Un-Allocated”<<endl ;
or is initialised using another }
object’s data value of the same class. In void status ( ) //Function 2
the example below the values of data {
members of object Q are dependent on cout<<WorkId<<”:
the values of data members of object P “<<WorkType<<endl ;
and Data members of object R dependent }
on Q. WORK ( ) //Function 3
//Example of Copy Constructor {
class Play WorkId = 10;
{ WorkType=’T’ ;
int Count, Number; }
S)
C

public: WORK(WORK &W) //Function 4


T
G

Play(); //constructor {
(P

Play(Play &);//copy constructor WorkId=W. WorkId+12;


ar
m

void Disp(); WorkType=W. WorkType+l


Ku

void Change(int,int); }
er
nd

}; };
re

Play::Play () //constructor (i) Which member function out of


Vi

{ Function 1, Function 2, Function 3 and


Count=0; Function 4 shown in the above definition
Number=0; of class WORK is called automatically,
} when the scope of an object gets over? Is
Play:: Play (Play &P) //copy constructor it known as Constructor OR Destructor
{ OR Overloaded Function OR Copy
Count=P.Count+l0; Constructor?
Number=P.Number+20; Ans Function 1
} Destructor.
void Play::Disp() (ii) WORK W; // Statement 1
{ WORK Y(W); // Statement 2
cout<<Count; Which member function out of Function
cout<<Number<<endl; 1, Function 2, Function 3 and Function 4
} shown in the above definition of class
void Play::Change(int C,int N) WORK will be called on execution of
{ statement written as statement 2 ? What
Count=C; is this function specifically known as
Number=N; out of Destructor or Copy Constructor or
} Default Constructor?
void main () Ans Function 4
{ Copy Constructor.
Play P; //Call for constructor
P.Disp (); P.Change(90,80) ; 2009 Outside Delhi:
Play Q(P); //Copy constructor call

54 XII Computer
(b) Answer the questions (i) and (ii) after class bazaar
going through the following class: { char Type[20] ;
2 char product [20];
class Job int qty ;
{ float price ;
int JobId; bazaar()
char JobType; //function 1
public: { strcpy (type , “Electronic”) ;
~Job ( ) //Function 1 strcpy (product , “calculator”);
{ qty=10;
cout<< “Resigned” <<end1; price=225;
} }
Job ( ) //Function 2 public :
{ void Disp() //function 2
JobId=10 ; { cout<< type <<”-”<<product<<”:”
JobType =‘T” ; <<qty<< “@” << price << endl ;
} }
void TellMe( )//Function 3 };
{ void main ()
cout<<JobId<< “: ” { Bazaar B ; //statement 1
<<JobType<<end1; B. disp() ; //statement 2
} }
Job (Job &J) //Function 4
{ (i)Will statement 1 initialize all the data
JobId=J.JobId+10; members for object B with the values
JobType=J.JobType+l; given in the function 1 ? (YES OR NO).
} Justify your answer suggesting the
S)
C

}; correction(s) to be made in the above


T
G

(i) Which member function out of code.


(P

Function 1, Function 2, Function 3 and


ar
m

Function 4 shown in the above definition Ans: No. The reason is the constructor
Ku

of class Job is called automatically, when should be defined under the public
er
nd

the scope of an object gets over? Is it visibility label.


re

known as Constructor OR Destructor OR (ii) What shall be the possible output


Vi

Overloaded Function OR Copy when the program gets executed ?


Constructor? (Assuming, if required _ the suggested
Ans Function 1. correction(s) are made in the program).
Destructor. Ans: Possible Output:
(ii) Job P ; //Line 1 Electronic–Calculator:10@225
Job Q(P) ; //Line 2
Which member function out of Function 2.c)Define a class Garments in c++ with
1, Function 2, Function 3 and Function 4 following descriptions
shown in the above definition of class Job 4
will be called on execution of statement private members :
written as Line 2 ? What is this function GCode of type string
specifically known as out of GType of type string
Destructor or Copy Constructor or Gsize of type intiger
Default Constructor? Gfabric of type istring
Ans Function 4. Gprice of type float
Copy Constructor. A function Assign() which calculate and
the value of GPrice as follows.
2008 DELHI: For the value of GFabric “COTTON” ,
GType GPrice(RS)
2.b) Answer the questions (i) and (ii) TROUSER 1300
after going through the following SHIRT 1100
program: 2 For GFabric other than “COTTON”, the
#include <iostream.h> above mentioned
#include<string.h> GPrice gets reduced by 10%

55 XII Computer
public members: Assign( );
A constructor to assign initial values of }
GCode,GType and GFabric with the a void display( )
word “NOT ALLOTED”and Gsize and { cout<<"\nThe Garment Code:
Gprice with 0. "<<GCode;
A function Input ()to the values of the cout<<"\nThe Garment Type:
data membersGCode, GType,Gsize and "<<GType;
GFabric and invoke the Assign() function. cout<<"\nThe Garment Size: "<<Gsize;
A function Display () which displays the cout<<"\nThe Garment Fabric:
content of all the data members for a "<<Gfabric;
garment. cout<<"\nThe Garment Price:
#include<iostream.h> "<<Gprice;
#include<string.h> }
#include<conio.h> };
#include<stdio.h> void main( )
class Garments { Garments G;
{ char GCode[21],GType[21]; G.Input( );
int Gsize; G.display( ); }
char Gfabric[21];
float Gprice; 2008 OUTSIDE DELHI:
void Assign( )
{ 2.b) Answer the questions (i) and (ii)
if(strcmp(strupr(Gfabric),"COTTON")==0 after going through the following
) program:
{ if(strcmp(strupr(GType),"TROUSER")= #include<iostream.h>
=0) #include<string.h>
Gprice=1300;
S)

class Retail
C

if(strcmp(strupr(GType),"SHIRT")==0) { char category[20];


T
G

Gprice=1100; char item[20];


(P

}
ar

int qty;
m

else float price;


Ku

{if(strcmp(strupr(GType),"TROUSER")= retail () //function 1


er
nd

=0) { strcpy (category, “cerial”);


re

Gprice=1300*0.90;
Vi

strcpy (Item, “Rice”);


if(strcmp(strupr(GType),"SHIRT")==0) qty =100 ;
Gprice=1100*0.90; price =25 ;
} }
} public;
public: void show() //function 2
Garments( ) { cout << category <<”-“<< Item << “
{ :”<<Qty<<“@”<< price<<endl;
strcpy(GCode,"NOT ALLOTED"); }
strcpy(GType,"NOT };
ALLOTED"); void main()
Gsize=0; { Retail R; //statement 1
strcpy(Gfabric,"NOT R. show (); //statement 2
ALLOTED"); }
Gprice=0; (i) will statement 1 initialize all the
} data members for objects R with the
void Input( ) given in the function 1 ? (YES OR NO).
{ cout<<"\nEnter the Grament Code: "; Justify your Answer suggesting the
gets(GCode); corrections(s) to be made in the above
cout<<"\nEnter the Garment Type: "; code.
gets(GType); Ans:No. The reason is the constructor
cout<<"\nEnter the Garment Size: "; should be defined under the public
cin>>Gsize; visibility label.
cout<<"\nEnter the Garment Fabric: "; (ii) What shall be the possible out put
gets(Gfabric); when the program gets executed ?
56 XII Computer
(Assuming, if required the suggested if(strcmp(strupr(Type),"SHIRT")==0
correction(s) are made in the program) )
Ans: Possible Output: price=1200*0.75;
cerial–Rice:100@25 }
}
2.c ) Define a class clothing in c++ with public:
the following descriptions : clothing( )
private members : { strcpy(Code,"NOT ALLOTED");
code of type string strcpy(Type,"NOT ALLOTED");
type of type string size=0;
size of type intiger strcpy(material,"NOT ALLOTED");
material of type string price=0;
price of type float }
A function calc_price( )which calculates void enter( )
and assigns the value of GPrice as { cout<<"\nEnter the Cloth Code: ";
follows ; gets(Code);
For the value of material as “COTTON” : cout<<"\nEnter the Cloth Type: ";
Type price (Rs) gets(Type);
TROUSER 1500. cout<<"\nEnter the Cloth Size: ";
SHIRT 1200. cin>>size;
for material other than “COTTON”, the cout<<"\nEnter the cloth material: ";
above mentioned GPprice price gets gets(material);
reduced by 25% calc_price( );
}
public members : void show( )
* A constructor to assign initial values of { cout<<"\nThe Cloth Code: "<<Code;
code ,type and material with the word cout<<"\nThe Cloth Type: "<<Type;
S)
C

“NOT ASSIGNED “and size and price with cout<<"\nThe Cloth Size: "<<size;
T
G

0. cout<<"\nThe Cloth Material: “


(P

* A function enter() to input the values of <<material;


ar
m

the data members code, type, size and cout<<"\nThe Cloth Price:
Ku

material and invoke the caclPrice () "<<price;


er
nd

function. }
re

* A function show which displays the };


Vi

content of all the data members for a void main( )


clothing. { clothing C;
#include<iostream.h> C.enter( );
#include<string.h> C.show( );
#include<conio.h> }
#include<stdio.h>
class clothing
{ char Code[21],Type[21]; 2007 DELHI:
int size;
char material[21]; 2.a) Differentiate between Constructor
float price; and Destructor function in context of
void calc_price( ) Classes and Objects Using C++?
{ 2
if(strcmp(strupr(material),"COTTON")== Ans:
0)
{ if(strcmp(strupr(Type),"TROUSER")=
=0) price=1500;
if(strcmp(strupr(Type),"SHIRT")==0)
price=1200;
}
else
{ if(strcmp(strupr(Type),"TROUSER")
==0)
price=1500*0.75;

57 XII Computer
Constructor: A constructor is used to Ans: They will be executed
intitialize the objects of that class type automatically.
with a legal initial value.If a class has a Member function 1 will be executed at
constructor, each object of that class will the time of creation of an object of
be initialized before any use is made of class Maths. Member function 2 will
the object. be executed at the time of
(A member function with the destruction of an object of class
same name as its class is called Maths.
Constructor and it is used to initialize the
objects of that class type with a legal 2.c)Define a class Tour in C++ with the
initial value. ) description given below
Destructor: A destructor is used to 4
destroy the objects that have been Private Members:
created by a constructor. A destructor TCode of type string
destroys the values of the object being
destroyed. Constructor Destructor
Purpose: Is used to Purpose: Is used to
intitialize the objects of destroy the objects that
that class type with a have been created by a
legal initial value constructor
2.b) Answer the question (i)and (ii)after Name: The name of the Name:The name of the
going through the following class: class class preceded by a ~.
Calling: It will be Calling: It will be called
2 called automatically at automatically at the
the time of creation of time of destruction of
class Maths the object. an object.
{ char Chapter[20] Ie Implicite calling Ie Implicite calling
int Marks; Return Type: No Return Type: No
return type not even return type not even
public:
S)

void void
C

Maths() //Member
T

No of Adults of type integer


G

Function 1
(P

{ No of Kids of type integer


ar

Kilometers of type integer


m

strcpy (Chapter, “Geometry”);


Ku

Marks=10; TotalFare of type float


er
nd

cout <<”Chapter Initialised “;


re

} Public Members:
Vi

-Maths() //Member • A constructor to assign initial


Functions 2 values as follows:
{ cout<<”Chapter Over”; TCode with the word “NULL”
} No of Adults as 0
}; No of Kids as 0
Kilometers as 0
(i)Name the specific features of class TotalFare as 0
shown by member Function 1 and • A function AssignFare() which
Member Function 2 in the above calculates and assigns the value of
example. the data member Totalfare as
Ans: Member function 1 is a (non- follows
parameterized or default) For each Adult
constructor (, which will be executed Fare (Rs) For Kilometers
automatically at the time of creation 500 >=1000
of an object of class Maths). 300 <1000 & >=500
Member function 2 is a destructor 200 <500
(,which will be executed For each Kid the above Fare will
automatically at the time of be 50% of the Fare mentioned in
destruction of an object of class the above table
Maths). For Example:
If Kilometers is 850, Noofadults
(ii)How would Member Function 1 and =2 and NoofKids =3 Then
Member Function 2 get executed ? TotalFare should be calculated as

58 XII Computer
Numof Adults *300+ NoofKids <<Kilometres;
*150 cout<<"\n\nThe Total Fare:
i.e., 2*300+ 3 *150 =1050 "<<TotalFare;
• A function EnterTour() to input }
the values of the data members };
TCode, NoofAdults, NoofKids and void main( )
Kilometers ; and invoke the { clrscr();
AssignFare() function. Tour T;
• A function ShowTour() which T.EnterTour( );
displays the content of all the T.ShowTour( );
data members for a Tour. getch();
}
Ans:
#include<conio.h> 2007 OUTSIDE DELHI:
#include<stdio.h>
#include<string.h> 2.b) Answer the questions (i) and (ii)
#include<iostream.h> after going through the following class :
class Tour 2
{ char TCode[21]; class Science
int NoofAdults,NoofKids,Kilometres; { char Topic[20] ;
float TotalFare; int Weightage ;
public: public :
Tour( ) Science ()
{ strcpy(TCode,"NULL"); //Function 1
NoofAdults=NoofKids=Kilometres=Total { strcpy (Topic, “Optics”) ;
Fare=0; Weightage =30
}
S)

cout<<”Topic Activated”;
C

void AssignFare( ) }
T
G

{ if(Kilometres>=1000) ~Science()
(P

TotalFare=NoofAdults*500+NoofKids*2
ar

//Function 2
m

50; { cout<<”Topic
Ku

else if(Kilometres>=500) Deactivated”; }


er
nd

TotalFare=NoofAdults*300+NoofKids*1 };
re

50;
Vi

else (i)Name the specific features of class


TotalFare=NoofAdults*200+NoofKids*1 shown by Function 1 and Function 2 in
00; the above example.
} Ans: Member function 1 is a (non-
void EnterTour( ) parameterized or default)
{ cout<<"\nEnter the Tour Code: "; constructor
gets(TCode); (, which will be executed
cout<<"\nEnter the Number of Adults: automatically at the time of creation
"; of an object of class Science).
cin>>NoofAdults; Member function 2 is a destructor
cout<<"\nEnter the Number of Kids: "; (,which will be executed
cin>>NoofKids; automatically at the time of
cout<<"\nEnter the Number of destruction of an object of class
Kilometres: "; Science).
cin>>Kilometres; (ii)How would Function 1 and Function 2
AssignFare( ); get executed ?
} Ans: They will be executed automatically.
void ShowTour( ) Member function 1 will be executed at
{ cout<<"\nThe Tour Code: "<<TCode; the time of creation of an object of class
cout<<"\nThe Number of Adults:” Science. Member function 2 will be
<<NoofAdults; executed at the time of destruction of an
cout<<"\nThe Number of Kids: object of class Science.
"<<NoofKids;
cout<<"\nThe Number of Kilometres: “

59 XII Computer
2.c) Define a class Travel in C++ with the Travel( )
description given below : { strcpy(T_Code,"NULL");
4 No_of_Adults=No_of_Children=Distance
=
Private Members: TotalFare=0;
T_Code of type string }
No_ of_ Adults of type integer void AssignFare( )
No _of _Children of type integer {
Distance of type integer if(Distance>=1000)
TotalFare of type float TotalFare=No_of_Adults*500+No_of_Children*
250;
Public Members: else if(Distance>=500)
TotalFare=No_of_Adults*300+No_of_Children*
• A constructor to assign initial 150;
values as follows: else
TCode with the word “NULL” TotalFare=No_of_Adults*200+No_of_Children*
No _of_ Adults as 0 100;
No_ of_Children as 0 }
Distance as 0 void EnterTravel( )
TotalFare as 0 { cout<<"\nEnter the Travel Code: ";
• A function AssignFare() which gets(T_Code);
calculates and assigns the value of cout<<"\nEnter the Number of
the data member Totalfare as Adults: ";
follows cin>>No_of_Adults;
For each Adult cout<<"\nEnter the Number of
Children: ";
Fare (Rs) For Kilometers cin>>No_of_Children;
cout<<"\nEnter the Distance in
S)

500 >=1000
C

Kilometres: ";
300 <1000 & >=500
T

cin>>Distance;
G

200 <500
(P

AssignFare( );
ar

For each Child the above Fare will be }


m
Ku

50% of the Fare mentioned in the above void ShowTravel( )


er

table { cout<<"\nThe Travel Code: “ <<T_Code;


nd

For Example:
re

cout<<"\nThe Number of Adults: “


Vi

If Distance is 750, No_of_adults =3 and <<No_of_Adults;


No_of_Children =2 cout<<"\nThe Number of Children:
Then TotalFare should be calculated as “<<No_of_Children;
Num_of _Adults *300+ No_of_Children cout<<"\nThe Distance in Kilometres:
*150 "<<Distance;
i.e., 3*300+ 2 *150 =1200 cout<<"\n\nThe Total Fare: "<<TotalFare;
• A function EnterTour() to input }
the values of the data members };
T_Code, No_of_Adults, void main( )
No_of_Children and Distance ; and {
invoke the AssignFare() function. clrscr();
• A function ShowTravel() which Travel T;
displays the content of all the T.EnterTravel( );
data members for a Travel. T.ShowTravel( );
getch();
#include<conio.h> }
#include<stdio.h>
#include<string.h> 2006 DELHI:
#include<iostream.h>
class Travel 2.b) Answer the following questions (i)
{ char T_Code[21]; and (ii) after going through the following
int class. 2
No_of_Adults,No_of_Children,Distance; class Interview
float TotalFare; { int Month;
public: public:
60 XII Computer
interview(int y) {Month=y;} { Year=y;
//constructor 1 }
interview(Interview&t); Exam(Exam &t);
//constructor 2 //Constructor 2
}; };
(i) create an object, such that it invokes (i) Create an object, such that it
Constructor 1. invokes Constructor 1
Ans: Interview A(10); //invoking Ans: Exam E((2008);
constructor 1 by passing a number. (ii) Write complete definition for
(ii) write complete definition for constructor 2.
Constructer 2. Ans: Exam(Exam &t)
Ans: Interview(Interview &t) //Copy Constructor.
//This is a copy constructor. { Year=t.Year;
{ Month=t.Month; }
}
2005 DELHI:
2006 OUTSIDE DELHI: 2.b) Answer the following questions (i)
and (ii) after going through the following
1.f) What is a default constructor? How class.
does it differ from destructor?
2 class Test
a) Default constructor: A constructor { char Paper[20];
that accepts no parameter is called the int Marks
default constructor. public:
With a default constructor, objects are Test() //Function 1
S)

created just the same way as variables of


C

other data types are created. { strcpy(Paper,”Computer”)


T
G

class X ;
(P
ar

{ int i ; Marks=0;
m

public:
Ku

}
int j, k ;
er
nd

------ //Members //Function 2


re
Vi

Functions Test(char P[])


------ { strcpy(Paper,P);
}; Marks=0;
Eg: X ob1; }
Student s1;
If a class has no explicit constructor //Function 3
defined, the compiler will supply a Test(int M)
default constructor. This implicitly { strcpy(Paper,”Computer”)
declared default constructor is an inline ;
public members of its class. Declaring a Marks=M;
constructor with arguments hides the }
default constructor. Test(char P[],int M)
There can be a default //Function 4
constructor as well as another { strcpy(Paper,P);
constructor with arguments for a class, Marks=M;
having multiple constructors is called as }
constructor overloading. };
(i)Which feature Object Oriented
2.b) Answer the following questions (i) programming is demonstrated using
and (ii) after going through the following Function 1, Function 2, Function 3 and
class. 2 Function 4 in the above class text?
class Exam Ans: Function overloading (here it is
{ int Year; constructor overloading).
public:
Exam(int y) //Constructor 1
61 XII Computer
(ii)Write statements in C++ that would Number_of_travellers=5;
execute Function 2 and Function 4 of Number_of_buses=1;
class Text. }
Ans: (let char name[20]; void NewPlan( )
int X=60; { cout<<"\nEnter the Plan Code: ";
strcpy(name,”COMPUTERSCIENCE” cin>>PlanCode;
); cout<<"\nEnter the Place to Travel: ";
are declared in the program) gets(Place);
(i) Test A(name); cout<<"\nEnter the Number of
//Will execute Funciton 2 Travellers: ";
(ii) Test B(name,X); cin>>Number_of_travellers;
//Will execute Function 4 if(Number_of_travellers>=40)
Number_of_buses=3;
2.c) Define a class Travelplan in C++ with else if(Number_of_travellers>=20)
the following descriptions: Number_of_buses=2;
Private Members: else
Plancode of type long Number_of_buses=1;
Place of type character }
array(string) void ShowPlan( )
Number_of_travellers of type { cout<<"\nThe Plan Code:
integer "<<PlanCode;
Number_of_buses of type cout<<"\nThe Place of Travel:
integer "<<Place;
Public Members: cout<<"\nNumber of Travellers: “
*A constructer to assign initial values of <<Number_of_travellers;
PlanCode as 1001, Place as cout<<"\nNumber of Buses: “
“agra”,Number_of_travellers as <<Number_of_buses;
S)
C

5,Number_of_buses as 1 }
T
G

* A function NewPlan() which allows };


(P

user to enter PlanCode, Place and void main( )


ar
m

Number_of travelers. Also, assign the { clrscr( );


Ku

value of Number_of_buses as per the TravelPlan T;


er
nd

following conditions: T.NewPlan( );


re

Number_of_travellers T.ShowPlan( );
Vi

Number_of_buses 1 getch();
less than 20 }
1
Equal to or more than 20 and less than 40
2
2005 OUTSIDE DELHI:
Equal to 40 or more than 40
1.a) Differentiate between a default
3
constructer and copy constructer, giving
* A function ShowPlan() to display the3
suitable examples of each.
content of all the data members on the
Ans: A default constructor also called as
screen.
non-parameterized constructor will take
Ans:
no argument and initialize the object with
#include<iostream.h>
the predefined values in that constructor,
#include<conio.h>
Where as a copy constructor will
#include<stdio.h>
take an already created object of that
#include<string.h>
class and stores that object values into
class TravelPlan
the newly created object of that class. A
{ long PlanCode;
copy constructor takes a reference to an
char Place[21];
object of the same class as an argument.
int
Number_of_travellers,Number_of_buses;
2.b) Answer the following questions
public:
(i)and (ii) after going through the
TravelPlan( )
following class.
{ PlanCode=1001;
class Exam
strcpy(Place,"Agra");
{ int Marks;
62 XII Computer
char Subject[20]; value of Number_of_buses as per the
public: following conditions:
Exam() //Function 1 Number_of_travellers
{ strcpy(Subject,”Computer Number_of_buses 1
”); less than 20
Marks=0; 1
} Equal to or more than 20 and less than 40
Exam(char S[]) //Function 2 2
Equal to 40 or more than 40
{ strcpy(Subject,S);
3
Marks=0; }
* A function ShowTravel() to display the
Exam(int M) //Function
content of all the data members on the
3
screen.
{ strcpy(Subject,”Computer”
Ans:
);
#include<iostream.h>
Marks=M;
#include<conio.h>
}
#include<stdio.h>
Exam(char S[],int M)
#include<string.h>
//Function4
class Travel
{ Strcpy(Subject,P);
{ long TravelCode;
Marks=M;
char Place[21];
}
int No_of_travellers,No_of_buses;
};
public:
(i)Write statements in C++ that would
Travel( )
execute Function 3 and Function 4 of
{ TravelCode=201;
class Exam.
strcpy(Place,"Nainital");
(let char name[20];
No_of_travellers=5;
int X=60;
S)

No_of_buses=1;
C

strcpy(name,”COMPUTERSCIENCE”);
}
T
G

are declared in the program)


(P

void NewTravel( )
(i) Exam A(X);
ar

{ cout<<"\nEnter the Travel Code: ";


m

//Will execute Funciton 3


Ku

cin>>TravelCode;
(ii) Exam B(name,X);
er

cout<<"\nEnter the Place to Travel: ";


nd

//Will execute Function 4


gets(Place);
re

(ii)Which feature Object Oriented


Vi

cout<<"\nEnter the Number of


Programming is demonstrated using
Travellers: ";
Function 1, Function 2, Function 3 and
cin>>No_of_travellers;
Function 4 in the above class text?
if(No_of_travellers>=40)
Ans: Function overloading (here it is
No_of_buses=3;
constructor overloading).
else if(No_of_travellers>=20)
No_of_buses=2;
2.c) Define a class Travel in C++ with the
else
following descriptions:
No_of_buses=1;
Private Members:
}
Travelcode of type long
void ShowTravel( )
Place of type character
{ cout<<"\nThe Plan Code:
array(string)
"<<TravelCode;
Number_of_travellers of type integer
cout<<"\nThe Place of Travel:
Number_of_buses of type integer
"<<Place;
Public Members:
cout<<"\nNumber of Travellers: “
* A constructer to assign initial values of
<<No_of_travellers;
TravelCode as 201,
cout<<"\nNumber of Buses: “
Place as “Nainital”,
<<No_of_buses;
Number_of_travellers as 10,
}
Number_of_buses as 1
};
* A function NewTravel() which allows
void main( )
user to enter TravelCode, Place and
{ clrscr( );
Number_of travelers. Also, assign the
Travel T;
T.NewTravel( );
63 XII Computer
T.ShowTravel( ); *Newplay() function to values for
getch(); Playcode and Playtitle.
} *Moreinfor() to assign the values of
assign the values of Duration and
2004 DELHI: Noofscenes with the of corresponding
values passed as parameters to this
2.a)Given the following C++ code, answer function.
the questions (i)and(ii) *Shoplay() function to display all the
class TestMeOut dataq members on the screen.
{ public: Ans: #include<iostream.h>
~TestMeOut( ) //Function 1 #include<conio.h>
{ #include<string.h>
cout<<”Leaving the examination #include<stdio.h>
hall”<<endl; class Play
} { int Playcode;
TestMeOut( ) //Function 2 char Playtitle[25];
{ float Duration;
cout<<”Appearing for int Noofscenes;
examination”<<endl; public:
} Play( )
void MyWork( ) { Duration=45;
{ Noofscenes=5;
cout<<”Attempting Questions”<<endl; }
} void Newplay( )
}; { cout<<"\nEnter the Play Code:
(i) In Object Oriented ";
cin>>Playcode;
S)

programming, what is
C

Function 1 referred as and cout<<"\nEnter the Play Title:


T
G

when does it get ";


(P

gets(Playtitle);
ar

invoked/called?
m

Ans: Function 1 is called as }


Ku

Destructor, It will automatically void Moreinfor(float D,int N)


er
nd

executed at the time of destruction of { Duration = D;


re

Noofscenes = N;
Vi

the object of class TestMeOut.


(ii) In Object Oriented }
Programming, what is void Showplay( )
Function 2 referred as and { cout<<"\nThe Play Code : “
when does it get <<Playcode;
invoked/called? cout<<"\nThe Play Title : “
Ans: Function 2 is called as <<Playtitle;
constructor (Non-parameterized or cout<<"\nThe Duration :”
default constructor) , it will <<Duration;
automatically executed at the time of cout<<"\nThe No of
creation of the object of class Scenes:"<<Noofscenes;
TestMeOut. }
};
void main( )
2003 DELHI: { clrscr( );
Play P;
2.b) Define a class Play in C++ with the P.Newplay( );
following specifications: float Dur;
Private members of class Play int NS;
*Play code integer cout<<"\nEnter the Duration
*Playtime 25 character and
*Duration float Number of Scenes: ";
*Noofscenes integer cin>>Dur>>NS;
Public member function of class Play P.Moreinfor(Dur,NS);
*A constructer function to initialize P.Showplay( );
Duration as 45 and Noofscenes as
64 XII Computer
getch( ); };
} void main( )
{
2002 DELHI: Sample s1(3,4); //Local object s1
constructed with values 3
2.c) Write the output of the following // and 4 using Sample ( )
program.4 -----
------
Ans: #include<iostream.h> ----//Automatically s1 is destructed at
class Counter the end of the block
{ private: //using destructor ~Sample( )
unsigned int count; }
public:
Counter() Here in the above example the destructor
{ count=0; ~Sample( ) will be automatically
} executed at the time of destruction of an
void inc_Count() object, and which is used to de-allocate
{ count++; the memory, before doing it whatever
} written in the destructor will be
int get_Count() executed.
{ return count; Ie in the above example whenever an
} object of the class is being destroyed,
}; “Destructor at work” will be displayed.
void main()
{ Counter C1,C2; 1998 DELHI:
cout<<"\nC1="<<C1.get_Coun
S)

t(); 2.a) What is a copy constructor? What do


C

cout<<"\nC2="<<C2.get_Coun you understand by constructer


T
G

t(); overloading?
(P
ar

C1.inc_Count(); Ans: copy constructor is a constructor of


m

C2.inc_Count(); the form classname(classname &). The


Ku

C2.inc_Count(); compiler will use the copy constructor


er
nd

cout<<"\nC1="<<C1.get_Coun whenever you initialize an instance using


re

t();
Vi

values of another instance of same type.


cout<<"\nC2="<<C2.get_Coun Eg: Sample S1;
t(); //Default constructor used
} Sample S2 = S1;
//Copy constructor used. Also
2000 DELHI: //Sample S2(S1);
In the above code, for the second
2.a) Why is destructor function required statement, the compiler will copy the
in classes? Illustrate with the function instance S1 to S2 member by member. If
with an example. you have not defined a copy constructor,
Ans: A destructor is a function which de- the compiler automatically, creates it and
allocates/frees the memory which was it is public.
reserved by the constructor. A copy constructor takes a reference to
Eg: an object of the same class an argument.
class Sample
{ Constructor Overloading:
Int i,j;
Public: With same constructor name,
Sample(int a, int b) having several definitions that are
//Constructor differentiable by the number or types of
{ i=a; j=b; } their arguments(ie Parameterized, non-
~Sample() parameterized and copy constructors) is
{ cout<<”Destructor at known as an overloaded constructor and
work\n”; } this process is known as constructor
------ overloading.
65 XII Computer
Constructor overloading
implements polymorphism. Model Paper 1 for 2008-09
An Example using Constructor
Batch:
Overloading:
2.c)Answer the questions (i) and (ii) after
1.Program to find area of a circle using
going through the following class:
class, constructor functions and
2
destructor.
class Seminar
#include<iostream.h>
{
#include<conio.h>
int Time;
class Circle
public:
{ float r,a; //r and a are private
Seminar() //Function 1
public:
{
Circle() //Non parameterized or
Time=30;cout<<”Seminar starts
Default Constructor
now”<<end1;
{ r=0.0; a=0.0; }
}
Circle(float rad) //Parameterized
void Lecture() //Function 2
Constructor
{
{ r = rad;
cout<<”Lectures in the seminar
a = 3.1415*r*r;
on”<<end1;
}
}
Circle(Circle &obj) //Copy
Seminar(int Duration) //Function 3
Constructor
{
{ r = obj.r;
Time=Duration;cout<<”Seminar starts
a = obj.a;
now”<<end1;
}
}
~Circle()
S)

~Seminar() //Function 4
C

{ cout<<"\nThe object is being


T

{
G

destroyed...."; }
(P

cout<<”Vote of thanks”<<end1;
void take()
ar

}
m

{ cout<<"Enter the value of Radius: ";


Ku

};
cin>>r;
er

i)In Object Oriented Programming, what


nd

}
is Function 4 referred as and when does
re

void calculate()
Vi

it get invoked/called?
{ a = 3.1415*r*r; }
Answer:
void display()
{ cout<<"\nThe Radius of the Circle = Destructor, it is invoked
"<<r; as soon as the scope of the
cout<<"\nThe Area of the Circle = object gets over.
"<<a; ii)In Object Oriented Programming,
} which concept is illustrated by Function 1
}; and Function 3 together? Write an
void main() example illustrating the calls for these
{ clrscr(); functions.
Circle c1; /*Default Constructor will be Answer:
called implicitely.ie c1.r = 0.0 and c1.a = Constructor Overloading
0.0 */ (Polymorphism)
Circle c2(10.3); //Parameterized Seminar S1,S2(90);
//Constructor will be called mplicitely
Circle c3(c2);
//Copy Constructor will be called Model Paper 2 for 2008-09
implicitely
c1.take(); Batch:
c1.calculate();
c1.display(); 2.c)Answer the questions (i) and (ii) after
c2.display(); going through the following program: 2
c3.display(); class Match
getch();} {
int Time;
66 XII Computer
public: cout<<"Seminar starts
Match() //Function 1 now"<<end1;
{ }
Time=0; void Lecture() //Function 2
cout<<”Match commences”<<end1;
{
}
cout<<"Lectures in the seminar
void Details() //Function 2
on"<<end1;
{
}
cout<<”Inter Section Basketball
Match”<<end1; Seminar(int Duration)
} //Function 3
Match(int Duration) {
//Function 3 Time=Duration;
{ cout<<"Seminar starts
Time=Duration; now"<<end1;
cout<<”Another Match begins }
now”<<end1; ~Seminar( )//Function 4
} {
Match(Match &M) //Function 4 cout<<"Vote of
{
thanks"<<end1;
Time=M.Duration;
cout<<”Like Previous Match }
”<<end1; };
} i) In Object Oriented Programming,
}; what is Function 4 referred as and
i)Which category of constructor - when does it get
Function 4 belongs to and what is the invoked/called?
S)
C

purpose of using it? A) Destructor, it is invoked as soon as


T
G

Answer: the scope of the object gets over. 2


(P

Copy Constructor, it is ii) In Object Oriented Programming,


ar
m

invoked when an object is which concept is illustrated by


Ku

created and initialised


er

Function 1 and
nd

with values of an already Function 3 together? Write an


re

existing object.
Vi

example illustrating the calls for these


functions.
ii)Write statements that would call the
A) Constructor Overloading (or
member Functions 1 and 3
Answer: Function Overloading or
Match M1; //for Polymorphism)
Function 1 Seminar S1; //Function 1
Match M2(90); //for Seminar S2(90); //Function 3
Function 3
Sample Paper 2 for 2009-10
Sample Paper 1 for 2009-10 Batch:
Batch:
2.b) Answer the questions (i) and (ii)
2. b) Answer the questions (i) and (ii) after going through the following
after going through the following program: 2
class: 2 class Match
class Seminar {
{ int Time;
int Time; public:
public: Match() //Function 1
Seminar() //Function 1 {
{ Time=0;
Time=30;
67 XII Computer
cout<<"Match void Assign();
commences"<<end1; void Show();
} };
void Details() //Function 2 class Director
{
{
int DID; //Director ID
cout<<"Inter Section
char Dname[20];
Basketball protected:
Match"<<end1; char Profile[30];
} public:
Match(int Duration) Director();
//Function 3 void Input();
{ void output();
Time=Duration; };
cout<<"Another Match begins class Company:private Chairperson, public
Director
now"<<end1;
{
} int CID; //Company ID
Match(Match &M) //Function char City[20], Country[20];
4 public:
{ Company();
Time=M.Duration; void Enter();
cout<<"Like Previous Match void Display();
"<<end1; };
}
}; (i) Which type of inheritance out of the
i) Which category of constructor - following is specifically is illustrated in
S)

the above C++ code?


C

Function 4 belongs to and what is the


T

(a) Single Level Inheritance


G

purpose
(P

(b) Multi Level Inheritance


of using it?
ar

(c) Multiple Inheritance


m

A) Copy constructor, It will help to


Ku

Ans.
copy the data from one object to
er

(c) Multiple Inheritance


nd

another
re
Vi

ii) Write statements that would call (ii) Write the names of data members,
the member Functions 1 and 3 which are accessible by objects of class
A) Match M; //Function 1 type Company.
Match N(10); //Function 3 Ans
None

(iii) Write the names of all member


6. INHERITANCE functions, which are accessible by objects
of class type Company.
2010 Delhi: Ans. Enter(), Display(), Input(), output()
(iv) Write the names of all members,
which are accessible from member
2.(d) Answer the questions (i) to (iv)
functions of class Director.
based on the following:
Ans. Input(), output(), Profile, Dname,
4
DID
class Chairperson
{
2010 Outside Delhi:
long CID; //Chairperson Identification
Number
2.(d) Answer the questions (i) to (iv)
char CName[20];
based on the following:
protected:
4
char Description [40];
class Director
void Allocate();
{
public:
long DID; //Director Identification
Chairperson();
Number
68 XII Computer
char Name[20]; 2009 Delhi:
protected:
char Description[40]; 2.(d) Answer the questions (i) to (iv)
void Allocate () ; based on the following:
public: 4
Director() ; class FaceToFace
void Assign () ; {
void Show () ; char CenterCode [10] ;
}; public:
class Ractory:public Director void Input ( ) ;
{ void Output ( ) ;
int FID; //Factory ID };
char Address[20]; class Online
protected: {
int NOE; //No. of Employees char website [50] ;
public: public:
Factory(); void SiteIn ( ) ;
void Input (); void SiteOut ( ) ;
void Output (); };
}; class Training: public FaceToFace, private
class ShowRoom:private Factory Online
{ {
int SID; //Showroom ID long Tcode ;
char City[20]; float charge;
public: int period;
ShowRoom(); public:
void Enter (); void Register ( ) ;
S)
C

void Display (); void Show ( ) ;


T
G

}; };
(P

(i) Which type of Inheritance is shown in


ar
m

(i) Which type of inheritance out of the the above example?


Ku

following is illustrated in the above C++ Ans


er
nd

code? Multiple Inheritance


re

(a) Single Level Inheritance


Vi

(b) Multi Level Inheritance ii) Write names of all the member
(c) Multiple Inheritance functions accessible from Show( )
Ans. function of class Training.
(b) Multilevel Inheritance Ans
Register( )
(ii) Write the names of data members, Siteln( ). SiteOut( ).
which are accessible by objects of class Input( ), Output( )
type ShowRoom.
Ans. iii) Wr i t e name of all the members
None accessible through an object of class
Training.
(iii) Write the names of all member Ans
functions which are accessible by objects Register( ), Show( ),
of class type ShowRoom. Input( ), Output( )
Ans. iv) Is the function Output( ) accessible
Enter(), Display() inside the function SiteOut( )? Justify
your answer.
(iv) Write the names of all members, Ans
which are accessible from member No, function Output( ) is not accessible
functions of class Factory. inside the function SiteOut( ), because
Ans. FID, Address, NOE, Description, Output( ) is a member of class
Input(), Output(), Assign(), Show(), FaceToFace and SiteOut( ) is a member of
Allocate() class Online. and the classes FaceToFace
and Online are two independent
69 XII Computer
classes. InRegular( ) is a member of class Regular
and InDistance( ) is a member of class
2009 Outside Delhi: Distance, and the classes Regular and
Distance are two independent classes.

2(d) Answer the questions (i) to


(iv)based on the following:
2008 DELHI:
4
class Regular 2.d) Answer the questions (i) to(iv)
{ based on the following code :
char SchoolCode[10];
public: class Dolls
void InRegular( ); { char Dcode[5];
void OutRegular( ); protected:
}; float Price;
class Distance void CalcPrice(float);
{ public:
char StudyCentreCode [5] ; Dolls();
public: void DInput();
void InDistance( ); void DShow();
void OutDistance( ); };
}; class SoftDolls:public Dolls
class Course: public Regular, private { char SDName[20];
Distance float Weight;
{ public:
char Code [ 5] ; SoftDolls();
float Fees; void SDInput();
S)

int Duration; void DShow();


C
T

public: };
G
(P

void InCourse( ); class ElectronicDolls:public


ar

void OutCourse( ); Dolls


m
Ku

}; { char EDName[20];
er

char BatteryType[10];
nd
re

(i) Which type of Inheritance is shown in int Batteries;


Vi

the above example? public:


Ans Multiple Inheritance ElecronicDolls();
void EDInput();
(ii) Write names of all the member void EDShow();
functions accessible from OutCourse };
function of class Course.
Ans (i)Which type of Inheritance is shown in
InCourse( ), InDistance( ), the above example?
OutDistance( ), Ans: Hierarchical Inheritance.
InRegular( ), OutRegular( ) Since the sub classes are derived from a
single base class(Dolls).
(iii) Write name of all the .:members (ii)How many bytes will be required by
accessible througb an object of class an object of the class ElectronicDolls ?
Course. Ans: 41 Bytes
Ans (Explonation: The memory will be
InCourse( ), OutCourse( ), InRegular( ), reserved as follows:
OutRegular( ) char Dcode[5]; //5 Bytes
float Price; //4 Bytes
(iv) Is the function InRegular( ) char EDName[20]; //20 Bytes
accessible inside the function InDistance( char BatteryType[10]; //10 Bytes
)? Justify int Batteries; //2 Bytes
your answer. Total = 41 Bytes )
Ans iii)Write name of all data members
No, function InRegular( ) is not accessible accessible from member function of the
inside the function InDistance( ), because class SoftDolls.
70 XII Computer
Ans: Dolls::Price, float Weight; // 4 Bytes
SoftDolls:: SDName, Total = 33 Bytes)
SoftDolls::Weight (iii)Write name of all data members
accessible from member function of the
(iv)Write name of member functions class SoftToys.
accessible an object of the class Ans: Toys::Price,
ElectronicDolls? SoftToys::STName,
Ans: ElectronicDolls::EDInput( ), SoftToys::Weight
ElectronicDolls::EDShow( ), (iv)Write name of member functions
Dolls::DInput( ), accessible an object of the class
Dolls::DShow( ) ElectronicToys ?
Ans: ElectronicToys::ETEntry( ),
Electronic Toys::ETDisplay( ),
2008 OUTSIDE DELHI: Toys::TEntry( ),
Toys::TDisplay( )
2.d) Answer the questions (i) to(iv)
based on the following code : 2007 DELHI:
class Toys
{ char Tcode[5]; 2.d) Answer the questions (i) to(iv)
protected: based on the following code:4
float Price; class Trainer
void Assign(float); { char
public: TNo[5],Tname[20],specialization[10];
Toys(); int Days;
void Tentry(); protected :
void Tdisplay(); float Remuneratoin;
S)

}; void AssignRem(float);
C

class SoftToys:public Toys public:


T
G

{ char STName[20]; Trainer();


(P
ar

float Weight; void TEntry();


m

public: void TDisplay();


Ku

SoftToys(); };
er
nd

void STentry(); class Learner


re
Vi

void STDisplay(); {
}; char Regno[10],LName[20],Program[10];
class ElectronicToys:public protected:
Toys int Attendance,grade;
{ char ETName[20]; public:
int No_of_Batteries; Learner();
public: void LEntry();
ElecronicToys(); void LDisplay();
void ETEntry(); };
void ETDisplay(); class Institute:public Learner,public
}; Trainer
{ char ICode[10],IName[20];
(i)Which type of Inheritance is shown in public:
the above example? Institute();
Ans: Hierarchical Inheritance. void IEntry();
Since the sub classes are derived from a void IDisplay();
single base class(Dolls). };
(ii)How many bytes will be required by
an object of the class SoftToys ? (i)Which type of inheritance is depicted
Ans: 33 Bytes by above example ?
(Explonation: The memory will be Ans: Multiple Inheritance.
reserved as follows: Since here the class Institute is deriving
char Tcode[5]; //5 Bytes from the classes Learner and Trainer.
float Price; //4 Bytes
char STName[20]; //20 Bytes
71 XII Computer
(ii)Identify the member function(s) that int Workload;
cannot be called directly from the objects protected :
of class Institute from the following float Salary;
TEntry() void AssignSal(float);
LDisplay() public:
IEntry() Teacher();
Ans: All the above 3 member functions void TEntry();
can be called directly from the objects of void TDisplay();
class Institute. };
(iii)Write name of all member(s) class Student
accessible from member functions of { char
class institute. Admno[10],SName[20],Stream
Ans: Data Members – [10];
Trainer::Remuneration, protected:
Learner::Attendan int Attendance,Totmarks;
ce, public:
Learner::Grade, Student();
Institute::ICode, void SEntry();
Institute::IName void SDisplay();
Member functions – };
Trianer::AssignRem( ), class School:public Student,public
Trainer::TEntry( ), Teacher
Trainer::TDisplay( ), { char SCode[10],SName[20];
Learner:: LEntry( ), public:
Learner::LDisplay( ), School( );
Institute::IEntry ( ) void SchEntry();
(LDisplay can call IEntry( )) void SchDisplay();
S)
C

Institute::LDisplay( ) };
T
G

(IEntry can call LDisplay( ))


(P

(iv)If class institute was derived (i)Which type of inheritance is depicted


ar
m

privately from class Learner and by above example?


Ku

privately from class Trainer, then name Ans: Multiplel Inheritance.


er
nd

the member function(s)that could be (ii)Identify the member function(s) that


re

accessed through Objects of class cannot be called directly from the objects
Vi

Institute. of class School from the following


Ans: Institute::IEntry( ), TEntry()
Institute:: IDisplay( ), SDisplay()
SchEntry()
Ans: All the above three member
2007 OUT SIDE DELHI: function(s) can be called from the objects
of class School.
2.a) Differentiate between Protected and (iii)Write name of all member(s)
Private members of a class in context of accessible from member functions of
inheritance using C++. 2 class School.
Ans: Protected members will be Ans: Data Members : Teacher::Salary
inherited into the derived class (they are
accessible from the derived class). But Student::Attendance
Private members cannot be accessed
from the derived class. Student::Totmarks
(Remember that the memory will be School::SCode
reserved for private as well as protected School::SName
members for the derived class object) Member
Funcions:Teacher::AssignSal( )
2.d) Answer the questions (i) to(iv) Teacher::TEntry( )
based on the following code: Teacher::TDisplay( )
class Teacher Student::Sentry( )
{ char Student::SDisplay( )
TNo[5],Tname[20],Dept[10]; School::SChEntry( )

72 XII Computer
School::SChDisplay( ) {
(iv) If class School was derived privately -----
from class Learner and privately from ------
class Trainer, then name the member }
function(s)that could be accessed class B
through Objects of class School. {
Ans: School::SChEntry( ) -----
School::SChDisplay( ) -----
}
2006 DELHI: class C:public A,protected B
{
2.a) Define Multilevel and Multiple -----
inheritance in context of Object Oriented -----
Programming. Give suitable example to }
illustrate the same2 Ans:
Multilevel Inheritance: When a 2.d) Answer the questions (i) to(iv)
subclass inherits from a class that itself based on the following code
inherits from another class, it is known as class stationary
multilevel inheritance. { char Type;
char Manufacture[10];
public:
stationary( );
void Read_sta_details( );
void Disp_sta_details( );
};
class office:public stationary
{ int no_of_types;
S)
C

Eg: (for Multi Level Inheritance) float cost_of_sta;


T
G

class A public:
(P

{ void Read_off_details( );
ar
m

----- void Disp_off_details( );


Ku

------ };
er
nd

} class printer:private office


re

class B:public class A { int no_of_users;


Vi

{ char delivery_date[10];
----- public:
----- void Read_pri_details( );
} void Disp_pri_details( );
class C:protected B };
{ void main( )
----- { printer MyPrinter;
----- }
} (i) Mention the member names which are
Multiple Inheritance: When a sub class accessible by MyPrinter declared in
inherits from multiple base classes, it is main() function.
known as multiple inheritance. Ans: printer::Read_pri_details( );
printer::Disp_pri_details( );
(ii) What is the size of MyPrinter in
bytes?
Ans: 29 Bytes
(iii)Mention the names of functions
accessible from the member function
Read_pri_details() of class printer.
Ans:
stationary::Read_sta_details( )
stationary::Disp_sta_details( )
Eg: (for Multiple Inheritance) office::Read_off_details( )
class A office::Disp_off_details( )

73 XII Computer
printer::Disp_pri_details( ) 2005 DELHI:
2006 OUT SIDE DELHI: 2.d) Answer the questions (i) to(iv)
based on the following code:4
2.d)Answer the questions (i) to(iv) based class Medicine
on the following code:4 {
class furniture char Category[10];
{ char Type; char
char Mode[10]; Date_of_manufacture[10];
public: char Company[20];
furniture( ); public:
void Read_fur_details(); Medicine();
void Disp_fur_details(); void entermedicinedetails();
}; void showmedicinedetails();
class sofa:public furniture };
{ int no_of_seats; class capsule:public Medicine
float cost_sofa; {
public: protected:
void Read_sofa_details(); char capsule_name[30];
void Disp_sofa_details(); char volume_lable[20];
}; public:
class office:public sofa float Price;
{ int no_of_pieces; capsules();
char delivery_date[10]; void entercapsuledetails();
public: void showcapsuledetails();
void Read_office_details(); };
S)

void Didp_office_details(); class Antibiotics:public Capsule


C

}; { int Dosage_units;
T
G

void main() char side_effects[20];


(P
ar

{ int Use_within_days;
m

office MyFurniture; public:


Ku

} Antibiotics();
er
nd

(i)Mention the member names which void enterdetails();


re
Vi

accessible by Myfurniture declared in void showdetails();


main() function. };
Ans: (i)How many bytes will be required by an
Data Members: No data member can be object of class Medicines and an object of
called from Myfurniture object. class Antibiotics respectively?
Member Functions: Ans: Medicine – 40 Bytes
Furniture::Read_fur_details() Antibiotics Object – 118 Bytes
Furniture::Disp_fur_details() (ii)Write the names of all the member
Sofa::Read_sofa_details() functions accessible from the object of
Sofa::Disp_sofa_details() class Antibiotics.
Office::Read_office_details() Ans:
Office::Didp_office_details() Medicine::entermedicinedetai
(ii)what is the size of Myfurniture in ls()
bytes? Medicine::showmedicinedetai
Ans: 29 Bytes ls()
(iii)Mention the names of functions Capsules::entercapsuledetails
accessible from the member function ()
Read_office_details() of class office. Capsules::showcapsuledetails
Ans: ()
Furniture::Read_fur_details( ) Antibiotics::enterdetails()
Furniture::Disp_fur_details( ) Antibiotics::showdetails()
Sofa::Read_sofa_details( ) (iii)Write the names of all the members
Sofa::Disp_sofa_details( ) accessible from member functions of
Office::Disp_office_details( ) class capsules.
Ans:Data Members:
74 XII Computer
Capsule::capsule_name[30] (ii)Write the names of all the member
Capsule::volume_lable[20] functions accessible from the object of
Capsule::Price class PainReliever.
Member Funcitons: Ans: Drug::enterdrugdetails()
Medicine::entermedicinedetai Drug::void showdrugdetails()
ls() Tablet::entertabletdetails()
Medicine::showmedicinedetai Tablet::showtabletdetails()
ls() PainReliever::enterdetails()
Capsule::entercapsuledetails() PainReliever::showdetails()
Capsule::showcapsuledetails() (iii)Write the names of all the members
(iv)Write names of all the data members accessible from member functions of
which are accessible from objects of class class Tablet.
antibiotics. Ans:Data Members:
Data members: Tablet::tablet_name[30];
Capsule::Price Tablet::volume_lable[20];
Tablet::Price;
2005 OUTSIDE DELHI: Member Functions:
Drug::enterdrugdetails()
2.d) Answer the questions (i) to(iv) Drug::showdrugdetails()
based on the following code: Tablet::entertabletdetails()
class Drug Tablet::showtabletdetails()
{ char Category[10]; (iv)Write names of all the data members
char which are accessible from objects of class
Date_of_manufacture[10]; PainReliever.
char Company[20]; Ans:Data Members: Tablet::Price
public:
2004 DELHI:
S)

Medicines();
C

void enterdrugdetails();
T
G

void showdrugdetails(); 2.c) Given the following definitions


(P
ar

}; answer the following:


m

class tablet:public Drug class livingbeing


Ku

{ { char specification[20];
er
nd

protected: int average;


re
Vi

char tablet_name[30]; public:


char volume_lable[20]; void read();
public: void show();
float Price; };
Tablet(); class ape: private
void entertabletdetails(); livingbeing
void showtabletdetails(); { int
}; no_of_organs,no_of_bones;
class PainReliever:public protected:
Tablet int iq_level;
{ int Dosage_units; public:
char side_effects[20]; void readape();
int Use_within_days; void showape();
public: };
PainReliever(); class human:public ape
void enterdetails(); { char race[20];
void showdetails(); char habitation[30];
}; public:
(i)How many bytes will be required by an void readhuman();
object of class Drug and an object of class };
PainReliever respectively? (i)Name the members, which can be
Ans: Drug Object - 40 Bytes accessed from the member functions of
Pain Reliever – 118 Bytes class human.
Ans: Data Members - ape::iq_level
human::race
75 XII Computer
human::habitation (When an object of the derived class is
Member Function – ape::readape( ) declared, in order to create it, firstly the
ape::showape( ) constructor of the base class is invoked
(ii)Name the members, which can be an then, the constructor of the derived
accessed by an object of class human. class is invoked. On the other hand, when
Ans: Data Members - No data members an object of the derived class is
can be accessed. destroyed, first the destructor of the
Member Functions: derived class is invoked followed by the
ape::readape(); destructor of the base class).
ape::showape(); ii) How many bytes does an object
human::readhuman(); belonging to class Outlet require?
(iii)What will be the size of an object of Ans: 133 Bytes
the (in bytes) of class human? iii) Name the member function(s) which
Ans: 78 Bytes. are accessed from the object(s) of class
Outlet.
2003 DELHI: Ans: Outlet::Enter( )
Outlet::Output( )
2.c)Consider the following and answer MNC::EnterData( )
the questions given below MNC::DisplayData( )
class MNC Branch::Add( )
{ char Cname[25]; Branch::Show( )
//Company name iv)Name the data member(s), which are
protected: accessible from the object(s) of class
char Hoffice[25]; //Head Branch.
office Ans: MNC::Country
public:
2002 DELHI:
S)

MNC( );
C

char Country[25];
T
G

void EnterData( ); 1.a) Illustrate the concept of Inheritance


(P
ar

void DisplayData( ); with the help of an example.


m

}; 2
Ku

class Branch:public MNC


er
nd

{ long NOE; //Number of Ans: The capability of one class to inherit


re
Vi

Employees propertied from another class, is called as


char Ctry[25]; //Country inheritance.
protected: The most important advantage of
void Association( ); inheritance is code reusability.
public: There are 5 types of inheritance:
Branch( ); (i) Single Inheritance): When a
void Add( ); sub class inherits only from
void Show( ); one base class, it is known as
}; single inheritance.
class Outlet:public Branch (ii) Multiple Inheritance: When a
{ sub class inherits from
char State[25]; multiple base classes, it is
public: known as multiple
Outlet( ); inheritance.
void Enter( ); (iii) Hierarchical Inheritance:
void Output( ); When many sub classes
}; inherit from a single base
Ans: class, it is known as
i) Which class constructor can be called hierarchical inheritance.
first at the time of declaration of an (iv) Multilevel Inheritance: When
object of class Outlet? a subclass inherits from a
Ans: MNC class constructor can be called class that itself inherits from
first at the time of declaration of an another class, it is known as
object of class Outlet. multilevel inheritance.

76 XII Computer
(v) Hybrid Inheritance: Hybrid (iii)Name the private member
inheritance combines two or function(s) of class Teacher.
more forms of inheritance. Ans: Teacher::Display( )
(iv)Is the member function OUT()
2001: accessible the objects of Dept?
Ans: Yes. Since it is public member
1.a) Reusability of classes is one of the function.
major properties of OOP. How is it
implemented in C++. 1999 DELHI:
2
Ans: Resuability of classes can be 2.a)What do you understand by visibility
implemented through Inheritance. Ie modes in class derivations? What are
After developing a class, if you want a these modes? 2
class which consists the features of this Ans: It is given in chapter 4, classes and
class( ie members ) and the other object as two answers. Ie Difference
features also, then instead of developing between private and protected, private
a class which consists all these features, and public.
you can inherited the existing features
(members) and you can develop new 2.c)Consider the following declarations
class consists the remaining features and answer the questions below:
using inheritance (in Object Oriented class vehicle
Programming ie in C++.) { int wheels;
protected:
2000 DELHI: int passenger;
void inputdata(int,int);
2.c)Consider the following and answer void outputdata();
S)

the questions given below: };


C

class heavy_vehicle:protected
T

class School
G

vehicle
(P

{ int A;
ar

protected: {
m

int diesel_petrol;
Ku

int B,C;
protected:
er

public:
nd

int load:
re

void INPUT(int);
Vi

void OUTPUT(); public:


}; void readdata(int,int);
class Dept:protected School void writedata();
{ };
int X,Y; class bus:private heavy_vehicle
protected: {
void IN(int,int) char make[20];
public: public:
void OUT(); void fetchdata(char);
}; void displaydata();
class Teacher:public Dept };
{ int P; (i)Name the base class and derived class
void DISPLAY(void); of the class heavy_vehicle.
public: Ans: Base class of heavy_vehicle –
void ENTER(); vehicle
}; Derived class of heavy_vehincle –
(i)Name the base class and derived class bus
of the class Dept. (ii)Name the data member(s) that can be
Ans: Base class of Dept - School accessed from function displaydata.
Derived class of Dept - Teacher Ans: bus::make
(ii)Name the data member(s) that can be heavy_vehicle::load
accessed from function OUT(). vehicle::passenger
Ans: Dept::X Dept::Y (iii)Name the data member(s) that can
School::B be accessed by an object of bus class.
School::C
77 XII Computer
Ans: No data member can be accessed by class PUBLISHER
an object of bus class. {
(iv)Is the member function outputdata char Pub[12];
accessible to the objects of heavy_vehicle double Turnover;
class? protected:
Ans: No. void Register();
public:
PUBLISHER();
1998 DELHI: void Enter();
void Display();
2.c) Consider the following declarations };
and answer the questions below: class BRANCH
{
class PPP char CITY[20];
{ int H; protected:
protected: float Employees;
int S; public:
public: BRANCH();
void INPUT(int); void Haveit();
void OUT(); void Giveit();
}; };
class QQQ:private PPP class AUTHOR:private BRANCH,public
{ int T; PUBLISHER
protected: {
int U; int Acode;
public: char Aname[20];
void INDATA(int,int); float Amount;
S)

public:
C

void OUTPUT();
T

AUTHOR();
G

};
(P

class RRR:public QQQ void Start();


ar

void Show();
m

{ int M;
Ku

public: };
er

(i) Write the names of data


nd

void DISP(void);
re

}; members, which are


Vi

(i)Name the base class and derived class accessible from objects
of the class QQQ. belonging to class AUTHOR.
Ans:Base class of QQQ – PPP (ii) Write the names of all the
Derived class of QQQ – RRR member functions, which are
(ii)Name the data member(s) that can be accessible from objects
accessed from function DISP(). belonging to class BRANCH.
Ans: QQQ::U , RRR::M (iii)Write the names of all the
(iii)Name the member function(s) , members which are
which can be accessed from the object of accessible from member
class RRR. functions of class AUTHOR.
Ans: QQQ::INDATA( ) (iv)How many bytes will be
QQQ::OUTPUT( ) RRR::DISP( required by an object
) belonging to class AUTHOR?
(iv) Is the member function OUT() Answer:
accessible by the objects of the class (i) None of data members are
QQQ? Ans: No. accessible from objects
belonging to class AUTHOR.
(ii) Haveit(), Giveit()
Model Paper 1 for 2008-09 (iii)Data members: Employee,
Acode, Aname, Amount
Batch: Member function: Register(),
Enter(), Display(), Haveit(),
2.f)Answer the questions (i) to (iv) based Giveit(), Start(), Show(),
on the following: (iv) 70
4
78 XII Computer
Model Paper 2 for 2008-09 iv)How many bytes will be required by
an object belonging to class SHOP?
Batch: Answer: 66
2.e) Answer the questions (i) to (iv)
based on the following: Sample Paper 1 for 2009-10
4 batch:
class CUSTOMER
{ 2.d) Answer the questions (i) to (iv)
int Cust_no; based on the following:
char Cust_Name[20]; 4
protected: class PUBLISHER
void Register(); {
public: char Pub[12];
CUSTOMER(); double Turnover;
void Status(); protected:
}; void Register();
class SALESMAN public:
{ PUBLISHER();
int Salesman_no; void Enter();
char Salesman_Name[20]; void Display();
protected: };
float Salary; class BRANCH
public: {
SALESMAN(); char CITY[20];
void Enter(); protected:
S)

void Show(); float Employees;


C
T

}; public:
G
(P

class SHOP : private CUSTOMER , public BRANCH();


ar

SALESMAN void Haveit();


m

{
Ku

void Giveit();
char Voucher_No[10];
er

};
nd

char Sales_Date[8]; class AUTHOR : private BRANCH , public


re

public:
Vi

PUBLISHER
SHOP(); {
void Sales_Entry(); int Acode;
void Sales_Detail(); char Aname[20];
}; float Amount;
i)Write the names of data members public:
which are accessible from objects AUTHOR();
belonging to class CUSTOMER. void Start();
Ans: None of data members are void Show();
accessible from objects belonging to class };
CUSTOMER.
ii)Write the names of all the member (i) Write the names of data members,
functions which are accessible from which are accessible from objects belong-
objects belonging to class SALESMAN. ing
Ans: Enter(), Show() to class AUTHOR.
Ans)None of data members are
iii)Write the names of all the members accessible from objects belonging to
which are accessible from member class AUTHOR.
functions of class SHOP.
Ans: Data members: Voucher_No, (ii) Write the names of all the member
Sales_Date, functions which are accessible from ob-
Salary jects
Member functions:Sales_Entry( ), belonging to class BRANCH.
Sales_Details( ), Enter (), Show( ), Ans) Haveit( ), Giveit( )
Register( ), Status( ).
79 XII Computer
(iii) Write the names of all the members Ans) None of data members are
which are accessible from member func- accessible from objects belonging to class
tions AUTHOR.
of class AUTHOR.
Ans) Data members: Employees, Acode, (ii) Write the names of all the member
Aname, functions which are accessible from
Amount objects
Member function: Register(), Enter(), belonging to class SALESMAN.
Display(), Haveit(), Giveit(), Start(), Ans) Enter(), Show()
Show(),
(iii) Write the names of all the members
(iv) How many bytes will be required by which are accessible from member
an object belonging to class AUTHOR? functions of
Ans) 70 class SHOP.
Ans) Data members: Voucher_No,
Sales_Date,
Sample Paper 2 for 2009-10 Salary
Member function : Sales_Entry(),
Batch: Sales_Detail(),
Enter(),Show(),Register(),
2.d) Answer the questions (i) to (iv)
Status()
based on the following:
4
(iv) How many bytes will be required by
class CUSTOMER
an object belonging to class SHOP?
{
Ans) 66
int Cust_no;
char Cust_Name[20];
S)

protected:
C
T

void Register();
G
(P

public:
ar

CUSTOMER();
m
Ku

void Status();
er

};
nd

class SALESMAN
re
Vi

{
int Salesman_no;
char Salesman_Name[20];
protected:
float Salary;
public:
SALESMAN();
void Enter();
void Show();
};
class SHOP : private CUSTOMER , public
SALESMAN
{
char Voucher_No[10];
char Sales_Date[8];
public:
SHOP();
void Sales_Entry();
void Sales_Detail();
};

(i) Write the names of data members


which are accessible from objects
belonging to
class CUSTOMER.
80 XII Computer
7.DATA FILE HANDLING Statement 1:
F. tellg ( );
DELHI 2010:
Statement 2:
4. (a) Observe the program segment F. seekp(Pos-sizeof(C)) ;
given below carefully and fill the OR
blanks marked as Statement 1 and F.seekp(-sizeof(C), ios::cur);
Statement 2 using tellg() and seekp()
functions for performing the required (b) Write a function in C++ to count
task. 1 the words “this” and “these” present
in a text file “ARTICLE.TXT”. 2
#include <fstream.h> [Note that the words “this” and “these” are
class Client complete words]
{
long Cno; Ans)
charName[20],Email[30] ;
public: void COUNT ( )
//Function to allow user to enter {
//the Cno, Name,Email
ifstream Fil; // ifstreamFil(“ARTICLE.TXT");
void Enter() ;
//Function to allow user to enter Fil. open(“ARTICLE.TXT”);
//(modify) Email char Word[80] ,Ch;
void Modify() ; int Cl =0, C2 = 0, I=O;
long ReturnCno() while(Fil.get(Ch))
{ {
return Cno; if (Ch! = ' ')
S)

}
C

Word[I++] = Ch;
};
T
G

else
(P

{
ar

void ChangeEmail()
m

Word[I] = ‘\0’;
Ku

{
if (strcmp (Word,“this”)==0)
er

Client C;
nd

fstream F; Cl++;
re
Vi

F.open (“INFO.DAT”,ios::binary else if (strcmp(Word,“these”)==0)


|ios::in|ios::out); C2++;
long Cnoc; //Client’s no. whose I=0;
//Email needs to be changed
}
cin>>Cnoc;
while (F.read((char*)&C, }
sizeof(C))) cout<<“Count of -this- in file:"<<Cl;
{ cout<<“Count of -these- in file:"<<C2;
// OR cout<<“Count of -this- and –
if (Cnoc= =C.ReturnCno())
//these- in file: “<<Cl+C2;
{
Fil.close( );
C.Modify(); //Statement 1
int Pos = __________
}
//To find the current position
//of file pointer (c) Write a function in C++ to search
and display details of all flights, whose
_______________ // Statement 2 destination is “Mumbai” from a binary
//To move the file pointer to
//write the modified record file “FLIGHT.DAT”. Assuming the
//back onto the file for the binary file is containing the objects of
//desired Cnoc the following class. 3
F.write((char*)&C, sizeof(C));
}
class FLIGHT
}
F.close();
{ int Fno; //Flight Number

} char From[20]; //Flight Starting Point

Ans) char To[20]; //Flight Destination

81
XII Computer
public: Statement 2 using tellg() and seekp()
char* GetFrom( ) functions for performing the required
{return From;} task. 1
char* GetTo( )
{return To;} #include <fstream.h>
void Enter( ) class Customer
{ { long Cno;
cin>>Fno; char Name[20],Mobile[12];
gets(From); public:
gets(To); //Function to allow user to enter
//the Cno, Name,Mobile
}
void Enter( );
void Display( ) //Function to allow user to enter (modify)
{ //mobile number
cout<<Fno<<“:”<<From<<“:”<<To<<endl; void Modify( );
} //Function to return value of Cno
}; long GetCno( )
{
Ans) return Cno;
void Read ( ) }
{ };
FLIGHT F; void ChangeMobile( )
ifstream fin; {
fin.open(“FLIGHT.DAT”,ios::binary); Customer C;
//OR ifstream fin (“FLIGHT. DAT”, ios: :binary) ;
fstream F;
while(fin.read((char*)&F,sizeof(F)))
F.open(“CONTACT.DAT”,ios::binary|
S)

{
C

ios::in|ios::out);
T

if (strcmp(F. GetTo(),“Mumbai”))
G

long Cnoc;
(P

F.Display( ) ;
ar

//Customer no. whose mobile number


}
m

//needs to be changed
Ku

fin.close(); // cin>>Cnoc;
er
nd

} while (F.read((char*)&C,sizeof(C)))
re

OR {
Vi

void Read( ) if (Choc==C.GetCno( ))


{ {
FLIGHT F; C.Modify( );
ifstream fin; int Pos=_____________ //Statement 1
fin.open (“FLIGHT. DAT”, ios::binary) ; //To find the current position of file pointer
//OR ifstream fin (“FLIGHT. DAT”, ios:: binary; ______________ //Statement 2
if (fin) //To move the file pointer to write the
//modified record back onto the file for the
{ fin.read((char*)&F, sizeof (F)); //desired Cnoc
while(!fin.eof( )) F.write((char*)&C, sizeof(C));
{ }
if (strcmp(F. GetTo( ),“Mumbai”)) }
F.Display( ); F. close ( ) ;
fin.read((char*)&F,sizeof(F)) }
}
fin.close( ); Ans)
} Statement 1
F.tellg( ) ;
OUTSIDE DELHI 2010:
Statement 2
4. (a) Observe the program segment F.seekp(Pos-sizeof(C));
given below carefully and fill the OR
blanks marked as Statement 1 and File.seekp(-l*sizeof(C),ios::cur);
82
{
(b) Write a function in C++ to count return To;
the words “to” and “the” present in a }
text file “POEM.TXT”. 2 void Input( )
[Note that the words “to” and “the” are complete {
words]
cin>>Tno;
gets(From);
Ans)
gets(To);
void COUNT( )
}
{
void Show( )
ifstream Fil; {
Fil. open (“POEM.TXT”); cout<<Tno<<“:”<<From<<“:”<<To<<endl;
//OR ifstream Fill(“POEM.TXT”); }
char Word[8O], Ch; };
int Cl =0, C2=0, i=0;
while(Fil.get(Ch)) Ans)
{ void Read ( )
if (Ch! = ‘ ‘) {
Word[i++] = Ch; TRAIN T;
else ifstream fin;
{ fin. open (“TRAIN.DAT”,ios::binary);
Word[i] = ‘\0’; //OR ifstream fin (“TRAIN.DAT”, ios::binary);
if (strcmp (Word, “to”) ==0) while(fin.read((char*)&T, sizeof(T)))
Cl++; {
else if (strcmp (Word, “the”) ==0) if(strcmp(T.GetTo(),”Delhi”)==O)
S)

C2++; T.Show( ) ;
C
T

i=0; }
G
(P

} fin.close( );
ar

} }
m
Ku

cout<<”Count of -to- in file:”<<Cl;


er
nd

cout<<”Count of -the- in file:”<<C2; DELHI 2009:


re

//OR cout«”Count of -to- and -the- in


Vi

Fil.close( ); 4. (a) Observe the program segment


} given below carefully and fill in the
blanks marked as Line 1 and Line 2
(c) Write a function in C++ to search using fstream functions for performing
and display details. of all trains, the required task. 1
whose destination is “Delhi” . from a
binary file “TRAIN.DAT”. Assuming the #include <fstream.h>
binary file is containing the objects of class Stock
the following class. {
3 long Ino ; //Item Number
char Item [20] ; //Item Name
class TRAIN int Qty ; //Quantity
{ public:
int Tno; // Train Number void Get(int);
charFrom[20]; // Train Starting Point //Function to enter the content
charTo [20]; // Train Destination void show( );
public: //Function to display the content
char* GetFrom( ) void Purchase (int Tqty)
{ {
return From; Qty + = Tqty ;
} } //Function to increment in Qty
char* GetTo( ) long KnowIno ( )
{
83
return Ino; Note: In the above example, ‘do’
} occurring as a part of word done is not
}; considered.
void Purchaseitem(long PINo, int PQty)
//PINo -> Ino of the item purchased Ans)
//PQty -> Number of item purchased
void COUNT_DO( )
{
{
fstream File;
ifstream Fi1;
File.open(“ITEMS.DAT”, ios ::
Fil.open(“MEMO.TXT”);
binarylios ::inlios :: out); //OR ifstream Fil(“MEMO.TXT”);
int Pos = –1 ; char Word[80],Ch;
Stock S ; int Count =0,I=0;
while (Pos = = –1 && File.read((char*) &S, sizeof
(S))) while(Fi1.get(Ch))
if (S. KnowIno( ) ==PINo) {
{ if (Ch! = ‘ ‘)
S. Purchase (PQty); Word[I++] = Ch;
//To update the number of Items else
Pos = File.tellg ( ) -sizeof (S) ; {
__________________; Word[I] = ‘\0’;
//Line 1: To place the file if (strcmp (Word, “do”) ==0)
//pointer to the required position
Count++;
___________________;
//Line 2: To write the object S on to I=O;
//the binary file }
} }
if (Pos = = –1) cout<<”Count of-do- in file:”<<Count;
S)
C

cout<<“No updation done as Fil.close( );


T
G

required Ino not found..” ; }


(P
ar

File.close ( ) ;
m

(c) Write a function in C++ to read and


Ku

}
er

display the detail of all the users


nd

Ans) whose status is ‘A’ (i.e. Active) from a


re
Vi

binary file “USER.DAT”. Assuming the


Statement 1: binary file “USER.DAT” is containing
File.seekp(Pos); objects of class USER, which is
OR defined as follows: 3
File.seekp(-sizeof(A), ios:: cur);
class USER
Statement 2: {
File.write((char*)&S, sizeof(S)); int Uid ; //User Id
OR char Uname [20];//User Name
File.write((char*)&S, sizeof(Stock)); char Status; //User Type: A Active I Inactive

(b) Write a function COUNT_DO( ) in Public:


C++ to count the presence of a word void Register ( );
//Function to enter the content
‘do’ in a text file “MEMO.TXT” 2
void show ( ) ;
//Function to display all data members
Example: char Getstatus ( )
If the content of the file “MEMO.TXT” {
is as follows: return Status;
I will do it, if you request me to do it. }
It would have been done much earlier. };
The function COUNT_DO ( ) will
display the following message: Ans)
Count of -do- in file : 2
84
void DisplayActive ( ) {
{ Qty+=Tqty;
USER U; } //Function to increment in Qty
ifstream fin; long GetAno( )
fin.open (“USER.DAT”, ios::binary); {
//OR ifstream fin (“USER.DAT”, ios::binary); return Ano;
while(fin.read((char*)&U, sizeof(U))) }
{ };
if(U.Getstatus()==’A’)
U.show( ); void BuyBook(long BANo,int BQty)
} //BANo ->Ano of the book purchased
fin.close( ); //BQty ->Number of books purchased
} {
OR fstream File;
void DisplayActive() File.open(“STOCK.DAT” ,
{ ios::binary|ios::in|ios::out);
USER U; int position=-l;
ifstream fin; Library L;
fin.open (“USER.DAT”, ios::binary); while(Position==-l &&
//OR ifstream fin(“USER.DAT”,ios::binary); File.read((char*)&L,sizeof(L)))
if (fin) if (L.GetAno()==BANo)
{ {
fin.read((char*)&U, sizeof(U)); L.Buy(BQty);
while(!fin.eof()) //To update the number of Books
{ Position = File.tellg()-sizeof(L) ;
S)

if (U.Getstatus( )==’A’) ____________________;


C
T

//Line 1: To place the file pointer to the required position


G

U.show( ) ; ____________________;
(P

fin.read((char*)&U, sizeof(U))
ar

//Line 2:To write the object L on to the binary file


m

} }
Ku

fin.close( ); if (Position==-l)
er
nd

} cout<< “No updation do:r{e as


re
Vi

required Ano not found..”;


OUTSIDE DELHI 2009: File.close( );
}
4. (a) Observe the program segment Ans)
given below carefully and fill the Statement 1
blanks marked as Line 1 and Line 2 File.seekp(Position);
using fstream functions for performing OR
the required task. 1 File. seekp (-sizeof (L), ios::cur);

#include <fstream.h> Statement 2


class Library File.write((char*)&L, sizeof(L));
{ OR
long Ano; File.write((char*)&L,sizeof(Library));
//Ano - Accession Number of the Book
char Title[20]; (b) Write a function COUNT_TO( ) in
//Title - Title of the Book
C++ to count the presence of a word
int Qty;
//Qty - Number of Books in Library ‘to’ in a text file “NOTES.TXT”. 2
public:
void Enter (int); Example:
//Function to enter the content If the content of the file “NOTES.TXT”
void Display(); is as follows:
//Function to display the content It is very important to know that
void Buy(int Tqty) smoking is injurious to health.
85
Let us take initiative to stop it. };
The function COUNT_TO( ) will display
the following message: Ans)
Count of -to- in file: 3 void DisplayL_M( )
Note: In the above example, ‘to’ {
occurring as a part of word stop is not CLUB C;
considered. fstream fin;
fin. open (“CLUB.DAT”,
Ans) ios::binary|ios::in);
void COUNT_TO ( ) //OR ifstream fin (“CLUB.DAT”, ios::binary);
{ while(fin.read((char*)&C, sizeof(C))
ifstream Fil; {
//OR ifstream Fi1(“NOTES.TXT”); if(C.WhatType()==’L’||C.WhatType()==’M’)
Fil.open(“NOTES.TXT”) C .Display ( );
char Word[80],Ch; }
int Count =0, I=0; fin.close( );
while(Fil.get(Ch)) }
{ OR
if (Ch!= ‘ ‘) void Disp1ayL_M ( )
Word [I++] = Ch; {
else CLUB C;
{ fstream fin;
Word[I] = ‘\0’; fin.open (“CLUB.DAT”, ios::binary | ios::in);
//ifstream fin (“CLUB.DAT”,ios::binary);
if (strcmp (Word, “to”) ==0) if(fin)
Count++;
S)

{
C

I=O;
T

fin.read((char*)&C, sizeof(C));
G

}
(P

while(!fin.eof())
ar

} {
m

Fil.close( );
Ku

if(C.WhatType()==’L’||C.WhatType()==’M’)
er

cout<<”Count of -to- in file: “<<Count; C. Display( );


nd

}
re

fin.read((char*)&C, sizeof(C));
Vi

}
(c) Write a function in C++ to read and }
display the detail of all the members fin.close( );
whose membership type is ‘L’ or ‘M’ }
from a binary file “CLUB.DAT”.
Assume the binary file “CLUB.DAT” DELHI : 2008:
contains objects of class CLUB,
which is defined as follows: 3 4.a)Observe the program segment
class CLUB given below carefully, and answer the
{ question that follows
int Mno; //Member Number
char Mname [20]; //Member Name class Applicant
char Type; //Member Type: L Life Member M {
//Monthly Member G Guest
long Aid ; // Applicant’s Id
public:
char Name[20] ; // Applicant’s Name
void Register( );
//Function to enter the content float Score ; // Applicant’s Score
void Display( ); public ;
//Function to display all data members void Enroll( ) ;
char WhatType( ) void Disp( ) ;
{ void MarksScore( ) ;
return Type; //Function to change Score
} long R_Aid( )
{
86
return Aid; int lowercount=0;
) while(fin)
}; {
void ScoreUpdate (long Id) fin.get(ch);
{ if(islower(ch))
fstream File ; lowercount++;
File.open (“APPLI.DAT” , ios :: binary | }
ios :: in | ios :: out) ; cout<<"\nTotal number of Lowercase
Applicant A ; alphabets in the file = "<<lowercount;
int Record = 0, Found = 0 ; getch( );
while (!Found && File.read }
( (char*)&C, sizeof(c) ) )
{ 4.c)Given a binary file PHONE.DAT,
if (Id = = A.R_Aid( ) ) containing records of the following
{ cout << “Enter new Score” ; structure type
A.MarksScore( ) ;
____________ //Statement 1 class phonlist
____________ //Statement 2 {
Found=1; char Name[20] ;
} char Address[30] ;
Record++ ; char AreaCode[5] ;
} char PhoneNo[15] ;
if (Found = = 1) public ;
cout << “Record Updated” ; void Register( ) ;
File.close( ) ; void Show( ) ;
S)
C

} int CheckCode(char AC[ ])


T
G

{ return strcmp(AreaCode,AC) ;
(P

}
ar

Write the Statement1 to position the


m

};
Ku

File Pointer at the beginning of the


er

Record for which the Applicant’s Id


nd

matches with the argument passed, Write a function TRANSFER( ) in C++,


re
Vi

and Statement 2 to write the updated that would copy all those records
record at that position. which are having AreaCode as “DEL”
from PHONE.DAT to PHONBACK.DAT.
Solution:
Ans)
Statement 1 void TRANSFER( )
File.seekp(File.tellp( )-sizeof(A)); {
ifstream fin(“PHONE.DAT’,ios::in,ios::binary);
ofstream fout(“PHONEBACK.DAT”,
Statement 2 ios::out,ios::binary);
File.seekp(Record*sizeof(Applicant)); phonlist P;
or while(fin) // or while(!fin.eof( ))
File.write((char*)&A,sizeof(A)); {
fin.read((char*)&P,sizeof(P));
4.b) Write a function in C++ to count if(P.CheckCode(“DEL”)= = 0)
the number of lowercase alphabets fout.write((char*)&P,sizeof(P));
present in a text file “BOOK.TXT”. }
fin.close( );
Solution: fout.close( );
void LowerLetters( ) }
{
clrscr( ); OUTSIDE DELHI 2008:
ifstream fin("BOOK.TXT",ios::in);
char ch;
87 cbse
4.a)Observe the program segment Statement 2
given below carefully, and answer the File.write((char*)&C,sizeof(C));
question that follows Or
File.write((char*)&C,sizeof(Candidate));
class candidate
{
long Cid ; // Candidate’s Id 4.b)Write a function in C++ to count
char CName[20]; // Candidate’s Name the number of uppercase alphabets
float Marks ; // Candidate’s Marks present in a text file “ARTICLE.TXT”.
public ;
void Enter( ) ; Solution:
void Display( ) ; void UpperLetters( )
void MarksChange( ) ; {
//Function to change marks clrscr( );
long R_Cid( ) ifstream fin("ARTICLE.TXT",ios::in);
{ char ch;
return Cid; int uppercount=0;
} while(fin)
}; { fin.get(ch);
void MarksUpdate (long Id) if(isupper(ch))
{ uppercount++;
fstream File ; }
File.open (“CANDIDATE.DAT”, ios :: cout<<"\nTotal number of Uppercase
binary|ios::in|ios :: out) ; alphabets in the file = "<<uppercount;
Candidate C ; getch( );
S)
C

int Record = 0, Found = 0 ; }


T
G

while (!Found&&File.read((char*)&C, sizeof(C)))


(P

{ 4.c) Given a binary file


ar
m

if (Id = =C.R_Cid( )) TELEPHON.DAT, containing records of


Ku

{ cout << “Enter new Marks” ; the following class Directory :


er
nd

C.MarksChange( ) ;
re
Vi

____________ //Statement1 class Directory


___________ //Statement 2 {
Found = 1 ; char Name[20] ;
} char Address[30] ;
Record++ ; char AreaCode[5] ;
} char phone_No[15] ;
if (Found = = 1) public ;
cout << “ Record Updated” ; void Register( ) ;
File.close( ) ; void Show( ) ;
} int CheckCode(char AC[ ])
{ return strcmp(AreaCode, AC) ;
Write the Statement to position the }
File Pointer at the beginning of the };
Record for which the Candidate’s Id
matches with the argument passed, Write a function COPYABC( ) in C++,
and Statement 2 to write the updated that would copy all those records
Record at that position. having AreaCode as “123” from
Ans) TELEPHON.DAT to TELEBACK.DAT.
Statement 1
File.seekp(File.tellp( )-sizeof(C)); Solution:
Or
File.seekp(Record*sizeof(C)); void COPYABC( )
{ ifstream fin(“TELEPHON.DAT’,ios::in|ios::binary);
88 cbse.extramarks.com
ofstream fout(“TELEBACK.DAT”,ios::out,ios|binary); }
Directory D; File . close( ) ;
while(fin) // or while(!fin.eof( )) }
{
fin.read((char*)&D,sizeof(D)); If the function AllocateMarks( ) is
if(D.CheckCode(“123”)= = 0) supposed to Allocate Marks for the
fout.write((char*)&D,sizeof(D)); records in the file MARKS.DAT based
} on their value of the member
fin.close( ); TimeTaken. Write C++ statements for
fout.close( ); the statement 1 and statement 2,
} where, statement 1 is required to
position the file write pointer to an
DELHI : 2007 appropriate place in the file and
statement 2 is to perform the write
4.a) Observe the program segment operation with the modified record.
given below carefully, and answer the
question that follows Ans)
Statement 1
class PracFile File.seekp(File.tellp( )-sizeof(P));
{ File.seekp(Record*sizeof(P));
int Pracno ;
char PracName[20] Statement 2
int TimeTaken ; File.write((char*)&P,sizeof(P));
int Marks ; File.write((char*)&P,sizeof(PracFile));
public :
S)
C

void EnterPrac( ) ; 4.b) Write a function in C++ to print


T
G

//Function to enter PracFile details the count of the word is as an


(P

void ShowPrac( ) : independent word in a text file


ar
m

//Function to display PracFile details DIALOGUE.TXT.


Ku

int RTime( )//function to return Time Taken For example,if the content of the file
er
nd

{ DIALOGUE.TXT is
re

return TimeTaken;}
Vi

This is his book. Is this book good ?


void Assignmarks(int M) Then the output of the program
//Function to assign Marks
{ should be 2.
Marks = M ;
} Solution:
};
void AllocateMarks( ) Ans)
{ void COUNT_IS ( )
fstream File ; {
File.open (“MARKS.DAT”, ios :: binary ifstream Fil;
//OR ifstream Fi1(“NOTES.TXT”);
| ios :: in | ios :: out ) ; Fil.open(“DIALOGUE.TXT”)
PracFile P ; char Word[80],Ch;
int Record = 0 ; int Count =0, I=0;
while (File.read ( (char*) &P, sizeof (P) ) )
while(Fil.get(Ch))
{ {
if (P.RTime( ) > 50) if (Ch!= ‘ ‘)
P.Assignmarks(0) Word [I++] = Ch;
else else
P.Assignmarks(10) {
_____________;//Statement 1
Word[I] = ‘\0’;
_____________;//Statement2 if (strcmp (Word, “is”) ==0)
Record++ ; Count++;
89 virender.sahrawat@gmail.com
I=O; void EnterExp( ) ;
} //function to enter Experiment details
} viod ShowExp( ) ;
//function to display Experiment details
Fil.close( );
char RChecked( )
cout<<”Count of -is- in file: “<<Count; //function to return Expno
} {
return Checked;
4.c)Given a binary file GAME.DAT, }
containing records of the following void Assignmarks (int M)
structure type //function to assign Marks
{
struct Game Marks = M;
{ }
char GameName[20] ; };
char Participate[10][30] ;
}; void ModifyMarks( )
{
Write a function in C++ that would fstream File ;
read contents from the file GAME.DAT File.open (“Marks.Dat”, ios :: binary l
and creates a file named BASKET.DAT ios :: in l ios :: out) ;
copying only those records from Labrecord L ;
GAME.DAT where the game name is int Rec=0 ;
“Basket Ball”. while (File.read ( (char*) &L,sizeof (L)))
{
S)

Solution: if (L.RChecked( )= =’N’)


C

L.Assignmarks(0)
T
G

else
(P

void BPlayers( )
ar

{ L.Assignmarks (10)
m
Ku

ifstream fin(“GAME.DAT’,ios::in,ios::binary); _______________; //Statement 1


er

ofstream fout(“BASKET.DAT”,ios::out|ios::binary);
nd

Game G;
re

________________;//Statement 2
Vi

while(fin) // or while(!fin.eof( ))
{ Rec++ ;
fin.read((char*)&G,sizeof(Game)); }
if(strcmp(G.GameName,”Basket Ball”)= = 0)
File.close( ) ;
fout.write((char*)&G,sizeof(G));
}
}
fin.close( );
If the function ModifyMarks ( ) is
fout.close( );
supposed to modify marks for the
}
records in the file MARKS.DAT based
on their status of the member
OUTSIDE DELHI : 2007
Checked (containg value either ‘Y’ or
‘N’).Write C++ statements for the
4.a) Observe the program segment
statement 1 and statement 2,where,
given below carefully,and answer the
statement 1 is required to position the
question that follows:
file write pointer to an appropriate
place in the file and statement 2 is to
class Labrecord
perform the write operation with the
{
modified record.
int Expno;
char Experiment[20] ;
Ans)
char Checked ;
Statement 1
int Marks ;
File.seekp(File.tellp( )-sizeof(L));
public : or
90 cbse.extramind.com
File.seekp(Rec*sizeof(L)); Write a function in C++ that would
read contents from the file
Statement 2 SPORTS.DAT and creates a file
File.write((char*)&L,sizeof(L)); named ATHLETIC.DAT copying only
or those records from SPORTS.DAT
File.write((char*)&L,sizeof(Labrecord)); where the event name is “Athletics”.

4.b)Write a function in C++ to print Solution:


the count of the word the as an void AthletsList( )
independent word in a text file {
STORY.TXT. ifstream fin(“SPORTS.DAT’,ios::in,
ios::binary););
For example,if the content of the file ofstream fout(“ATHLETIC.DAT”,
STORY.TXT is ios::out|ios::binary);
There was a monkey in the zoo.The Sports S;
monkey was very naughty. while(fin) // or while(!fin.eof( ))
Then the output of the program {
should be 2. fin.read((char*)&S,sizeof(Sports));
if(strcmp(S.Event,”Athletics”)= = 0)
Solution: fout.write((char*)&S,sizeof(S));
void COUNT_THE ( ) }
{ fin.close( );
ifstream Fil; fout.close( );
//OR ifstream Fi1(“NOTES.TXT”); }
Fil.open(“STORY.TXT”)
S)
C

char Word[80],Ch; DELHI : 2006


T
G

int Count =0, I=0;


(P

while(Fil.get(Ch)) 4.a)
ar
m

{ void main( )
Ku

if (Ch!= ‘ ‘)
er

{
nd

Word [I++] = Ch; char ch = ‘A’ ;


re
Vi

else fstream fileout(“data.dat”, ios::out) ;


{ fileout<<ch ;
Word[I] = ‘\0’; int p = fileout.tellg( )
if (strcmp (strupr(Word), “THE”) ==0) cout<<p ;
Count++; }
I=O;
} What is the output if the file content
} before the execution of the program is
Fil.close( ); the string “ABC”
cout<<”Count of-the- in file: “<<Count; (Note that “ “ are not part of the file).
}
Ans) 1
4.c)Given a binary file
(Since, the file is opened in out mode, it looses all
SPORTS.DAT,containg records of the the previous content, if the file mode is app, then
following structure type: result will be 4)

struct Sports 4.b)Write a function to count the


{ number of words present in a text file
char Event[20] ; named “PARA.TXT”. Assume that each
char Participant[10][30] ; word is separated by a single
}; blank/space character and no
blanks/spaces in the beginning and
end of the file.
91 cbse.snipshot.com
is”<<C.Colony_Name;
Solution: cout<<”\nEnter the Number of
People”;
void WordsCount( ) cin>>C.No_of_People;
{ finout.seekp(finout.seekp( )-sizeof(C));
clrscr( ); finout.write((char *)&C,sizeof(C));
ifstream fin("PARA.TXT",ios::in); }
char ch; }
int Words=1;
if(!fin) OUTSIDE DELHI : 2006
{
cout<<”No words at all in the file”; 4.a)
exit(0); void main( )
} {
while(fin) char ch = ‘A’ ;
{ fin.get(ch); fstream fileout(“data.dat”, ios :: app);
if(ch= =’ ‘) fileout<<ch ;
Words++; int p = fileout.tellg( ) ;
} cout << p ;
cout<<"\nTotal number of Words in }
the file = "<<Words;
getch( ); What is the output if the file content
} before the execution of the program is
4.c)Following is the structure of each the string ? “ABC”
(Note that “ “ are not part of the file)
S)

record in a data file named


C

“COLONY.DAT”
T
G

Ans)4
(P
ar

struct COLONY
m

(Since, the file is opened in app mode, it retains the


Ku

{ previous content also, if the file mode is out, then


er

char Colony_Code[10] ; result will be 0 since it will loose all the old content
nd
re

char Colony_Name[10] of the file.)


Vi

int No_of_People ;
}; 4.b)Write a function to count the
number of blanks present in a text file
Write a function in C++ to update the named “PARA.TXT” .
file with a new value of No_of_People.
The value of Colony_Code and Solution:
No_of_People are read during the void BlanksCount( )
execution of the program. {
clrscr( );
Solution: ifstream fin("PARA.TXT",ios::in);
char ch;
void Update( ) int Blanks=0;
{ if(!fin)
fstream finout(“COLONY.DAT”,ios::in| { cout<<”No words at all in the file.
ios::out); So no blank spaces”;
COLONY C; exit(0);
finout.seekg(0); }
while(finout) while(fin)
{ {
finout.read((char *)&C, sizeof(C)); fin.get(ch);
cout<<”\nThe Colony Code is if(ch= =’ ‘)
“<<C.Colony_Code; Blanks++;
cout<<”\nThe Colony Name }
92 j
cout<<"\nTotal number of Blank //function to enter Book details
Spaces in the file = "<<Blanks;
getch( ); void showdetails( ) ;
//function to display Book details
}
int Rbook_no( )
{return Book_no ;}
4.c) Following is the structure of each //function to return Book_no
record in a data file named
“PRODUCT.DAT” . };

struct PRODUCT void Modify (Book NEW)


{ char Product_Code[10] ; {
char Product_Description[10] ; fstream File ;
int Stock ; File.open(“BOOK.DAT”, ios :: binary
}; |ios :: in | ios :: out) ;
Write a function in C++ to update the Book OB ;
file with a new value of Stock. The int Record = 0, Found = 0 ;
Stock and the Product_Code, whose
Stock to be updated, are read during while (!Found && File.read((char*)
the execution of the program. &OB, sizeof(OB) ) )
Solution: {
Recordsread++ ;
void Update( ) if (NEW.RBook_no( ) == OB.RBook_no( ))
{ {
fstream finout(“PRODUCT.DAT”, ___________ //Missing Statement
ios::in|ios::out);
S)

File.write((char*) &NEW, size of(NEW)) ;


C

PRODUCT P; Found = 1 ;
T
G

finout.seekg(0); }
(P
ar

while(finout) else
m
Ku

{ File.write((char*) &OB, sizeof(OB)) ;


er

finout.read((char *)&P, sizeof(P)); }


nd

cout<<”\nThe Product Code is if (!Found)


re
Vi

“<<P.Product_Code; cout << “Record for modification


cout<<”\nThe Product does not exist” ;
Description is”<< File.close( ) ;
P.Product_Description; }
cout<<”\nEnter the Stock: “;
cin>>P.Stock; If the function Modify( ) is supposed to
finout.seekp(finout.seekp( )-sizeof(P)); modify a record in file BOOK.DAT with
finout.write((char *)&P,sizeof(P)); the values of Book NEW passed to its
} argument, write the appropriate
} statement for Missing Statement
using seekp( ) or seekg( ), whichever
DELHI : 2005 needed, in the above code that would
write the modified record at its proper
4.a) Observe the program segment place.
given below carefully, and answer the
question that Ans)
File.seekp((Recordsread-1)*sizeof(NEW));
class Book OR
{ File.seekp(-sizeof(NEW), ios::curr);
int Book_no : OR
char Book_name[20] ; File.seekp(File.tellg()-sizeof(NEW));
public ;
void enterdetails( ) ;
93 jnvwestgodavari.yahoo.com
4.b)Write a function in C++ to count cout << setw(3) << Percentage << endl ;
and display the number of lines }
starting with alphabet ‘A’ present in a int ReturnPercentage( )
text file “LINES.TXT”. {
return Percentage;
Example : }
If the file “LINES.TXT” contains the };
following lines,
A boy is playing there. Write a function in C++, that would
There is a playground. read contents of file STUDENT.DAT
An aeroplane is in the sky. and display the details of those
Alphabets and numbers are allowed Students whose Percentage is above
in the password. 75.

The function should display the Ans)


output as 3 void Distinction()
{
Ans) Student S;
fstream Fin;
void counter( ) Fin.open(“STUDENT.DAT”,
{ ios::binary|ios::in);
char Aline[80]; while(Fin.read((char*)&S,
int Count=0; sizeof(Student))
ifstream Fin (“LINES.TXT”); if (S.ReturnPercentage()>75)
S.DisplayData();
S)

while(Fin.getline(Aline,80, ‘\n’))
C

if (Aline[0]== ‘A’) Fin.close();


T
G

}
(P

Count++;
ar

Fin.close( );
m
Ku

cout<<Count<<endl; OUTSIDE DELHI : 2005


er

}
nd

4.a) Observe the program segment


re
Vi

4.c)Given a binary file STUDENT.DAT, given below carefully , and answer


containing records of the following the question that follows :
class Student type
class Member
class Student {
{ int Member_no ;
char S_Admno[10] ; char Member_name[20] ;
//Admission number of student public :
char S_Name[30] ; void enterdetails ( ) ;
//Name of student //function to enter Member details
int Percentage ; void showdetails ( ) ;
//Marks Percentage of student //function to display Member details
public : int RMember_no( )
void EnterData( ) {
{ return Member_no;
gets(S_Admno); } //function to return Member_no
gets(S_Name); };
cin >> Percentage ; void Update (Member NEW)
} {
void DisplayData( ) fstream File ;
{ File.open(“MEMBER.DAT” , ios ::
cout << setw(12) << S_Admno ; binary |ios :: in | ios :: out) ;
cout << setw(32) << S_Name ; Member OM ;
94 cbse.nip.cs.com
int Recordsread = 0, Found = 0 ; An aeroplane is in the sky.
while (!Found && File.read((char*) Numbers are not allowed in the
& OM, sizeof(OM))) password.
{ The function should display the
Recordsread++ ; output as 3
if (NEW.RMember_no( ) ==
OM.RMember_no( )) Ans)
{ void COUNTALINES()
___________ //Missing Statement {
File.write((char*) & NEW , ifstream FILE(“STORY.TXT”);
sizeof(NEW) ; int CA=0;
Found = 1 ; char LINE[80];
} while (FILE.getline (LINE,80))
else if (LINE[0]!=’A’)
File.write((char*) & OM, CA++;
sizeof(OM)) ; cout<<”Not Starting with A counts to
} “<<CA<<endl;
if (!Found) FILE.close( );
cout<<”Record for modification does }
not exist” ;
File.close( ) ; 4.c) Given a binary file APPLY.DAT,
} containing records of the following
class Applicant type 3
If the function Update( ) is supposed
S)

to modify a record in file class Applicant


C

MEMBER.DAT with the values of { char A_Rno[10] ;


T
G
(P

Member NEW passed to its argument, //Roll number of applicant


ar

write the appropriate statement for char A_Name[30];


m

//Name of applicant
Ku

Missing statement using seekp( ) or


int A_Score; //Score of applicant
er

seekg( ), whichever needed, in the


nd

public :
re

above code that would write the


Vi

void Enrol( )
modified record at its proper place.
{ gets(A_Rno);
gets(A_Name);
Ans)
cin >> A_Score ;
File.seekp((Recordsread-1)*sizeof(OM));
}
OR
void Status( )
File.seekp(Recordsread*sizeof(OM));
{
OR
cout << setw(12) << A_Admno ;
File.seekp(-l*sizeof(OM),ios::curr);
cout << setw(32) << A_Name ;
OR
cout << setw(3) << A_Score << endl ;
File.seekp(file.tellg()-sizeof(OM)); }
int ReturnScore( )
2.b) Write a function in C++ to count {
and display the number of lines not return A_Score;
starting with alphabet ‘A’ present in a }
text file “STORY.TXT”. };
Write a function in C++, that would
Example : read contents of file APPLY.DAT and
If the file “STORY.TXT” contains the display the details of those Students
following lines, whose A_Score is above 70.
The rose is red.
A girl is playing there. DELHI : 2004
There is a playground.
95
4.a)Assuming that a text file named more objects belonging to class
FIRST.TXT contains some text written LAUGHTER at the bottom of it.
into it, write a function named
vowelwords( ), that reads the file class LAUGHTER
FIRST.TXT and creates a new file { int Idno; // Identification number
named SECOND.TXT, to contain only char Type[5]; //LAUGHTER Type
those words from the file FIRST.TXT char Desc[255];//Description
which start with start with a lowercase public :
vowel (i.e. with ‘a’, ’e’, ’I’, ‘o’, ‘u’). For void Newentry( )
example if the file FIRST.TXT contains {
cin>>Idno;gets(Type);gets(Desc);
Carry umbrella and overcoat when }
it rains void Showonscreen( )
Then the file SECOND.TXT shall {
contain: cout<<Idno<<”:”<<Type<<endl
umbrella and overcoat it <<Desc<<endl;
}
4.b) Assuming the class Computer as };
follows:
class computer DELHI : 2002
{
char chiptype[10]; 4.a)What is the difference between
int speed; pub( ) and write( ) ?
public:
S)

void getdetails( ) 4.b) Write a C++ program, which


C

{ initializes a string variable to the


T
G
(P

get(chiptype); content “Time is a great teacher but


ar

cin>>speed; unfortunately it kills all its pupils.


m
Ku

} Berlioz” and outputs the string one


er

void showdetails( ) character at a time to the disk file


nd
re

{ cout<<”Chip”<<chiptype<”Spe OUT.TXT.You have to include all the


Vi

ed = “speed; header files if required.


}
}; DELHI : 2001

4.c)Write a function readfile( ) to read 4.a) Distinguish between ios::out and


all the records present in already ios::app.
existing binary file SHIP.DAT and
display them on the screen, also count Ans)
the number of records present in the The ios::out mode opens the file in
file. output mode only.
The ios::app mode opens the file in
DELHI : 2003 append mode, where the file can be
appended.
4.a) Write a user defined function in
C++ to read the content from a text file 4.b) Consider the class declaration
NOTES.TXT, count and display the class FLIGHT
number of blank spaces present in it. { protected:
int flight_no;
4.b)Assuming a binary file FUN.DAT is char destination[20];
containing objects belonging to a class float distance;
LAUGHTER (as defined below).Write a public:
user defined function in C++ to add void INPUT( );
//To read an object from the keyboard
96
void write_file(int); from binary file and display them on
//To write N objects into the file, screen.
//Where N is passed as argument.
void OUTPUT( );
//To display the file contents on the class FLOPPYBOX
//monitor. { int size;
}; char name[10];
Complete the member functions public:
definitions. void getdata()
{
2000: cin>>size;gets(name);
}
Q 4 (a) Name two member functions of void showdata(){cout<<size<<"
ofstream class <<name<<endl;}
};
Q 4 (b) Assuming the class DRINKS
defined below, write functions in C++ 1998:
to perform the following:
(i)Write the objects of DRINKS to a Q 4(a) Write name of two member
binary file. functions belonging to fstream class.
(ii) Read the objects of DRINKS from
binary file and display them on screen Q 4(b) Assuming the class EMPLOYEE
when DNAME has given below, write functions in C++ to
value "INDY COLA". perform the following:
(i) Write the objects of EMPLOYEE to
S)

class DRINKS a binary file.


C

{ int DCODE; (ii) Read the objects of EMPLOYEE


T
G
(P

char DNAME[13]; //Name of the drink from binary file and display them on
ar

int DSIZE,; //Size in liters the screen.


m
Ku

float DPRICE; class EMPLOYEE


er

public: { int ENO;


nd
re

void getdrinks( ) char ENAME[10];


Vi

{ public:
cin>>DCODE>>DNAME> void GETIT( )
>DSIZE>>DPRICE;
}
{
void showdrinks( ) cin>>ENO;
{ gets(ENAME);
cout<<DCODE<<DNAME<<DSIZE<< }
DPRICE<<endl; void SHOWIT( )
} { cout< < ENO<<ENAME<<endl;
char *getname( ) }
{return DNAME;} };
};
2009-10 MODEL PAPER 1:
1999:
4.a) Observe the program segment
Q 4 (a) Differentiate between functions given below carefully and fill the
read( ) and write( ). blanks marked as Statement 1 and
Statement2 using seekp( ) and seekg( )
Q 4 (b) Assuming the class functions for performing the required
FLOPPYBOX, write a function in C++ task. 1
to perform following:
(i) Write the objects of FLOPPYBOX to #include <fstream.h>
a binary file. class Item
(ii) Reads the objects of FLOPPYBOX
97
{ c) Write a function in C++ to search
int Ino; for a BookNo from a binary file
char Item[20]; "BOOK.DAT",assuming the binary file
public: is containing the objects of the
void Search(int ); following class. 3
//Function to search and display the
//content from a particular record number
class
void Modify(int);
//Function to modify the content of a
{
//particular record number int Bno;
}; char Title[20];
void Item::Search(int RecNo) public:
{ int RBno( )
fstream File; {return Bno;}
File.open("STOCK.DAT",ios::binary|ios::in); void Enter( )
________________ //Statement 1 {cin>>Bno;gets(Title);}
File.read((char*)this,sizeof(Item)); void Display( )
cout<<Ino<<"==>"<<Item<<endl; {cout<<Bno<<Title<<endl;}
File.close( ); };
}
void Item::Modify(int RecNo) Ans)
{ void BookSearch()
fstream File; {
File.open("STOCK.DAT",ios::binary|ios fstream FIL;
::in|ios::out); FIL.open("BOOK.DAT",ios::binary|ios::in);
BOOK B;
S)

cout>>Ino;cin.getline(Item,20);
C

________________ //Statement 2 int bn,Found=0;


T
G

cout<<"Enter Book No. to search…";


(P

File.write((char*)this,sizeof(Item));
ar

File.close( ); cin>>bn;
m
Ku

} while (FIL.read((char*)&S,sizeof(S)))
er

if (FIL.RBno()==bn)
nd

{
re

Ans)
Vi

Statement 1 S.Display();
File.seekg(RecNo*sizeof(Item)); Found++;
}
Statement 2 if (Found==0)
File.seekp(RecNo*sizeof(Item)); cout<<"Sorry! Book not
found!!!"<<endl;
b) Write a function in C++ to count the FIL.close( );
number of lines present in a text file }
"STORY.TXT". 2
2009-10 MODEL PAPER 2:
Ans)
void CountLine() 4.a) Observe the program segment
{ given below carefully and fill the
ifstream FIL("STORY.TXT"); blanks marked as Statement 1 and
int LINES=0; Statement 2 using seekg() and tellg()
char STR[80]; functions for performing the required
while (FIL.getline(STR,80)) task. 1
LINES++;
cout<<"No. of Lines:"<<LINES<<endl; #include <fstream.h>
f.close( ); class Employee
} {
int Eno;char Ename[20];
public:
98
//Function to count the total number of records void Display( )
int Countrec( ); { cout<<Rno<<Name<<endl;
}; }
int Item::Countrec( ) };
{ Ans)
fstream File; void Addnew( )
File.open("EMP.DAT",ios::binary|ios::in); {
__________________ //Statement 1 fstream FIL;
int Bytes =_______ //Statement 2 FIL.open("STUDENT.DAT",ios::binary|ios::app);
int Count = Bytes/sizeof(Item); STUD S;
File.close( ); char CH;
return Count; do
} {
Ans) S.Enter();
Statement 1 FIL.write((char*)&S,sizeof(S));
File.seekg(0,ios::end); cout<<"More(Y/N)?";cin>>CH;
}
Statement 2 while(CH!='Y');
File.tellg( ); FIL.close( );
}
b) Write a function in C++ to count the
number of alphabets present in a text 2008-09 MODEL PAPER 1:
file "NOTES.TXT". 2
Q4. (a) Observe the program
Ans) segment given below carefully and fill
S)
C

void CountAlphabet() the blanks marked as Statement 1


T
G

{ and Statement 2 using seekp() and


(P

ifstream FIL("NOTES.TXT");
ar

seekg() functions for performing the


m

int CALPHA=0; required task.


Ku
er

char CH=FIL.get(); 1
nd

while (!FIL.eof())
re
Vi

{ #include <fstream.h>
if (isalpha(CH)) class Item
CALPHA++; {
CH=FIL.get( ); int Ino;char Item[20];
} public:
cout<<"No. of Alphabets:"<< void Search(int );
CALPHA<<endl; //Function to search and display the content
//from a particular record number
}
void Modify(int);
//Function to modify the content of a
c) Write a function in C++ to add new //particular record number
objects at the bottom of a binary file
"STUDENT.DAT", assuming the binary };
file is containing the objects of the void Item::Search(int RecNo)
following class. 3 {
fstream File;
class STUD File.open(“STOCK.DAT”,ios::binary|ios::in);
{ _______________ //Statement 1
int Rno; File.read((char*)this,sizeof(Item));
char Name[20]; cout<<Ino<<”==>”<<Item<<endl;
public: File.close( );
void Enter( ) }
{ cin>>Rno;gets(Name); void Item::Modify(int RecNo)
} {
99
fstream File; }
File.open(“STOCK.DAT”,ios::binary|ios };
::in|ios::out);
cout>>Ino; Answer:
cin.getline(Item,20); void BookSearch()
_________________ //Statement 2 {
File.write((char*)this,sizeof(Item)); fstream FIL;
File.close( ); FIL.open(“BOOK.DAT”,ios::binary|ios::in);
} BOOK B;
Answer: int bn,Found=0;
Statement 1 cout<<”Enter Book Num to search…”;
File.seekg(RecNo*sizeof(Item)); cin>>bn;
Statement 2
while (FIL.read((char*)&S,sizeof(S)))
File.seekp(RecNo*sizeof(Item)); if (B.RBno( )==bn)
{
B.Display( );
(b) Write a function in C++ to count
Found++;
the number of lines present in a text
}
file “STORY.TXT”. 2
if (Found==0) cout<<”Sorry! Book
not found!!!”<<endl;
Answer:
FIL.close( );
void CountLine( )
}
{
ifstream FIL(“STORY.TXT”);
2008-09 MODEL PAPER 2:
int LINES=0;
S)
C

char STR[80];
4.(a) Observe the program segment
T
G

while (FIL.getline(STR,80))
(P

given below carefully and fill the


LINES++;
ar

blanks marked as Statement 1 and


m

cout<<”No. of Lines:”<<LINES<<endl;
Ku

FIL.close( ); Statement 2 using seekg() and tellg()


er

functions for performing the required


nd

}
re

task. 1
Vi

c)Write a function in C++ to search for


a BookNo from a binary file #include <fstream.h>
“BOOK.DAT”, assuming the binary file class Employee
is containing the objects of the {
following class. 3 int Eno;char Ename[20];
public:
//Function to count the total number of records
class BOOK int Countrec( );
{ };
int Bno; int Item::Countrec( )
char Title[20]; {
public: fstream File;
int RBno( ) File.open(“EMP.DAT”,ios::binary|ios::in);
{ ______________ //Statement 1
return Bno; int Bytes = _____ //Statement 2
} int Count = Bytes / sizeof(Item);
void Enter( ) File.close();
{ return Count;
cin>>Bno;gets(Title); }
} Answer:
void Display( ) File.seekg(0,ios::end);//Statement 1
{ File.tellg( ); //Statement 2
cout<<Bno<<Title<<endl;
100
(b)Write a function in C++ to count the 2009 Delhi:
number of alphabets present in a text
file “NOTES.TXT”. 2 1.(d) Find the output of the following
Answer: program: 3
void CountAlphabet()
{ #include<iostream.h>
ifstream FIL(“NOTES.TXT”); void main( )
int CALPHA=0; {
char CH=FIL.get( ); int X[ ] = {10,25,30,55,110};
while (!FIL.eof( )) int *p = X;
{ if (isalpha(CH)) while ( *p < 110)
CALPHA++; {
CH=FIL.get( ); if ( *P%3 != 0 )
} *p=*p+1;
cout<<”No. of Alphabets:”<<CALPHA <<endl; else
FIL.close( ); *p = *p + 2;
} p++;
}
c) Write a function in C++ to add new for(int I = 4; I>=l ; I--)
objects at the bottom of a binary file {
“STUDENT.DAT”, assuming the binary cout << X[I] << “*" ;
file is containing the objects of the if ( I%3 == 0)
following class. 3 cout<<endl;
S)

class STUD }
C

{ int Rno; cout<<X[0] * 3<<endl;


T
G
(P

char Name[20]; }
ar

public: Ans)
m
Ku

void Enter( ) 110*56*


er

{ cin>>Rno; 32*26*33
nd
re

gets(Name);
Vi

} 2009 Outside Delhi:


void Display( )
{ cout<<Rno<<Name<<endl; 1.(d) Find the output of the following
} program: 3
};
Answer: #include<iostream.h>
void Addnew() void main( )
{ fstream FIL; {
FIL.open(“STUDENT.DAT”,ios::binary|ios::app); int A[ ] = {10, 15, 20, 25, 30}
STUD S; int *p = A;
char CH; while (*p < 30)
do {
{ S.Enter(); if (*p%3 ! = 0)
FIL.write((char*)&S,sizeof(S)); *p = *p + 2 ;
cout<<”More(Y/N)?”; else
cin>>CH; *p = *p + 1;
} p++;
while(CH!=’Y’); }
FIL.close(); for (int J = 0; J<=4; J++)
} {
cout << A[J] << “*” ;
8.POINTERS if ( J%3 = = 0)
101
cout<<end1; }
} for(C=0;C<4;C++)
cout<<A[4] * 3<<end1; cout<<Numbers[C]<<”#”;
} cout<<endl;
}
Ans)
2006 Delhi:
12*
16*22*27* 1.d)Find the output of the following
30*90 program: 3

2007 Delhi: #include<iostream.h>


#include<string.h>
1.d)Find the output of the following class state
program: 2 {
char *state_name;
#include<iostream.h> int size;
void main( ) public:
{ state( )
int Array[ ]={4,6,10,12}; {
int *pointer=Array; size=0;
for(int I=1;I<=3;I++) state_name=new char[size+1];
{ }
cout<<*pointer<<”#”; state(char *s)
S)

pointer++; { size=strlen(s);
C

} state_name=new char[size+1];
T
G
(P

cout<<endl; strcpy(state_name,s);
ar

for(I=1;I<=4;I++) }
m
Ku

{ (*pointer)*=3; void display( )


er

--pointer; { cout<<state_name<<endl;
nd
re

} }
Vi

for(I=1;I<5;I++) void Replace(state &a, state &b)


cout<<Array[I-1]<<”@”; { size=a.size+b.size;
cout<<endl; delete state_name;
} state_name=new char[size+1];
strcpy(state_name,a.state_name);
2007 Outside Delhi: strcat(state_name,b.state_name);
}
1.d)Find the output of the following };
program: 2 void main( )
{ char *temp=”Delhi”;
#include<iostream.h> State state1(temp),state2(“Mumbai”),
void main( ) state3(“Nagpur”),S1,S2;
{ int Numbers[]={2,4,8,10}; S1.Replace(state1,state2);
int *ptr=Numbers; S2.Replace(S1,state3);
for(int C=1;C<3;C++) S1.display( );
{ cout<<*ptr<<”@”; S2.display( );
ptr++; }
}
cout<<endl; 2006 Outside Delhi:
for(C=0;C<4;C++)
{ (*ptr)*=2; 1.d) Find the output of the following
--ptr; program 3
102
object that is currently invoking a
#include<iostream.h> member function. The this pointer is
#include<string.h> implicitly passed to the member
functions of a class whenever they are
class student invoked.
{
char *name; (As soon as you define a class,
int I; the member functions are created and
public: placed in the memory space only once.
student( ) That is, only one copy of member
{ functions is maintained that is shared
I=0; by all the objects of the class. Only
name=new char[I+1]; space for data members is allocated
} separately for each object.
student(char *s)
{ When a member function is called,
I=strlen(s); it is automatically passed an
name=new char[I+1]; implicit(in built) argument that is a
strcpy(name,s); pointer to the object that invoked the
} function. This pointer is called this. If
void display( ) an object is invoking a member
{ cout<<name<<endl; function, then an implicit argument is
} passed to that member function that
void manipulate(student &a, student &b) points to (that) object. The
{
S)

programmer also can explicitly specify


C

I=a.I+b.I; ‘this’ in the program if he desires.)


T
G

delete name;
(P
ar

name=new char[I+1]; Eg: Example program to demonstrate


m
Ku

strcpy(name,a.name); the usage of this pointer.


er

strcat(name,b.name);
nd

}
re

#include<iostream.h>
Vi

}; #include<conio.h>
class Rectangle
void main( ) {
{ float area,len,bre;
char *temp=”Jack”; public:
Student name1(temp),name2(“Jill”), void input( )
name3 (“John”),S1,S2; { cout<<"\nEnter the length and
S1.manipulate(name1,name2); breadth: ";
S2.manipulate(S1,name3); cin>>this->len>>this->bre;
S1.display( ); }
S2.display( ); void calculate( )
} {
area=len*bre;
//Here Implicit 'this' pointer will be worked.
}
2006 Outside Delhi: void output( )
{
2.a) What is “this” pointer? Give an cout<<"\nThe Area of the
example to illustrate the use of it in Rectangle:"<<this->area;
C++. }
};
Ans: A special pointer known as this
pointer stores the address of the void main( )
103
{ Warning Line 8 : ‘j’ is assigned a
Rectangle R; value that is never used.
clrscr( ); Warning Line 8 : ‘ptr’ is assigned a
R.input( ); value that is never used.
R.calculate( ); Explanation:
R.output( ); (1)Error 1 is in Line no.5 ie (*ptr)++
getch(); Here ptr is a constant pointer ie the
} contents cann’t be modified.
(2)Error 2 is in Line no.7 ie ptr=&j;
2004: Here ptr is a constant pointer the
address in this pointer can’t be
1.d) What will be the output of the modified.
following program: (It is already pointing the address of i.)

#include<iostream.h> 1.d) Give the output of the following


#include<conio.h> program segment. (Assuming all
#include<ctype.h> required header files are included in
#include<string.h> the program) 2

void ChangeString(char Text[],int void main( )


&Counter) {
{ int a=32,*x=&a;
char *Ptr=Text; char ch=65,&cho=ch;
int Length=strlen(Text); cho+=a;
*x+=ch;
S)

for(;Counter<Length- 2; Counter+=2,Ptr++)
C

{ cout<<a<<’,’<<ch<<endl;
T
G

*(Ptr+Counter)=toupper(*(Ptr+Counter)); }
(P
ar

}
m
Ku

} 2.a) Distinguish between


er

int *ptr=new int(5);


nd

void main( ) int *ptr=new int[5]; 2


re
Vi

{
clrscr( ); Ans: The int *ptr=new int(5); declares
int Position=0; and creates the space for the new data
char Message[]=”Pointers Fun”; directly.
ChangeString(Message,Position); Ie The new operator reserves 2
cout<<Message<<”@”<<Position; bytes of memory from heap memory
} (free pool) and returns the address of
that memory location to a pointer
2001: variable called ptr, 5 is the initial
value to be stored in the newly
1.c) Identify the syntax error(s), if allocated memory.
any, in the following program. Also The int *ptr = new int[5];
give reason for errors. 2 initializes an array element. A
void main( ) memory space for an integer type of
{ const int i=20; array having 5 elements will be
const int* const ptr=&i; created from the heap memory (free
(*ptr)++; pool).
int j=15;
ptr=&j; 2.c) Give the output of the following
} program 4
Ans: #include<iostream.h>
Error Line 5 : Cannot modify a const object. #include<string.h>
Error Line 7 : Cannot modify a const object. class per
104
{ char name[20];
float salary; Ans)
public: void CHANGE (int A[ ], int N)
per(char *s, float a) {
{ strcpy(name,s); for(int I = 0; I<N; I++)
salary=a; {
} if (A[I]%7 = = 0)
per *GR(per &x) A [I] = A [I] /7;
{ if(x.salary>=salary) else
return &x; A[I] = A[I] * 3;
else }
return this; }
}
void display( ) (b) An array P[50] [60] is stored in the
{ cout<<”Name:“<<name<<”\n”; memory along the column with each of
cout<<”Salary:“<<salary<<”\n”; the element occupying 2 bytes, find
} out the memory location for the
}; element P[10][20], if the Base Address
void main( ) of the array is 6800. 3
{ Per P1(“REEMA”,10000), Ans)
P2(“KRISHNAN”,20000), Loc(P[I] [J]) = Base(P)+W(I+J*M)i
P3(“GEORGE”,5000); Loc(P[10][20]) = Base(P)+2(10+20*50)
per *P; Loc(P[10] [20]) = 68OO + 2(10+20*50)
P=P1.GR(P3);P->display( ); = 6800 + 2 (10+1000)
S)

P=P2.GR(P3);P->display( ); } = 6800 + 2*1010


C

= 6800 + 2020
T
G
(P

1999: = 8820
ar

1.d) Give the output of the following OR


m
Ku

program. Address of P[i] [j] = BaseAddress


er

#include<stdio.h> + W((i–L1)+(j–L2)*M)
nd
re

void main( ) Address of P[10] [20]= 6800 +


Vi

{ char *p=”Difficult”; 2((10-0)+(20-0)x50)


char c; = 6800 + 2 x 1010
c=*p++; = 6800 + 2020
printf(“%c”,c); = 8820
} OR
9.ARRAYS Address of P[I] [J] along the column
= BaseAddress + W((I–LBR)+(J–
DELHI 2010: LBC)*M)
(where N is the number of rows, LBR = LBC = 1)
3.(a) Write a function CHANGEO in C+ Address of P[10][20]
+, which accepts an array of integer =6800+2((10-1)+(20-l)x50)
and its size as parameters and divide = 6800 + 2 ( 9 + 19 x 50 )
all those array elements by 7 which = 6800 + 2 x 959
are divisible by 7 and multiply other- = 6800 + 1918
array elements by 3. 3 = 8718
Sample Input Data of the array
(d) Write a function int SKIPSUM(int
A[ ] [3], int N,int M) in C++ to find and
Content of the array after Calling return the sum of elements from all
CHANGE( ) function alternate elements of a two-
dimensional array starting from A[0]
[0]. 2

105
Hint: int S=0, C=0;
If the following is the content of the for(int I = 0; 1< N; 1++)
array for (int J = 0; J<M; J++ )
{
if (C%2 == 0)
S = S + A[I][J];
C++;
}
return S;
}
OR

int SKIPSUM(int A[][3], int N, int M)


{
The function SKIPSUM() should add
int S=0, C=l;
elements A[0][0], A[0][2], A[1][l],
for(int I = 0; I<N; I++)
A[2][0] and A[2][2].
for (int J = 0; J<M; J++ )
{
Ans)
if (C%2 != 0)
int SKIPSUM(int A[ ][ 3 ], int N,int M)
S = S + A[I][J];
{ int S=0:
C++;
for(int I = 0; 1< N; 1++)
}
for (int J = (I%2)?1:0; J<M; J = J+2)
return S;
S = S + A [I][J];
}
return S;
S)

OR
}
C
T

OR
G
(P

int SKIPSUM (int A[ ][3], int N, int M)


int SKIPSlJM(int A[ ][3], int N, int M)
ar

{
m

{ int S=0;
Ku

int S=0;
for (int I = 0; 1< N; I++)
er

for(int I = 0; l< N; l++)


nd

for (int J = (I%2==0)? 0:1 ; J<M; J = J+2)


re

S = S + A [I][J]; for (int J = 0; J<M; J++ )


Vi

return S; {
} if ((I+J)%2 == 0)
OR S = S + A[I][J];
}
int SKIPSUM(int A[][3], int N, int M) return S;
{ }
int I,J, S=O;
for (I = 0; 1 < N; 1++)
{ OUTSIDE DELHI 2010:
if (I%2)
//OR (1%2 !=0 ) OR (I%2 == 1) 3. (a) Write a function REASSIGNO in
J = l; C++, which accepts an array of
else integers and its size as parameters
J = 0; and divide all those array elements by
for ( ; J<M; J = J+2) 5 which are divisible by 5 and multiply
S = S + A[I][J]; other array elements by 2. 3
}
return S;
}
OR
int SKIPSUM(int A[][3], int N, int M)
{
106
Address of T[10][40] = BaseAddress +
4[ (10 - 1) +(40 - l)x 90]
= 7200+4[9 + 39 x 90]
= 7200+4[9 + 3510]
= 7200+4 x 3519
= 7200+14076
Content of the array after calling = 21276
REASSIGNO function
(d) Write a function int ALTERSUM
(int B[ ] [5], int N, int M in C++ to find
and return the sum of elements from
all alternate elements of a two-
dimensional array starting from B[0]
[0]. 2
Ans)
Hint: If the following is the content
void REASSIGN (int Arr[ ], int Size) of the array:
{
for (int i=0;i<Size;i++)
if (Arr[i]%5==0)
Arr[i]/=5;
else
Arr[i]*=2;
}
OR
S)
C

void REASSIGN(int Arr[ ],int Size)


T
G

{
(P

The function should add elements B[0]


ar

for (int i=0;i<Size;i++)


m

[0], B[0][2], B[l][l], B[2][0] and B[2][2].


Ku

Arr[i]%5 ? Arr[i]/=5 :
er

Arr[i] *= 2;
nd

} Ans.
re
Vi

(b) An array T[90][100] is stored in the


memory along the column with each of
the elements occupying 4 bytes. Find int ALTERSUM(int B[ ][5] ,int N,int M)
out the memory location for the {
element T[10][40], if the Base Address int Sum=0;
of the array is 7200. 3 for (int I=0;I<N;I++)
for (int J=(I%2==0)?0:1;J<M;J+=2)
Ans. Sum+=B[I][J] ;
return Sum;
Loc(T[I][J)) = Base(T)+W(I+J*N) }
(where N is the number of rows, LBR = LBC = 0) OR
= 7200 + 4[10 + 40 x 90] int ALTERSUM(int B[ ][5],int N,int M)
= 7200 + 4[10+3600] {
= 7200 + 4 x 3610 int Sum=0,J=0;
= 7200 + 14440 for (int I=0;I<N;I++)
= 21640 {
OR for (;J<M;J+=2)
Sum+=B[I][J] ;
Address of T[I][J] along the column J-=M;
= BaseAddress + W [(I-LBR)+(J-LBC)* N] }
(where N is the number of rows, LBR=LBC = 1) return Sum;
}
107
OR
int ALTERSUM(int B[ ][5],int N,int M) Note: Assume the following definition
{ of structure Game
int *P=&B[0][0],Sum=0;
for (int I=0;I<M*N;I+=2) struct Game
{ {
Sum+=(*P); long PNo; //Player Number
P+=2; char PName [20] ;
} long Points;
return Sum; };
}
OR
int ALTERSUM (int B[ ][5], int N, int
M)
{ int S=0, C=0;
for(int I = 0; 1< N; 1++)
for (int J = 0; J<M; J++ )
{
if (C%2 == 0)
S = S + B[I][J];
C++;
}
return S;
}
S)

OR
C

int ALTERSUM(int B[ ][5],int N,int M)


T
G
(P

{ int Sum=0;
ar

for (int I=0;1<N;1++)


m
Ku

for (int J=0;J<M;J++)


er

if ((I+J)%2==0)
nd
re

Sum+=B [I][J] ;
Vi

return Sum;
} Ans)
OR void SORTPOINTS(Game G[], int N)
int ALTERSUM(int B[ ][5],int N,int M) {
{ Game Temp;
int Sum=0; for (int I = 0; I<N-l; I++)
for (int I=0;1<N;1++) for (int J = 0; J<N-I-l; J++)
for (int J=0;J<M;J++) if(G[J].Points < G[J+l].Points)
{ {
if ((I%2==0 && J%2=0)||(1%2!=0 Temp = G[J];
&& J%2!=0)) G[J] = G[J+l];
Sum+=B [I][J] ; G[J+l] = Temp;
} }
return Sum; }
}
(b) An array S[40][30] is stored in the
DELHI 2009: memory along the column with each of
the element occupying 4 bytes, find
3. (a) Write a function SORTPOINTS( ) out the base address and address of
in C++ to sort an array of structure element S[20][15], if an element S[15]
Game in descending order of Points [10] is stored at the memory location
using Bubble Sort. 3 7200. 4
108 BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
Ans)
Loc(S[I][J]) = Base(S)+W(I+J*N)
Loc(S[15][10]) =
Base(S)+4(15+10*40)
Base(S) = 7200-4*415
Base(S) = 7200-1660
Base(S) = 5540
Loc(S[20][15]) =
Base(S)+4(20+15*40)
Loc(S[20][15])
= 5540 + 4(20+15*40)
= 5540 + 4(20+600)
= 5540 + 4*620
= 5540 + 2480
= 8020
OR Ans)

Address of S[i][j]=BaseAddress + void SWAPCOL(int A[][100], int M, int N)


W[(i-L1) + ( j - L2) *M] {
Address of S[15] [10] = int Temp, I;
BaseAddress+ 4[(15–0)+(10 - 0)*40] for(I=O; I<M; I++)
7200= Base Address + 4 [415] {
Base Address = 7200 - 4 * 415 Temp = A [I][0] ;
S)

= 7200 - 1660 A[I][0] = A[I][N-l];


C

= 5540
T

A[I][N-l] = Temp;
G
(P

Address of S[20][15] }
ar

= 5540 + 4 [(20 - 0) + (15 - 0) x 40] }


m
Ku

= 5540 + 4 x 620 OR
er

= 5540 + 2480 void SWAPCOL(int A[4][4])


nd
re

= 8020 {
Vi

OR int Temp, I;
for(I=O; I<4; I++)
Address of Sri] [j] along the column = {
Base Address + W [( i - L1) + (j - L2) * M] Temp = A[I][0];
Address of S[15)[10] = A[I][0] = A[I][3];
BaseAddress + 4[(15 - 1)+(10-1) x 40] A[I][3] = Temp;
7200= Base Address + 4 [374] }
Base Address = 7200 - 4 x 374 }
= 7200 - 1496
= 5704 OUTSIDE DELHI 2009:
Address of 5[20)[15]
= 5704 + 4 [(20 - 1) + (15 - 1) x 40] 3. (a) Write a function SORTSCORE( )
= 5704 + 4 x 579 in C++ to sort an array of structure
= 5704 + 2316 Examinee in descending order of Score
= 8020 using Bubble Sort. 3

(d) Define a function SWAPCOL ( ) in Note: Assume the following definition


C++ to swap (interchange) the first of structure Examinee
column elements with the last column
elements, for a two dimensional struct Examinee
integer array passed as the argument {
of the function. 3 long RollNo;
109 BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
char Name[20] ; Loc(T[25][10]) = Base(T)+4(25+10*50)
float Score; Base(T) = 9800-4*525
}; Base(T) = 9800-2100
Base(T) = 7700
Loc(T[30][15]) =
Base(T)+4(30+15*50)
Loc(T[30][15])
= 7700 + 4(30+15*50)
= 7700 + 4(30+750)
= 7700 + 4*780
= 7700 + 3120
= 10820
OR

Address of T[i][j]
=BaseAddress + W [(i - L1) + (j - L2) * M]
Address of T[25] [10] =
BaseAddress + 4[(25 - 0)+(10 - 0)*50]
9800 = Base Address + 4 [525]
Base Address = 9800 - 4 * 525
= 9800 - 21.00
= 7700
Address of T[30][15]
=7700 + 4 [(30 - 0) + (15 - 0) x 50]
S)

= 7700 + 4 x 780
C

= 7700 + 3120
T
G
(P

= 10820
ar

OR
m
Ku

Ans)
er

Address of T[i][j] along the column


nd
re

=Base Address+ W[( i - L1)+(j - L2)* M]


Vi

void SORTSOORE (Examinee E[ ], int N)


Address of T[25][10]
{
=BaseAddress + 4[(25 - 1) +(10 -1)x50]
Examinee Temp;
9800= Base Address + 4 [474]
for (int I = 0; I<N-l; I++)
Base Address
for (int J = 0; J<N-I-l; J++)
= 9800 - 4 x 474
if(E[J].Score < E[J+l].Score)
= 9800 - 1896
{
= 7904
Temp = E[J];
Address of T[30][15]
E[J] = E[J+l];
= 7904 + 4 [(30 - 1) + (15 - 1) x 50]
E[J+l] = Temp;
= 7904 + 4 x 729
}
= 7904 + 2916
}
= 10820
(b) An array T[50][20] is stored in the
(d) Define a function SWAPARR( ) in
memory along the column with each of
C++ to swap (interchange) the first row
the elements occupying 4 bytes. Find
elements with the last row elements,
out the base address and address of
for a two dimensional integer array
element T[30][15], if an element T[25]
passed as the argument of the
[10] is stored at the memory location
function. 3
9800. 4

Ans)
Loc(T[I][J]) = Base(T)+W(I+J*N)
110
Then the function should rearrange
the array as
10,12, 8, 7, 6, 1, 5, 2, 4

Solution:
void receive(int A[ ], int size)
{
int temp;
for(i=0,j=size-1;i<size/2;i++,j--)
{
temp=A[i];
A[i]=A[j];
A[j]=temp;
}
} //end of receive function.

3.b) An array Arr[40][10] is store in


Ans) the memory along the column with
void SWAPARR(int A[][100], int M, int N) each element occupying 4 bytes. Find
{ out the base address of the location
int Temp, Ji Arr[3][6] if the location Arr[30][10] is
for (J=0; J<N; J++) stored at the address 9000.
{
Temp = A[0)[J] ; Solution:
A[0][J] = A[M-1][J];
S)
C

A[M-l][J] = Temp; Address of Array[i][j] along the column


T
G

} =Base Address + W [( i - L1) + (j - L2) * M]


(P
ar

}
m

OR where,
Ku
er

void SWAPARR(int A[4][4]) W = size of each location in bytes = 4


nd

{ L1 = Lower Bound of rows = 0


re
Vi

int Temp, J; L2 = Lower Bound of columns = 0


for (J=0; J<4; J++) M = Number of rows per column = 40
{
Temp = A[0][J]; Address of Array[30][10]
A[0][J] = A[3][J]; = Base Address + 4 * (30 + 10 * 40)
A[3][J] = Temp; 9000 = Base Address + 4 * 430
}
} Base Address = 9000 - 4 x 430
= 9000 -1720
DELHI 2008: = 7280

3.a) Write a function in C++, which Address of Array[3][6]


accepts an integer array and its size = 7280 + 4 * (3 + 6 * 40)
as parameters and rearranges the = 7280 + 4 * 243
array in reverse. = 7280 + 972
= 8252
Example: OR

If an array of nine elements initially Address of Array[i][j] along the column


contains the elements as 4, 2, = Base Address + W (( i - L1) + (j - L2) * M)
5, 1, 6, 7, 8, 12, 10
where,
W = size of each location in bytes = 4
111
L1 = Lower Bound of rows = 1 Then the output should appear as:
L2 = Lower Bound of columns = 1 Product of Column 1 = 24
M = Number of rows per column = 40 Product of Column 2 = 30
Product of Column 3 =240
Address of Array[30][10] void receive(int A[ ][ ],int r,int c)
= Base Address + 4 * ((30 -1) +(10 -1) * 40) { int i,j,B[c];
9000 = Base Address + 4 * (29+9*40) for(i=0;i<c;i++)
9000 = Base Address + 4 * (29+360) B[i]=1;
9000 = Base Address + 4 * (389) for(i=0;i<r;i++)
for(j=0;j<c;j++)
Base Address B[j]=B[j]*A[i][j];
= 9000 - 4 * 389 for(i=0;i<c;i++)
= 9000 -1556 cout<<”\nProduct of Column
= 7444 “<<i+1<<” = “<<B[i];
}
Address of Array[3][6] OR
= 7444 + 4 * ((3 -1) + (6 -1) * 40) void ProdCol(int Arr[][100], int Row, int Col)
= 7444 + 4 * (2+5 * 40) {
= 7444 + 4 * (2+200), int i, j, Prod;
= 7444 + 4 * 202 for (j = 0; j < Col; j++)
= 7444 + 808 {
= 8252 Prod=1;
OR for (i = 0; i < Row; i++)
Prod * = Arr[i][j];
Address of Array[i][j] along the column cout<<“Product of Column”
S)
C

=Address of Array[x][y] + W [( i-x) + (j - y) * M] <<j<< “=” <<Prod<<endl;


T
G

}
(P
ar

where, }
m
Ku

OUTSIDE DELHI 2008:


er

W = size of each location in bytes = 4


nd

M = Number of rows per column = 40 3.a)Write a function in C++, which


re
Vi

i , j = Index value of the unknown element accepts an integer array and its size
x , y = Index value of the known element as arguments and swap the elements
of every even location with its
Address of Array[3][6] following odd location.
= Address of Array[30][10]+ 4 [(3 - 30)
+(6 -10) * 40] Example :
= 9000 + 4 [-27 -160] If an array of nine elements initially
= 9000 - 4 x 187 contains the elements as
= 9000 -748 2,4,1,6,5,7,9,23,10
= 8252 then the function should rearrange
the array as
3.d)Write a function in C++ to print 4,2,6,1,7,5,23,9,10
the product of each column of a two
dimensional array passed as the void SwapArray(int A[ ], int N)
arguments of the function. {
Example : If the two dimensional int i,j,temp;
array contains
/* cout<<”\nThe elements before doing the desired
alterations…”;
for(i=0;i<N;i++)
cout<<A[i]<<’\t’; */

for(i=0;i<N-1;i+=2)
{
112
temp=A[i]; = 8152+3898
A[i]=A[i+1]; =12050
A[i+1]=temp;
} 3.d)Write a function in C++ to print
the product of each row of a two
/* cout<<”\nThe elements after completed the dimensional array passed as the
desired alterations…”;
for(i=0;i<N;i++) arguments of the function
cout<<A[i]<<’\t’; */
Example: if the two imensional array
} contains

3.b) An array Arr[50][10] is store in


the memory along the row with each
element occupying 2 bytes. Find out
the Base address of the location
Arr[20][50], if the location Arr[10][25]
is stored at the address 10000. Then the output should appear as:
Product of Row 1 = 8000
Ans) Product of Row 2 = 6000
Product of Row 3 =3600
Assuming LBR=LBC=0 Product of Row 4 = 2400
S=2 bytes
Number of Rows (N)=50 void receive(int A[ ][ ],int r,int c)
Number of Columns (M)=100 { int i,j,B[r];
S)

for(i=0;i<r;i++)
C

LOC (Arr [I] [J]) = B + (I*M+J)*S B[i]=1;


T
G

LOC (Arr [10] [25]) = B +(10*100+25)*2


(P

for(i=0;i<r;i++)
ar

10000 = B +(1000+25)*2 for(j=0;j<c;j++)


m

B = 10000-2050
Ku

B[i]=B[i]*A[i][j];
er

B = 7950 for(i=0;i<r;i++)
nd
re

cout<<”\nProduct of Row “<<i+1<<


Vi

LOC (Arr [20] [50]) ” = “<<B[i];


= 7950+(20*100+50)*2 }
= 7950 + (2050*2)
= 7950+4100 DELHI 2007:
= 12050
OR 3.a)Write function in C++ which
accepts an integer array and size as
Assuming LBR=LBC=1 arguments and replaces elements
S=2 bytes having odd values with thrice its value
Number of Rows (N) = 50 and elements having even values with
Number of Columns (M) =100 twice its value.

LOC (Arr [I] [J]) Example : if an array of five elements


=B +((I-LBR)*M+(J-LBC))*S initially contains elements as
LOC (Arr [10] [25]) 3, 4, 5, 16, 9
=B +((10–1)*100+(25–1))*2
10000 = B +(900+24)*2 The the function should rearrange the
B = 10000-1848 content of the array as
B = 8152 9, 8, 75, 32, 27

LOC (Arr [20] [50]) Solution:


= 8152+ ((20-1)*100+ (50-1))*2 void manipulate (int a[ ],int size)
= 8152 + (1949*2)
113
{ 1 2 9
for (i=0;i<size;i++)
{ Out put through the function should be :
if (a[i]%2= =1) Diagonal One : 5 7 9
a[i]=a[i]*3; Diagonal Two : 3 7 1
else
a[i]=a[i]*2; Solution:
cout<<a[i]<<’,’;
} void accept(int a[ ][ ],int size)
} {
int i,j;
3.b)An array Array[20][15] is stored in cout<<"Diagonal One:";
the memory along the column with for (int i=0;i<size;i++)
each element occupying 8 bytes. Find for(int j=0;j<size;j++)
out the base address of the element if (i= = j)
Array[2][3] if the element Array[4][5] is cout<<a[i][j]<<’\t’;
stored at the address 1000. cout<<"\n Diagonal Two:";
for (i=0;i<size;i++)
Solution: for(j=0;j<size;j++)
if((i+j)= =(size-1))
Given Data: Aray [20][15] W=8 cout<<a[i][j]<<’\t’;
B=? R=20 C=15 Lr = 0 Lc = 0 }
Address of Array [2][3] =?
Address of Array[4][5] =1000. OUTSIDE DELHI 2007:
S)

Address of an element (I,J) in


C

column major 3.a)Write a function in C++ which


T
G

accepts an integer array and its size


(P

=B + W ( (I-Lr) + R(J-Lc ) )
ar

Therefore as arguments and replaces elements


m
Ku

1000=B+8*((4-0)+20(5-0)) having even values with its half and


er

1000=B+8*(4+20*5) elements having odd values with twice


nd
re

1000 =B+8*104 its value .


Vi

1000=B+832
B =1000-832 Example : If an array of five elements
B =168 initially contains the elements
as 3, 4, 5, 16, 9
Therefore Address of then the function should rearrange
Array[2][3]=168+8*((2-0)+20(3-0)) content of the array as
=168+8*(2+20*3) 6, 2, 10, 8, 18
=168+8*62
=168+496 Solution:
=664
void accept(int a[ ],int size)
3.d)Write a function in C++ which {
accepts a 2D array of integers and its for (int i=0;i<size;i++)
size as arguments and displays the {
elements which lie on diagonals. if (a[i]%2= =0)
[Assuming the 2D Array to be a square a[i]=a[i]/2;
matrix with odd dimension i.e., 3x3, else
5x5 ,7x7 etc…] a[i]=a[i]*2;
cout<<a[i]<<’,’;
Example : if the array content is }
5 4 3 }
6 7 8
114
3.b)An array Arr[15][20] is stored in for(int j=0;j<size;j++)
the memory along the row with each if (i= = size/2)
element occupying 4 bytes. Find out cout<<a[i][j]<<’\t’;
the Base address of the location Arr[3] cout<<"\n Middle Column:";
[2], if the location Arr[5][2] is stored at for (i=0;i<size;i++)
the address 1500. for(j=0;j<size;j++)
if(j= =size/2)
Solution: cout<<a[i][j]<<’\t’;
Given Data: Arr[15][20] W=4 }
B=? R=15 C=20 Lr = 0 Lc = 0
Address of Arr[3][2] = ? DELHI 2006:
Address of Arr[5][2] = 1500.
3.a)Write function in C++ which
Address of an element (I,J) in row accepts an integer array and size as
major = B+W(C(I-Lr)+(J-Lc )) arguments and assign values into a
Therefore, 2D array of integers in the following
1500 = B+4(20(5-0)+(2-0)) format :
1500 = B+4(20*5+2)
1500 = B+4*102 If the array is 1, 2, 3, 4, 5, 6
1500 = B+408
B =1500-408
B=1092 The resultant 2D array is given below
Address of Arr[3][2]
=1092+4(20*3+2) 1 2 3 4 5 6
S)

=1092+4(62) 1 2 3 4 5 0
C

=1092+248 1 2 3 4 0 0
T
G
(P

=1340. 1 2 3 0 0 0
ar

1 2 0 0 0 0
m
Ku

3.d)Write a function in C++ which 1 0 0 0 0 0


er

accepts a 2D array of integers and its


nd
re

size as arguments and displays the If the array is 1, 2, 3


Vi

elements of middle row and the


elements of middle column. [Assuming The resultant 2D array is given :
the 2D Array to be a square matrix
with odd dimension 1 2 3
i.e., 3x3, 5x5, 7x7 etc…] 1 2 0
1 0 0
Example : If the array content is
3 5 4 Solution:
7 6 9
2 1 8 void input (int a[ ],int size)
{ int b[size] [size];
Output through the function should be : for (int i=0;i.<size;i++)
Middle Row :7 6 9 {
Middle Column : 5 6 1 for (int j=0;j<size;j++)
{
Solution: if(( i+j)>=size)
b[i][j]=0;
void accept(int a[ ][ ],int size) else
{ b[i][j]=a[j];
int i,j; cout<<b[i][j]<<’\t’;
cout<<"Middle Row:"; }
for (int i=0;i<size;i++) cout<<endl;
115
} Thus, Address of MAT[20][5]
} = -472 + 8 ( 4 × 30 + 19)
= -472 + 8 × 139
3.b) An array MAT[30][10] is stored in = -472 + 1112
the memory along column wise with = 640
each element occupying 8 bytes of the
memory. Find out the Base address
and the address of element MAT[20][5] OUTSIDE DELHI 2006:
, if the location MAT[3][7] is stored at
the address 1000. 3.a)Write function in C++ which
accepts an integer array and size as
Ans) arguments and assign values into a
2D array of integers in the following
For Column wise allocation format :
Address of A[I][J]
= BA + W[ (J –LBC) x M + (I - LBR)] If the array is 1, 2, 3, 4, 5, 6
Where
BA = Base Address The resultant 2D array is given below :
W = Size of each element in bytes
= 8 bytes (given) 1 0 0 0 0 0
M = No. of rows in the 2D Array = 30 1 2 0 0 0 0
(given) 1 2 3 0 0 0
Address of MAT[5][7] given is 1000. 1 2 3 4 0 0
1 2 3 4 5 0
S)

Assumption 1 : LBR=LBC=0 1 2 3 4 5 6
C
T
G
(P

Therefore If the array is 1, 2, 3


ar

1000 = BA + 8 (7 × 30 + 5)
m
Ku

= BA + 8 × 215 The resultant 2D array is given:


er

= BA + 1720
nd
re

BA = 1000 – 1720 1 0 0
Vi

= -720 1 2 0
1 2 3
Therefore,Base Address = - 720
Solution:
Thus, Address of MAT[20][5] = -720 +
8 ( 5 × 30 + 20) void input (int a[ ],int size)
= -720 + 8 × 170 {
= -720 + 1360 int b[size] [size];
= 640 for (int i=0;i.<size;i++)
{
Assumption 2 : LBR=LBC=1 for (int j=0;j<size;j++)
{
Therefore if(( i<j)
1000 = BA + 8 [(7-1) × 30 +(5-1)] b[i][j]=0;
= BA + 8[6 × 30 + 4] else
= BA + 8 ×184 b[i][j]=a[j];
= BA + 1472 cout<<b[i][j]<<’\t’;
BA = 1000 – 1472 }
= -472 cout<<endl;
}
Therefore,Base Address = - 472 }
OR
116
Therefore,Base Address = 896
const int R = 100, C = 100; Thus, Address of MAT[10][5]
void Arrayconvert(int A1D[ ], int N) = 896 + 4 ( 10 (10-1) + (5-1))
{ = 896+376
int A2D[R][C]={0}; = 1272
for(int I = 0; I<N; I++)
for (int J = 0; J <=I; J++)
A2D[I][J] = A1D[J]; DELHI 2005:
}
3.a)Write a function in C++ which
3.b)An array MAT[20][10] is stored in accepts an integer array and its size
the memory along the row with each as arguments and exchanges the
element occupying 4 bytes of the values of first half side elements with
memory. Find out the Base address the second half side elements of the
and the address of element MAT[10][5] array.
, if the location MAT[3][7] is stored at Example :
the address 1000.
If an array of 8 elements initial content as
Ans) 2, 4, 1, 6, 7, 9, 23, 10

For Row wise allocation The function should rearrange array as


Address of A[I][J] 7, 9, 23, 10, 2, 4, 1, 6
= BA + W( (I-LBR) x N + (J-LBC))
Solution:
S)

Where
C

BA = Base Address void change(int a[ ],int size)


T
G

{
(P

W = Size of each element in bytes


ar

= 4 bytes (given) int i,j,temp;


m

for(i=0,j=size/2;j<size;i++,j++)
Ku

N = No. of columns in the 2D Array


er

= 10 (given) {
nd

temp=a[i];
re

Address of MAT[3][7] given is 1000.


Vi

a[i]=a[j];
Therefore a[j]=temp;
}
(Assumption 1: LBR = LBC = 0) }
OR
MAT[3][7]=100 = BA + 4 (10 (3-0) + (7-0))
= BA + 148 void Exchange (int A [ ], int N)
BA = 1000 – 148 = 852 {
for (int I=0;I<N/2;I++)
Therefore,Base Address = 852 {
Thus, Address of MAT[10][5] = 852 + 4 int Temp=A[I];
( 10 (10-0) + (5-0)) A[I]=A[N/2+I];
= 852+420 A[N/2+I]=Temp;
= 1272 }
OR }
OR
(Assumption 2: LBR = LBC = 1)
void Exchange(int A[], int N)
MAT[3][7]=1000 = BA + 4 (10 (3-1) + (7-1)) {
= BA + 104 int M=(N%2==0)?N:N+l;
BA = 1000 – 104 for (int I=0; I<M/2; I++)
= 896 {
int Temp=A[I];
117
A[I]=A[M/2+I]; Solution:
A[M/2+I]-Temp; void Sum(int A[ ][ ],int R,int C)
} {
} int i,j,S=0;
for(i=0;i<R;i++)
3.b)An array Arr[15][35] is stored in for(j=0;j<C;j++)
the memory along the row with each of if(A[i][j]%2= = 0 ||A[i][j]%3= = 0)
its element occupying 4 bytes . Find S=S+A[i][j];
out the Base address and the address cout<<”\nThe Sum of all the values
of element Arr[2][5] , if the location which are divisible by 2 or 3 in
Arr[5][10] is stored at the address the array = “<<S;
4000. }
OUTSIDE DEHI 2005:

Ans) 3.a)Write a function in C++ which


accepts an integer array and its size
LOC(Arr[I][J] ) as arguments and exchanges the
=Base(Arr)+W*(I + No.of Rows * J ) values of first half side elements with
LOC(Arr[5][10]) the second half side elements of the
=Base(Arr)+8*(5+15*10) array.
4000 =Base(Arr)+8*(155)
4000 =Base(Arr)+1240 Example :
Base(Arr) =4000-1240
Base(Arr) =2760 If an array of 8 elements initial content as
S)

8, 10, 1, 3, 17, 90, 13, 60


C

LOC(Arr[2][5]) =Base(Arr)+8* (2 + 15*5)


T
G

=2760+8*(77) The function should rearrange array as


(P
ar

=2760+616 17, 90, 13, 60, 8, 10, 1, 3


m
Ku

=3376
er

Ans)
nd

OR
re
Vi

void Exchange(int A[],int N)


LOC(Arr[I][J]) {
=Base(Arr)+W*( (I-1) + No. of Rows * (J-l) ) for (int I=0;I<N/2;I++)
LOC(Arr[5][10]) {
=Base(Arr)+8*[(5-1)+15* (10-1)] int Temp=A[I];
4000 =Base(Arr)+8*(139) A[I]=A[N/2+I];
4000 =Base(Arr)+1112 A[N/2+I]=Temp;
Base(Arr) =4000-1112 }
Base(Arr) =2888 }
OR
LOC(Arr[2][5])
=Base(Arr)+ 8*[(2-1)+15*(5-1)] void Exchange(int A[],int N)
=2888+8*(61) {
=2888+488 for (int I=0,J=N/2;I<N/2;I++,J++)
=3376 {
int Temp=A[J];
for (int K=J;K>I;K--)
3.d)Write a function in C++ to print A[K]=A[K-1];
sum of all values which either are A[I]=Temp;
divisible by 2 or divisible by 3 present }
in a 2D array passed as the argument }
of the function. OR

118
void Exchange(int A[],int N) divisible by 3 or divisible by 5 present
{ in a 2D array passed as the argument
int M=(N%2=0)?N:N+l; of the function.
for (int I=0;I<M/2;I++)
{ Ans)
int Temp=A[I]; void Sum(int A[ ][ ],int R,int C)
A[I]=A[M/2+I]; { int S=0,i,j;
A[M/2+I]=Temp; for(i=0;i<R;i++)
} for(j=0;j<C;j++)
} if((a[i][j]%3= =0)||(a[i][j]%5= =0))
S=S+A[i][j];
3.b)An array Arr[35][15] is stored in cout<<" nThe Sum of all the values
the memory along the row with each of which are divisible by 3 or 5 in
its element occupying 4 bytes . Find the array = “<<S;
out the Base address and the address }
of element Arr[20][5] , if the location
Arr[2][2] is stored at the address 3000. DELHI 2004:

Ans) 3.a) Define the function


SwapArray(int[ ], int),that would
LOC(Arr[I][J]) expect a 1D integer array NUMBERS
Base(Arr)+W*(No. of Cols*I+J) and its size N. the function should
LOC(Arr[2][2]) =Base(Arr)+4*(15*2+2) rearrange the array in such a way that
3000 =Base(Arr)+4*(32) the values of that locations of the
3000 =Base(Arr)+128
S)

array are exchanged.


C

Base(Arr) =3000-128 (Assume the size of the array to be even).


T
G

Base(Arr) =2872
(P
ar

Example :
m
Ku

LOC(Arr[20][5])
er

=Base(Arr)+4*(15*20+5) If the array initially contains


nd

=2872+4*(300+5)
re

{2, 5, 9, 14, 17, 8, 19, 16}


Vi

=2872+4*305 Then after rearrangement the array


=2872+1220 should contain
=4092 {5, 2, 14, 9, 8, 17, 16, 19}

OR Solution:

LOC(Arr[I][J]) void SwapArray(int NUMBERS[ ], int N)


=Base(Arr)+W*(No. of Cols*(I-1)+(J-1) {
LOC(Arr[2][2]) int i,j,temp;
=Base(Arr)+4*(15*(2-1)+(2-1)) /* cout<<”\nThe elements before doing the desired
alterations…”;
3000 =Base(Arr)+4*(16) for(i=0;i<N;i++)
3000 =Base(Arr)+64 cout<<NUMBERS[i]<<’\t’; */
Base(Arr) =3000-64 for(i=0;i<N-1;i+=2)
Base(Arr) =2936 {
temp=NUMBERS[i];
LOC(Arr[20][5]) NUMBERS[i]=NUMBERS[i+1];
=Base(Arr)+4*(15*(20-1)+(5-1)) NUMBERS[i+1]=temp;
=2936+4*(289) }
=2936+1156 /* cout<<”\nThe elements after completed the
desired alterations…”;
=4092 for(i=0;i<N;i++)
cout<<NUMBERS[i]<<’\t’; */
3.d) Write a function in C++ to print }
sum of all values which either are
119
3.b) An array ARR[5][5] is stored in the Etemp=E[j];
memory with each element occupying E[j]=E[j+1];
3 bytes of space. Assuming the base E[j+1]=temp;
address of ARR to be 1500, compute }
the address of ARR[2][4], when the cout<<"The details of the employee
array is stored : in ascending order of salary ";
Solution: Children, Try this answer as for(i=0;i<n;i++)
an assignment. cout<<E[i].Eno<<'\t'<<E[i].name
3.c) Write a function in C++ to find the <<’\t<<E[i].Salary<<endl;
sum of diagonal elements from a 2D }
array of type float. Use the array and
its size as parameters with float as its 3.b)An array X[30][10] is stored in the
return type. memory with each element requiring 4
bytes storage. Find out the Base
Solution: address of X is 4500, find out memory
float diasum(float A[ ][ ],int R,int C) locations of X[12][8] and X[2][14], if
{ the content is stored along the row.
int i,j;
float Dsum=0.0; Solution: Children, Try this answer as
for(i=0;i<R;i++) an assignment.
for(j=0;j<C;j++)
if((i= = j)| | (i+j)= =(size-1)) 3.c)Write a user-defined function in
Dsum=Dsum+A[i][j]; C++ to display those elements of 2D
return Dsum; array T[4][4] which are divisible by
S)

} 100. Assume the content of the array


C

is already present and the function


T
G
(P

DELHI 2003: prototype is as follows: void


ar

showhundred( int T[4][4]);


m
Ku

3.a)Assume a array E containing


er

elements of structure Employee is void showhundred(int T[4][4])


nd
re

required to be arranged in descending {


Vi

order of Salary. Write a C++ function int i,j;


to arrange same with the help of cout<<”\nThe elements in the array
bubble sort, the array and its size is which are divisible by 100 …..”;
required to be passed as parameters for(i=0;i<4;i++)
to the function. Definition of for(j=0;j<4;j++)
structrure Employee is as follows: if(T[i][j]%100= =0)
cout<<T[i][j]<<’\t’;
Struct Employee }
{ int Eno;
char name[25]; DELHI 2002:
float Salary;
}; 3.a) Define array and pointer.

Solution: Solution: An array refer to a named


void bubble(Employee E[ ],int n) list of a finite number n of similar data
{ elements. Each of the data elements
int i,j; can be referenced respectively by a set
Employee Etemp; of consecutive numbers.
for(i=0;i<n;++i) Arrays can be one dimensional, two
for(j=0;j<(n-1)-i ;j++) dimensional or multi dimensional.
if(E[j].salary<E[j+1].salary) An array can be declared as :
{ Syntax: data_type Array_name[size];
120
Eg: int A[10]; //Then location of
//the array are A[0], A[1],…….A[9]. (i)
All odd numbers of X from
int B[5][4]; left to right are copied into
//This array can holds 5 X 4 = 20 elements. Z from left to right.
(ii) All even numbers of X
from left to right are
3.d) The array A[20][10] is stored in copied into Z from right to
the memory with each element left.
requiring one byte of storage if the (iii) All odd numbers of Y from
base address of a is 0, determine the left to right are copied into
location of A[10][5] when the array A is Z from left to right.
stored by column major. (iv) All even numbers of Y
from left to right are
Solution: Children, Try this answer as copied into Z from right to
an assignment. left.
X, Y and Z are passed as arguments to
3.c) Considering the following key set: MERGE( ).
42,29,74,11,65,58, use insertion sort
to sort the data in ascending order Eg. X is {3, 2, 1, 7, 6, 3} and {9, 3, 5,
and indicate the sequences of steps 6, 2, 8, 10}
required.
The resultant array Z is
Solution: {3, 1, 7, 3, 9, 3, 5, 10, 8, 2, 6, 6, 2}

In this, Suppose an array A with n


S)

Ans)
C

elements A[1],A[2],…A[N] is in
T
G

memory. The insertion sort algorithm


(P

void MERGE(int X[ ], int m,int Y[ ],


scans A from A[1] to A[N], insertion
ar

int n,int Z[ ])
m

each element A[K] into its proper


Ku

{
er

position in the previously sorted int mn,i,,left=0,right=mn-1;


nd

subarray A[1],A[2],…,A[K-1].
re

mn=m+n;
Vi

This sorting algorithm is frequently for(i=0;i<m;i++)


used when n is small. if (X[i]%2= = 1)
The array contains 6 elements as Z[left++]=X[i];
follows: 42,29,74,11,65,58 //For copying odd numbers of
//X into Z from left to right
else
Pass A[0] A[1] A[2] A[3] A[4] A[5] A[6] Z[right- -]=X[i];
K=1 -32768 42 29 74 11 65 58 //For copying even number of
K=2 -32768 42 29 74 11 65 58 //X into Z from right to left
K=3 -32768 29 42 74 11 65 58 for(i=0;i<n;i++)
K=4 -32768 29 42 74 11 65 58 if (X[i]%2= = 1)
K=5 -32768 11 29 42 74 65 58 Z[left++]=Y[i];
K=6 -32768 11 29 42 65 74 58 //For copying odd numbers of
Sor - 11 29 42 58 65 74 //Y into Z from left to right
ted 32768 else
Z[right- -]=Y[i];
DELHI 2001: //For copying even number of
// X into Z from right to left

3.a) Given two arrays of integers X }


and Y of sizes m and n respectively.
Write a function named MERGE() 3.b) An array X[10][20] is stored in the
which will third array named Z, such memory with each element requiring 4
that the following sequence is bytes of storage. If the Base address of
followed. the array is 1000, calculate location of
121
X[5][15] when the array X is stored A, B and C as arguments in the
using column major order. function.
void Merge(int A[ ],int M,int B[ ],
NOTE: X[10][20] means valid row int N,int C[ ])
indices are 0 and 9 and valid {
column indices are 0 and 19 int a,b,c;
for(a=0,b=N-1,c=0;a<M&&b>=0;)
Solution: Children, Try this answer as {
an assignment. if(A[a]<=B[b])
C[c++]=A[a++];
3.c)Write a user-defined function else
named Lower_half() which takes 2D C[c++]=B[b--];
array A, with size N rows and N }
columns as argument and prints the if(a<M)
lower half of the array. {
while(a<M)
Eg: C[c++]=A[a++];
Input: }
2 3 1 5 0 else
7 1 5 3 1 {
2 5 7 8 1 while(b>=0)
0 1 5 0 1 C[c++]=B[b--];
3 4 9 1 5 }
}
S)

Output:
C

2 3.b) An array VAL[1…15][1…10] is


T
G
(P

7 1 stored in the memory with each


ar

2 5 7 element requiring 4 bytes of storage. If


m
Ku

0 1 5 0 the base address of the array VAL is


er

3 4 9 1 5 1500, determine the location of


nd
re

VAL[12][9] when the array VAL is


Vi

Solution: stored (i) Row wise (ii) Column wise.

void Lower_half( int A[ ][ ],int N) Solution:


{ int i,j; Given Data:
for(i=0;i<N;i++) VAL[1…15][1…10]
for(j=0;j<N;j++) Word Length (W) = 4 Bytes
{ if(i<j) Base Address of VAL(B) = 1500
cout<<A[i][j]<<’\t’; VAL[12][9] = ?
cout<<endl; C = Total No of Columns
} R = Total No of Rows
} Lr = Least Row=1
Lc = Least Column=1
DELHI 2000:
( i ) Row Major:
3.a) Suppose A, B, C are arrays of Address of an element (I,J) in row
integers of size M, N and M+N major = B + W ( C (I-Lr) + (J – Lc))
respectively. The numbers in array A
appear in ascending order while VAL [12][9] = 1500 + 4 (10 * (12-1) + (9-1))
numbers in array in descending order. = 1500 + 4 (10 * 11+8)
Write user defined function in C++ to = 1500 + 4 (118)
produce third array C by merging = 1500 + 472
array A by B in ascending order. Use = 1972.
122
if (Sno= = AR[m])
( i ) Column Major: {
Address of an element (I,J) in flag=1;
column major break;
= B + W ( (I-Lr) + R(J – Lc)) }
VAL [12][9] = 1500 + 4 ((12-1) +15 * (9-1)) else if(Sno<AR[m])
= 1500 + 4 (11 + 15 * 8) u=m-1;
= 1500 + 4 ( 11+ 120) else
= 1500 + 4 * 131 l=m+1;
= 1500 + 524 }
= 2024. if( flag = = 0)
cout<<”\nThe Search Element
3.c) Write a user-defined function in “ <<Sno<<” is not available”;
C++ to find and display the sum of else
diagonal elements from a 2D array cout<<”\nThe Search Element
MATRIX[6][6] containing integers. “ <<Sno<<” is available”;
}
void displaysum( )
{ 3.b) An array A[10][20] is stored in the
int i,j,D1=0,D2=0,MATRIX[6][6]; memory with each element requiring 4
cout<<”\nEnter any 36 values….”; bytes of storage. If the base address of
for(i=0;i<6;i++) the array in the memory is 400,
for(j=0;j<6;j++) determine the location of A[8][13]
{ cin>>MATRIX[i][j]; when the array VAL is stored (i) Row
S)

if(i= = j) major (ii) Column major.


C

D1=D1+MATRIX[i][j];
T
G

else if ((i+j)= =(size-1))


(P

Solution: Children, Try this answer.


ar

D2=D2+MATRIX[i][j];
m
Ku

} 3.c) Write a user-defined function in


er

cout<<”\nThe sum of the elements of C++ to find and display the


nd
re

the Main Diagonal = “<<D1; multiplication of row elements of two


Vi

cout<<”\nThe sum of the elements of dimensional array A[4][6] containing


the Other Diagonal = “<<D2; integers.
}
void rowmul( )
DELHI 1999: { int A[4][6],i,j,rowmul;
cout<<”\nEnter any 24 values…”;
3.a) Suppose a 1D array AR for(i=0;i<4;i++)
containing integers is arranged in for(j=0;j<6;j++)
ascending order. Write a user defined cin>>A[i][j];
function in C++ to search for one for(i=0;i<4;i++)
integer from AR with the help of {
binary search method, to show rowmul=1;
presence of the number in the array. for(j=0;j<6;j++)
The function should have three rowmul=rowmul*A[i][j];
parameters: (1) an array AR (2) the cout<<”\nThe multiplication of
number to be searched and (3) the “<<i+1<<” row = “<<rowmul;
number of elements N in the array. }
}
void BinSearch(int AR[ ], int Sno, int N)
{ int l=0,u=N-1,m,flag=0;
while(l<=u)
{ DELHI 1998:
m=(l+u)/2;
123
else if ((i+j)= =(size-1))
3.a) Suppose an array P containing D2=D2+R[i][j];
float is arranged in ascending order. }
Write a user defined function in C++ cout<<”\nThe sum of the elements of
to search for one float from p with the the Main Diagonal = “<<D1;
help of binary search method. The cout<<”\nThe sum of the elements of
function should return an integer 0 to the Other Diagonal = “<<D2;
show absence of the number in the }
array. The function should have the
parameters as (1) an array P (2) the MODEL PAPER 1 FOR 2009-10:
number DATA to be searched (3)
number of elements N. 3.a) Write a function in C++ to merge
the contents of two sorted arrays A &
int BinSearch(float P[ ], float DATA, int N) B into third array C. Assuming array A
{ int l=0,u=N-1,m; and B are sorted in ascending order
while(l<=u) and the resultant array C is also
{ required to be in ascending order. 3
m=(l+u)/2;
if (DATA= = P[m]) Ans)
return 1; void AddNSave(int A[ ],int B[ ],int C[ ],
else if(DATA<P[m]) int N,int M, int &K)
u=m-1; {
else int I=0,J=0;
l=m+1; K=0;
S)

} while (I<N && J<M)


C

return 0; if (A[I]<B[J])
T
G

}
(P

C[K++]=A[I++];
ar

else if (A[I]>B[J])
m
Ku

3.b) An array T[15][10] is stored in the C[K++]=B[J++];


er

memory with each element requiring 2 else


nd
re

bytes of storage. If the base address of {


Vi

T is 2000, determine the location of C[K++]=A[I++];


T[7][8] when the array VAL is stored (i) J++;
Row major (ii) Column major. }
for (;I<N;I++)
Solution: Children, Try this as an C[K++]=A[I];
assignment. for (;J<M;J++)
C[K++]=B[J];
3.c) Write a user-defined function in }
C++ to find and display the sum of
diagonal elements from a 2D array b)An array S[40][30] is stored in the
R[7][7] containing integers. memory along the row with each of the
element occupying 2 bytes, find out
void displaysum( ) the memory location for the element
{ S[20][10], if the Base Address of the
int i,j,D1=0,D2=0,R[7][7]; array is 5000. 3
cout<<”\nEnter any 49 values….”;
for(i=0;i<7;i++) Ans)
for(j=0;j<7;j++)
{ Given,
cin>>R[i][j]; W=2
if(i= = j) N=40
D1=D1+R[i][j]; M=30
124
Base(S)=5000 an element P[2][20] is stored at the
memory location 5000. 3
Row Major Formula:
Ans)
Loc(S[I][J])
=Base(S)+W*(M*I+J) Given,
W=4
Loc(S[20][10]) N=20
=5000+2*(30*20+10) M=30
=5000+2*(600+10) Loc(P[2][20]) =5000
=5000+1220
=6220 Column Major Formula:

d) Write a function in C++ to find the Loc(P[I][J]) = Base(P)+W*(N*J+I)


sum of both left and right diagonal
elements from a two dimensional Loc(P[2][20]) = Base(P)+4*(20*20+2)
array (matrix). Base(P) = 5000 -4*(400+2)
2 =5000-1608
=3392
Ans)
void DiagSum(int M[][4],int N,int M) d) Write a function in C++ to find sum
{ of rows from a twodimensional array.2
int SumD1=0,SumD2=0;
for (int I=0;I<N;I++) Ans)
S)

{ void MatAdd(int M[][4],int N,int M)


C

SumD1+=M[I][I];SumD2+=M[N-I-1][I]; {
T
G

}
(P

for (int R=0;R<N;R++)


ar

cout<<"Sum of Diagonal 1:" {


m
Ku

<<SumD1<<endl; int SumR=0;


er

cout<<"Sum of Diagonal 2:" for (int C=0;C<M;C++)


nd
re

<<SumD2<<endl; SumR+=M[C][R];
Vi

} cout<<SumR<<endl;
}
MODEL PAPER 2 FOR 2009-10: }

3.a) Write a function in C++ to MODEL PAPER 1 FOR 2008-09:


combine the contents of two equi-sized
arrays A and B by adding their Q3. Write a function in C++ to merge
corresponding elements as the the contents of two sorted arrays A &
formula A[i]+B[i]; where value i varies B into third array C. Assuming array A
from 0 to N-1 and transfer the is sorted in ascending order, B is
resultant content in the third same sorted in descending order, the
sized array C. 3 resultant array is required to be in
Ans) ascending order. 4
void AddNSave(int A[ ],int B[ ],int C[ ],int N)
{ Answer:
for (int i=0;i<N;i++)
C[i]=A[i]+B[i]; void AddNSave(int A[],int B[],int C[],int
} N,int M, int &K)
{
b) An array P[20][30] is stored in the int I=0,J=M-1;
memory along the column with each of K=0;
the element occupying 4 bytes, find while (I<N && J>=0)
out the Base Address of the array, if
125
{ void DiagSum(int A[100][100],int N)
if (A[I]<B[J]) {
C[K++]=A[I++]; int SumD1=0,SumD2=0;
else if (A[I]>B[J]) for (int I=0;I<N;I++)
C[K++]=B[J--]; {
else SumD1+=A[I][I];SumD2+=A[N-I-1][I];
{ }
C[K++]=A[I++]; cout<<”Sum of Diagonal 1:”
J--; <<SumD1<<endl;
} cout<<”Sum of Diagonal 2:”
} <<SumD2<<endl;
for (int T=I;T<N;T++) }
C[K++]=A[T];
for (T=J;T>=0;T--)
C[K++]=B[T]; MODEL PAPER 2 FOR 2008-09:
}
3.a)Write a function in C++ to combine
f) An array S[40][30] is stored in the the contents of two equi-sized arrays A
memory along the row with each of the and B by computing their
element occupying 2 bytes, find out corresponding elements with the
the memory location for the element formula 2*A[i]+3*B[i]; where value i
S[20][10], if an element S[15][5] is varies from 0 to N-1 and transfer the
stored at the memory location 5500.4 resultant content in the third same
Ans) sized array. 4
S)

Ans)
C
T

Given, void AddNSave(int A[ ],int B[ ],int C[ ],int N)


G
(P

W=2 {
ar

for (int i=0;i<N;i++)


m

N=40
Ku

M=30 C[i]=2*A[i]+3*B[i];
er

}
nd

Loc(S[15][5])=5500
re

Row Major Formula:


Vi

Loc(S[I][J]) =Base(S) 3.b) An array P[20][30] is stored in the


+W*(M*I+J) memory along the column with each of
Loc(S[15][5] =Base(S) the element occupying 4 bytes, find
+2*(30*15+5) out the memory location for the
5500 =Base(S)+2*(450+5) element P[5][15], if an element P[2][20]
Base(S) =5500- 910 is stored at the memory location 5000.
Base(S) =4590 4
Loc(S[20][10]) Ans)
=4590+2*(30*20+10)
=4590+2*(600+10) Given,
=4590+1220 W=4
= 5810 N=20
M=30
Loc(P[2][20])=5000
Column Major Formula:
h)Write a function in C++ to find the Loc(P[I][J])=Base(P)+W*(N*J+I)
sum of both left and right diagonal Loc(P[2][20])=Base(P)+4*(20*20+2)5000
elements from a two dimensional =Base(P)+4*(400+2)
array (matrix). Base(P) = 5000- 1608
2 Base(P) = 3392
Loc(P[5][15])=3392+4*(20*15+5)
Ans) =3392+4*(300+5)
126
=3392+1220 public:
=4612 Stack( )
{
Top = NULL;
3.d) Write a function in C++ to find }
sum of rows from a two dimensional void Push() ;
array. 2 void Pop() ;
void Display() ;
Ans) ~Stack () ;
};
void MatAdd(int A[100][100], int N,int M) void Stack::Push( )
{ {
for (int R=0;R<N;R++) Node *Temp = new Node;
{ gets(Temp -> Country);
int SumR=0; Temp -> Link = Top;
for (int C=0;C<M;C++) Top = Temp;
SumR+=A[C][R]; }
cout<<SumR<<endl; void Stack::Pop( )
} {
} if (Top !=NULL)
{
Node *Temp = Top;
Top = Top -> Link;
10. LINKED LISTS , delete Temp;
S)

}
C

else
T
G

STACKS AND QUEUES


(P

cout<<“stack Empty”;
ar

}
m
Ku

void Stack::Display( )
er

{
nd
re

Node *Temp = Top;


Vi

DELHI 2010: while (Temp! = NULL)


{
cout<<Temp -> Country <<endl;
Temp = Temp -> Link;
}
3.d) Write a complete program in c++ }
to implement a dynamically allocated Stack::~Stack ( )
Stack containing names of {
Countries.4 while (Top!=NULL)
{
Ans) NODE *Temp=Top;
Top=Top->Link;
#include<iostream.h> delete Temp;
#include<stdio.h> }
struct Node }
{ void main ( )
char Country [20] ; {
Node *Link; Stack ST;
}; char Ch;
class Stack do
{ {
Node *Top; cout<<“p/O/D/Q” ;
127
cin>>Ch;
switch (Ch)
{
case ‘P’ : ST.Push( ); break;
case ‘O’ :ST.Pop(); break;
case ‘D’ :ST.Disp();
}
} while (Ch!=’Q’);
}

(e) Evaluate the following postfix


notation of expression: 2
(Show status of Stack after each operation)
False, True, NOT, OR, True, False, AND, OR

Ans.

S)
C
T
G
(P
ar
m
Ku
er
nd
re

OR
Vi

OUTSIDE DELHI 2010:

(c) Write a complete program in C++ to


implement a dynamically allocated
Queue containing names of Cities. 4

Ans)

#include <iostream.h>
#include <conio.h>
struct NODE
{
char City[20];
NODE *Next;
};
class Queue
{
NODE *Rear,*Front;
puplic:
Queue( )
{
Rear=NULL;Front=NULL;
128
} }
void Qinsert( ); }
void Qdelete( ); void main( )
void Qdisplay( ); {
~Queue( ); Queue QU;
}; char Ch;
void Queue::Qinsert( ) do
{ {
NODE *Temp; :
Temp=new NODE; :
cout<<”Data:”; } while (Ch!=’Q’);
gets (Temp->City); }
Temp->Next=NULL;
if (Rear==NULL) (e) Evaluate the following postfix
{ notation of expression: 2
Rear=Temp; (Show status of Stack after each operation)
Front=Temp; True, False, NOT, OR, False, True, OR, AND
}
else
{
Rear–>Next=Temp;
Rear=Temp;
}
}
S)

void Queue::Qdelete( )
C

{
T
G
(P

if (Front!=NULL)
ar

{
m
Ku

NODE *Temp=Front;
er

cout<<Front->City<<”Deleted \n”; OR
nd
re

Front=Front->Next;
Vi

delete Temp;
if (Front==NULL)
Rear=NULL;
}
else
cout<<”Queue Empty..”;
}
Queue:: Qdisplay( )
{
NODE *Temp=Front;
while (Temp!=NULL)
{
cout<<Temp->City<<endl;
Temp=Temp->Next;
}
}
Queue:: ~Queue( )//Destructor Function
{
while (Front!=NULL)
{
NODE *Temp=Front;
Front=Front->Next; delete Temp;
129
}
void QUEINS( ); //Function to insert a node
void QUEDEL( ); //Function to de1ete a
node
void QUEDISP( );//Function to disp1ay nodes
~Queue( ); //Destructor to de1ete a11 nodes
};
void Queue::QUEINS( )
{
Node *Temp;
Temp = new Node;
cin>>Temp->PId;
gets(Temp->Pname);
//Or cin>>Temp->Pname;
//cin.get1ine(Temp->Pname);
Temp->Next = NULL;
if (Rear = = NULL)
{
Front = Temp;
Rear = Temp;
}
e1se
{
Rear->Next = Temp;
Rear = Temp;
S)

}
C
T

}
G
(P

OR
ar
m
Ku
er
nd

void QUEINS (Node *&Front, Node *&Rear)


DELHI 2009:
re

{
Vi

Node *Temp = new Node;


(c) Write a function QUEINS( ) in C++ cin>>Temp->PId;
to insert an element in a dynamically gets (Temp->Pname);
allocated Queue containing nodes of //or cin>>Temp->Pname;
the following given structure: 4 //cin.get1ine(Temp->Pname);
struct Node Temp->Next = NULL;
{ if(Rear == NULL)
int PId ; //Product Id Front = Temp;
char Pname [20] ; e1se
NODE *Next ; Rear -> Next = Temp;
}; Rear = Temp;
}
Ans)
(e) Convert the following infix
class Queue expression to its equivalent postfix
{ expression showing stack contents for
Node *Front, *Rear; the conversion: 2
public: X–Y /(Z + U) * V
QUEUE( )
//Constructor to initia1ize Front and Rear Ans)
{
Front = NULL; X - Y / (Z + U) * v
Rear = NULL; = (X - ((Y / (Z + U)) * v))
130
a dynamically allocated Queue
containing nodes of the following given
structure: 4
struct NODE
{
int Itemno;
char Itemname[20];
NODE *Link;
};

Ans)

class Queue
{
Node *Front, *Rear;
public:
QUEUE( )
//Constructor to initialize Front and Rear
{
Front = NULL;
Rear = NULL;
}
void QUEINS( );
//Function to insert a node
void QUEDEL( );
S)
C

//Function to delete a node


T

void QUEDISP( );
G
(P

//Function to display nodes


ar

~Queue();
m

OR
Ku

//Destructor to delete all nodes


er

};
nd
re
Vi

void Queue::QUEDEL( )
{
if (Front!=NULL)
{
NODE *Temp=Front;
cout<<Front->Itemno<<” “;
cout<<Front->Itemname<<”Deleted“;
Front=Front->Link;
delete Temp;
if (Front NULL)
Rear=NULL;
}
else
cout<<”Queue Empty..”;
}
OR

void QUEDEL(Node *&Front, Node *&Rear)


OUTSIDE DELHI 2009: {
if (Front ! =NULL)
(c) Write a function QUEDEL( ) in C++ {
to display and delete an element from NODE *Temp=Front;
cout<<Front->Itemno<<” “;
131
cout<<Front->Itemname<<”Deleted”;
Front=Front->Link;
delete Temp;
if (Front == NULL)
Rear=NULL;
}
else
cout<<”Queue Empty..”;
}

(e) Convert the following infix


expression to its equivalent postfix
expression showing stack contents for
the conversion: 2

A + B * (C – D) / E

Ans)
DELHI 2008:
A + B * (C - D) / E
= (A+ ( (B* (C-D) ) / E) )
3.c) Write a function in C++ to insert
an element into a dynamically
allocated Queue where each node
contains a name (of type string) as
S)
C

data.
T
G
(P

Assume the following definition of


ar
m

THENODE for the same.


Ku
er
nd

struct THENODE
re
Vi

{
char Name[20];
THENODE *Link;
};

Solution:

struct THENODE
{
char Name[20];
THENODE *Link;
OR };

class Queue
{
THENODE *front,*rear;
public:
Queue( )
{
front = rear = NULL;
}
void Insert( );
void Delete( );
132
void Display( );
};
void Queue::Insert( )
{
THENODE *ptr;
ptr=new THENODE;
if(ptr= = NULL)
{
cout<<”\nNo memory to create a
new node….”;
exit(1);
}
cout<<”\nEnter the name….”;
gets(ptrName);
ptrLink=NULL;
if(rear= = NULL)
front=rear=ptr;
else
{
rearLink=ptr;
rear=ptr;
}
}
S)

3.e) Evaluate the following postfix


C

notation of expression (Show status of


T
G
(P

stack after execution of each operation ): 2


ar

4, 10, 5, +, *, 15, 3, /, -
m
Ku
er
nd
re
Vi

133
{ front=rear=NULL; }
void Insert( );
void Delete( );
void Display( );
};
void Queue::Delete( )
{
MYNODE *temp;
if(front= = NULL)
cout<<”Queue Underflow”;
else
{
cout<<”\nThe content of the
element to delete: “<<frontNUM;
temp=front;
front=frontLink;
delete temp;
}
}

3.e) Evaluate the following postfix


notation of expression (Show status of
stack after execution of each
operations):
S)

5, 20, 15, -, *,25, 2, *, + 2


C
T

OUTSIDE DELHI 2008:


G
(P

Ans)
ar

3.c) Write a function in C++ to Delete


m
Ku

an element into a dynamically


er

allocated Queue where each node


nd
re

contains a real number as data. 4


Vi

Assume the following definition of


MYNODE for the same:

struct MYNODE
{
float NUM;
MYNODE * Link;
};

Solution:

struct MYNODE
{ DELHI : 2007
float NUM;
MYNODE *Link; 3.c)Write a function in C++ to delete a
}; node containing Book’s information,
class Queue from a dynamically allocated Stack
{ of Books implemented with the help of
MYNODE *front,*rear; the following structure.
public: struct Book
Queue( ) {
134
int BNo ;
char BName[20] ;
Book *Next ;
};

Solution:

struct Book
{
int BNo ;
char BName[20] ;
Book *Next ;
};
class Stack
{
Book *Top;
public:
Stack( )
{
Top = NULL;
OUTSIDE DELHI : 2007
}
void Push( );
3.c) Write a function in C++ to delete
void Pop( );
a node containing customer’s
void Display( );
information, from a dynamically
S)

};
allocated Queue
C

of Customers
void Stack::Pop( )
T
G

implemented with the help of the


(P

{
following structure:
ar

Book *Temp;
m
Ku

if( Top= = NULL)


struct Customer
er

cout<<”Stack Underflow…”;
nd

{
re

else
Vi

int CNo ;
{
char CName[20] ;
cout<<”\nThe Book number of the
Customer *Link ;
element to delete: “<<TopBNo;
};
cout<<”\nThe Book name of the
element to delete: “<<TopBName;
Solution:
Temp=Top;
Top=TopNext;
struct Customer
delete Temp;
{
}
int CNo ;
}
char CName[20] ;
Customer *Link ;
3.e)Evaluate the following postfix
};
notation of expression : 2
class Queue
25 8 3 - / 6 * 10 +
{
Customer *front,*rear;
public:
Queue( )
{
front=rear=NULL;
}
void Insert( );
void Delete( );
135
void Display( ); rear = - 1 ;
}; }
void Queue::Delete( ) void add( );
{ //to add an element into the queue
Customer *Temp; void remove( );
if(front= =NULL) //to remove an element from the queue
cout<<”Queue Underflow. No void Delete(int ITEM( );
//to delete all elements which are equal to
element to delete”; ITEM
else };
{
cout<<”\n The customer number for the Complete the class with all function
element to delete”<<frontCNo;
cout<<”\n The customer name for the
definitions for a circular array Queue.
element to delete”<<frontCName; Use another queue to transfer data
Temp=front; temporarily.
front = frontLink;
delete Temp; Solution:
}
} void queue::add( )
{
3.e) Evaluate the following postfix if((front= = 0 && rear = = 9) | |
notation of expression : 2 (front= =rear+1)
15 3 2 + / 7 + 2. * cout<<”\nQueue Overflow”;
else if (rear= = -1)
Ans) {
S)

front=rear=0;
C
T

cout<<”\nEnter the element to be inserted”;


G

cin>>data[rear];
(P
ar

}
m
Ku

else if(rear= =9)


er

{
nd
re

rear=0;
Vi

cout<<”\nEnter the element to be inserted”;


cin>>data[rear];
}
else
{
rear++;
cout<<”\nEnter the element to
be inserted”;
cin>>data[rear];
. }
}
DELHI : 2006 void queue::remove( )
{
3.c ) if(front= = -1)
class queue cout<<”\nQueue Underflow…”;
{ else
int data[10] ; { cout<<”\nThe element to be
int front, rear; deleted”<<data[front];
public : if(front= =rear)
queue( ) front=rear=-1;
{ else if (front= =9)
front = - 1; front=0;
else
136
front++; if (front != rear) //Ignoring –1 initial values
} {
} front = (front+1)%10;
void queue::Delete(int ITEM ) cout<< data[front]<<” deleted…”;
{ }
//Children, try to complete this else
function. cout<<”Queue empty ! Underflow Error!!\n”;
}
OR

} void queue::add( )
OR {
int item;
void queue::add( ) if((front==0 && rear==9) ||
{ front==rear+1)
if ( (rear + 1) % 10 != front ) cout<<”\nQueue overflow error”;
{ else
if (rear == -1 ) {
front = rear = 0 ; cout<<”\nEnter an item to add : “;
else cin>>item;
rear = (rear + 1) %10; if(front==-1)
cin>>data[rear]; {
} front=0;rear=0;
else }
else
S)

cout<<”Queue full !! Overflow Error !!\n”;


C

} rear=rear+1;
T
G

void queue::remove( ) if(rear==10)


(P
ar

{ rear=0;
m

data[rear]=item;
Ku

if (front != -1)
er

{ }
nd

cout<< data[front]<<” deleted ”; }


re
Vi

if(front==rear) OR
front=rear=-1;
else void queue::remove( )
front = (front+1)%10; {
} if((front==-1 )
else cout<<”\nQueue Underflow Error”;
cout<<”Queue empty ! Underflow Error!!\n”; else
} {
OR int item=data[front];
if(front==rear)
void queue::add( ) front=rear=-1;
{ else if(front==9)
if ( (rear + 1) % 10 != front ) front=0;
//Ignoring –1 initial values else
{ front=front+1;
rear = (rear + 1) %10; cout<<”\nDeleted item is : “<<item;
cin>>data[rear]; }
} }
else
cout<<”Queue full !! Overflow Error !!\n”; 3.d) Write a function in C++ to
} perform a PUSH operation on a
void queue::remove() dynamically allocated stack containing
{ real number.
137
struct Node 3.e) Write the equivalent infix
{ expression for
float Number ; a, b, AND, a, c, AND, OR.
Node *Link ;
}; Ans) a, b, AND, a, c, AND, OR
class STACK (a AND b), (a AND c), OR
{ (a AND b) OR (a AND c)
Node *Top ;
public :
STACK( )
{
Top = NULL;
}
void PUSH( ) ;
void POP( ) ;
~STACK( ) ;
};

Solution:

struct Node
{
float Number ; OUTSIDE DELHI : 2006
S)

Node *Link ;
C

}; 3.c) Introduction
T
G
(P

class STACK
ar

{ class stack
m
Ku

Node *Top ; {
er

public : int data[10] :


nd
re

STACK( ) int top ;


Vi

{ public :
Top = NULL; stack( )
} {
void PUSH( ) ; top = - 1;
void POP( ) ; }
~STACK( ) ; void push( ) ;
}; //to push an element into the stack
void STACK::PUSH( ) void pop( ) ;
//to pop an element from the stack
{ Node *Temp;
Temp=new Node; void Delete(int ITEM) ;
//To delete all elements which are
if(Temp= =NULL) //equal to ITEM.
{ };
cout<<”\nNo memory to create the Complete the class with all function
node…”; definitions. Use another stack to
exit(1); transfer data temporarily.
}
cout<<”\nEnter the Number to be Solution:
inserted: “;
cin>>TempNumber; void stack::push( )
TempLink=Top; {
Top=Temp; if(top>=9)
} cout<<”Stack Overflow…”;
138
else { char Name[20];
{ NODE *Link;
top++; };
cout<<”\nEnter the element to be
inserted…”; Solution:
cin>>data[top]; class Queue
} {
} NODE *front,*rear;
void stack::pop( ) public:
{ Queue( )
if(top= =-1) {
cout<<”\nStack Underflow”; front = rear = NULL;
else }
{ void Insert( );
cout<<”\nThe element to be void Delete( );
deleted = “<<data[top]; void Display( );
top--; };
} void Queue::Insert( )
} {
void stack::Delete(int ITEM) NODE *ptr;
{ ptr=new NODE;
//Dear children, try to complete this function. if(ptr= = NULL)
{
cout<<”\nNo memory to create a
S)

new node….”;
C

} exit(1);
T
G

OR
(P

}
ar

cout<<”\nEnter the name….”;


m

void stack::push( )
Ku

gets(ptrName);
{ int n;
er

ptrLink=NULL;
nd

cout<<”Enter a value”;cin>>n;
re

if(rear= = NULL)
Vi

if (top==10) front=rear=ptr;
cout<<”Stack Overflow”; else
else {
data[++top]=n; rearLink=ptr;
} rear=ptr;
void stack::pop( ) }
{ }
if (top==-1)
cout<<”Stack Underflow”; 3.e) Write the equivalent infix
else expression for 10, 3, *, 7, 1, --,*, 23, +
cout<<data[top--];
} Solution:
10, 3, *, 7, 1, - , *, 23, +
void stack::Delete(int ITEM); This is in Postfix form
//Ignore this part (ie Operator will come after the operand(s));.

Infix form means Operator must come


3.d)Write a function in C++ to perform in between the operands.
Insert operation in dynamically 10, 3, *, 7, 1, - , *, 23, +
allocated Queue containing names of
students. Prefix: 10 * 3, 7 – 1,*,23,+
(10 * 3) * (7 – 1),23,+
Struct NODE (10 * 3) * (7 – 1) + 23
139
cout<<”\nNo memory to
(Infix form) create the node…”;
OR exit(1);
10*3*(7-1)+23 }
cout<<”Enter the value of X and Y”;
DELHI : 2005 cin>>TempX>>TempY;
TempLink=Top;
3.c) Write a function in C++ to Top=Temp;
perform a PUSH operation in a }
dynamically allocated stack
considering the following : 3.e) Evaluate the following postfix
notation of expression :
struct Node 10 20 + 25 15 - * 30 /
{
int X,Y ; Ans)
Node *Link ;
};

class STACK
{
Node *Top ;
public :
STACK( )
{Top = Null ;}
S)

void PUSH( ) ;
C

void POP( ) ;
T
G
(P

~STACK( ) ;
ar

};
m
Ku
er

Solution:
nd
re
Vi

struct Node
{
int X,Y ;
Node *Link ;
};
class STACK
{
Node *Top ;
public :
STACK( )
{ Top = NULL;
}
void PUSH( ) ;
void POP( ) ;
~STACK( ) ;
};
void STACK::PUSH( )
{
Node *Temp;
Temp=new Node;
if(Temp= =NULL)
{
140
OUTSIDE DELHI : 2005
S)

3.c) Write a function in C++ to


C
T

perform a DELETE operation in a


G
(P

dynamically allocated queue


ar
m

considering the following description :


Ku
er
nd

struct Node
re
Vi

{
float U, V ;
Node *Link ;
};
class QUEUE
{
Node *Rear, *Front ;
public :
QUEUE( )
{
Rear = NULL;
Front = NULL;
}
void INSERT( ) ;
void DELETE( ) ;
~ QUEUE( ) ;
};

Solution:

void Queue::DELETE( )
OR {
141
NODE *temp;
if(front= = NULL)
cout<<”\nQueue Underflow”;
else
{ cout<<”\nThe value of U of the
element to delete: “<<FrontU;
cout<<”\nThe value of V of the
element to delete: “<<FrontV;
temp=Front;
Front=FrontLink;
delete temp;
}
}

3.e) Evaluate the following postfix


notation of expression :
20 10 + 5 2 * - 10 /

Ans)

S)
C
T
G
(P
ar
m
Ku
er
nd
re
Vi

142
3.e)Define member functions queins( )
to insert nodes and quedel ( ) to delete
nodes of the linked list implemented
class queue, where each node has the
following structure:

struct node
{
char name[20] ;
int age ;
node *Link ;
};
class queue
{
2004: node *rear, *front ;
public :
3.d) Obtain the postfix notation for the queue( )
following infix notation of expression { rear = NULL; front = NULL} ;
showing the contents of the stack and void queins( ) ;
postfix expression formed after each void quedel( ) ;
step of conversion : };
(P—Q)/(R*(S—T)+U)
Ans) ((P-Q)/((R*(S-T))+U)) Solution:
S Symbol Stack Expression Y
S)

No Scanned
void queue::queins( )
C

{
T
G
(P

1 ( ( node *ptr;
ar

2 ( ( ( ptr=new node;
m
Ku

3 P ( ( P if(ptr= = NULL)
er

4 - ( (- P {
nd

5 Q ( (- P Q
re

cout<<”\nNo memory to create a


Vi

6 ) ( P Q -
7 / ( / P Q - new node….”;
8 ( ( / ( P Q - exit(1);
9 ( ( / ( ( P Q - }
10 R ( / ( ( P Q - R cout<<”\nEnter the name….”;
11 * ( / ( ( * P Q - R gets(ptrname);
12 ( ( / ( ( * ( P Q - R
cout<<”\nEnter the age…”;
13 S ( / ( ( * ( P Q - R S
14 - ( / ( ( * ( - P Q - R S
cin>>ptrage;
15 T ( / ( ( * ( - P Q - R S T ptrLink=NULL;
16 ) ( / ( ( * P Q - R S T if(rear= = NULL)
- front=rear=ptr;
17 ) (/ ( P Q - R S T else
- *
{
18 + (/ ( + P Q - R S T
- * rearLink=ptr;
19 U (/ ( + P Q - R S T rear=ptr;
- * U }
20 ) (/ P Q - R S T }
- * U + void queue::quedel( )
21 ) P Q - R S T
{
- * U + /
node *temp;
if(front= = NULL)
Postfix Form: PQ-RST-*U+/
cout<<”Queue Underflow”;
else
143
{ NODE *ptr;
cout<<”\nThe name of the ptr=new NODE;
element to delete: “<<frontname; if(ptr= = NULL)
cout<<”\nThe age of the element to {
delete: “<<frontage; cout<<”\nNo memory to create a
temp=front; new node….”;
front=frontLink; exit(1);
delete temp; }
} cout<<”\nEnter the Ticket
} Number….”;
cin>>ptrTicketno;
DELHI : 2003 cout<<”\nEnter the Passenger
Name..”;
3.c) Evaluate the following postfix gets(ptrPName);
expression using a stack and show the ptrNext=NULL;
contents of stack after execution of if(rear= = NULL)
each operation: front=rear=ptr;
20, 45, +, 20, 10, -, 15, +, * else
{
Ans) Children, Try this answer as an rearNext=ptr;
assignment. rear=ptr;
}
3.e)Consider the following portion of a }
program, which implements
S)

passengers Queue for a train. Write DELHI : 2002


C

the definition of function. Insert


T
G
(P

(whose prototype is shown below); to 3.b) Given the following class, 4


ar

insert a new node in the queue with


m
Ku

required information. char *msg[ ]={“over flow”,”under flow”};


er

class Stack
nd
re

struct NODE { int top; //the stack pointer


Vi

{ int stk[5]; //the elements


long Ticketno; void err_rep(int e_num)
char PName[20];//Passengers Name {
NODE * Next; cout<<msg[e_enum];
}; //report error message
class Queueoftrain }
{ public:
NODE * Rear, * Front; void init( )
public : {
Queueoftrain( ) top=0;
{ Rear = NULL; Front = NULL:} } //initialize the stack pointer
void Insert( );
void Delete( ); void push(int); //put new value in stk
~Queueoftrain( ); void pop( ); //get the top value.
}; };

Solution: Define pop outside the Stack. In your


definition take care of under flow
condition. Function pop should
invoke err_rep to report under flow.
void Queueoftrain::Insert( ) Solution:
{
void Stack::pop( )
144
{ //Dear children, try to complete this function. /* End of If structure */
6. If a right parenthesis is
encountered, then:
} (a) Repeatedly pop from STACK
and add to Y each operator (on the top
3.c) Change the following infix of STACK) until a left Parenthesis is
expression into postfix expression. encountered.
(A+B)*C+D/E-F 3 (b) Remove the left parenthesis.
(Do not add the left parenthesis to Y).
Ans) Children, Try this answer as an /* End of If structure */
assignment. 7. End.

DELHI : 2001 3.e)Each node of a STACK contains


the following information, in addition
3.d)Write an algorithm to convert an to pointer field:
infix expression to postfix expression. (i).Pin code of city
(ii).Name of city
Ans) Give the structure of node for the
The following algorithm transforms the linked STACK in question. TOP is a
infix expression X into its equivalent pointer that points to the topmost
postfix expression Y. The algorithm node of the STACK. Write the
uses a stack to temporarily hold following functions: 4
operators and left parentheses. The
postfix expression Y will be a)PUSH( ) – To push a node into the
S)

constructed from left to right using the STACK, which is allocated


C

operands from X and the operators dynamically.


T
G
(P

which are removed from STACK. We


ar

begin by pushing a left parenthesis b)POP( ) – To remove a node from the


m
Ku

onto STACK and adding a right STACK, and release the memory.
er

parenthesis at the end of X. The


nd
re

algorithm is completed when STACK is Solution:


Vi

empty.
Algorithm: struct City
Suppose X is an arithmetic expression { long Cpin ;
written in infix notation. This char CName[20] ;
algorithm finds the equivalent postfix City *Next ;
expression Y. };
1. Push “(“ onto STACK, and add “)” to
the end of X. class Stack
2. Scan X from left to right and {
REPEAT Steps 3 to 6 for each element City *Top;
of X UNTIL the STACK is empty. public:
3. If an operand is encountered, add Stack( ) { Top = NULL; }
it to Y. void Push( );
4. If a left parenthesis is encountered, void Pop( );
push it onto STACK. void Display( );
5. If an operator is encountered, then: };
(a) Repeatedly pop from STACK and
add to Y each operator(on the top of void Stack::PUSH( )
STACK) which has the same { City *Temp;
precedence as or higher precedence Temp=new City;
than operator. if(Temp= =NULL)
(b) Add operator to STACK. {
145
cout<<”\nNo memory to create class Queue
the node…”; {
exit(1); NODE *front,*rear;
} public:
cout<<”\nEnter the City Pin Code Queue( )
to be inserted: “; {
cin>>TempCpin; front = rear = NULL;
cout<<”\nEnter the City Name to }
be inserted: “; void Insert( );
gets(TempCName); void Delete( );
TempNext=Top; void Display( );
Top=Temp; };
} void Queue::Insert( )
void Stack::POP( ) {
{ NODE *ptr;
City *Temp; ptr=new NODE;
if( Top= = NULL) if(ptr= = NULL)
cout<<”Stack Underflow…”; {
else cout<<”\nNo memory to
{ create a new node….”;
cout<<”\nThe City Pin Code for exit(1);
the element to delete: “<<TopCpin; }
cout<<”\nThe City name of the element
to delete: “<<TopCName;
cout<<”\nEnter the Number….”;
Temp=Top; cin>>ptrNumber;
S)

Top=TopNext; ptrLink=NULL;
C

if(rear= = NULL)
T

delete Temp;
G
(P

} front=rear=ptr;
ar

else
m

}
Ku

{
er

rearLink=ptr;
nd

DELHI : 2000
re

rear=ptr;
Vi

3.d)Evaluate the following postfix }


expression using a stack. Show the }
contents of stack after execution of
each operation: 1999:
20, 8, 4, /, 2, 3, +, *, -
Ans) Children, Try this answer as an 3 (d) Evaluate the following postfix
assignment. expression using a stack and show the
contents of the stack after execution of
3.e)Give necessary declarations for a each operation
queue containing float type numbers;
also write a user defined function in 5,11,-,6,8,+,12,*,/
C++ to insert a float type number in
the queue. You should use linked Ans) Children, Try this answer as an
representation of queue. assignment.

3 (e) Give the necessary declaration of


Solution: a linked list implemented queue
containing float type elements. Also
struct NODE write a user defined function in C++ to
{ float Number; delete a float type number from the
NODE *Link; queue.
};
146
struct MYNODE {
{ float NUM; float Number;
MYNODE * Link; Node *Next ;
}; };
class Stack
Solution: {
Node *Top;
struct MYNODE public:
{ float NUM; Stack( )
MYNODE *Link; {
}; Top = NULL;
class Queue }
{ void Push( );
MYNODE *front,*rear; void Pop( );
public: void Display( );
Queue( ) };
{ front=rear=NULL; } void Stack::Pop( )
void Insert( ); {
void Delete( ); Node *Temp;
void Display( ); if( Top= = NULL)
}; cout<<”Stack Underflow…”;
void Queue::Delete( ) else
{ MYNODE *temp; {
if(front= = NULL) cout<<”\nThe Number of the element to
delete: “<<TopNumber;
S)

cout<<”Queue Underflow”;
C

else Temp=Top;
T
G

Top=TopNext;
(P

{
delete Temp;
ar

cout<<”\nThe content of the


m

}
Ku

element to delete: “<<frontNUM;


er

temp=front; }
nd

front=frontnext;
re
Vi

delete temp; MODEL PAPER 1 FOR 2009-10:


}
} (c) Write a function in C++ to perform
Insert operation in a dynamically
1998: allocated Queue containing names of
students. 4
3 (d) Evaluate the following postfix
expression using a stack and show the Ans)
contents of stack after execution of
each operation: struct NODE
50, 40, +, 18, 14, -, 4, *, + { char Name[20];
NODE *Link;
Ans) Children, Try this answer as an };
assignment. class QUEUE
3 (e) Give the necessary declaration of {
a linked implemented stack NODE *R,*F;
containing integer type numbers; also public:
write a user defined function in C++ to QUEUE();
pop a number from this stack. void Insert();
void Delete();
Solution: };
void QUEUE::Insert()
struct Node {
147
NODE *Temp;
Temp=new NODE;
gets(Temp->Name);
Temp->Link=NULL;
if (Rear==NULL)
{
Rear=Temp;
Front=Temp;
}
else
{
Rear->Link=Temp;
Rear=Temp;
}
}

(e) Evaluate the following postfix


notation of expression: 2
MODEL PAPER 2 FOR 2009-10:
20, 30, +, 50, 40, - ,*
c) Write a function in C++ to perform
Push operation on a dynamically
allocated Stack containing real
numbers. 4
S)

Ans)
C
T
G
(P

struct NODE
ar
m

{
Ku

float Data;
er
nd

NODE *Link;
re
Vi

};
class STACK
{
NODE *Top;
public:
STACK( );
void Push();
void Pop();
void Display();
~STACK();
};
void STACK::Push()
{
NODE *Temp;
Temp=new NODE;
cin>>Temp->Data;
Temp->Link=Top;
Top=Temp;
}

e) Evaluate the following postfix


notation of expression:

148
True, False, AND, True, True, NOT, OR, {
AND 2 char Name[20];
NODE *Link;
Ans) };
class QUEUE
{
NODE *R,*F;
public:
QUEUE();
void Insert();
void Delete();
};
void QUEUE::Insert()
{ NODE *Temp;
Temp=new NODE;
gets(Temp->Name);
Temp->Link=NULL;
if (Rear==NULL)
{
Rear=Temp;
Front=Temp;
}
else
{
S)

Rear->Link=Temp;
C

Rear=Temp;
T
G
(P

}
ar

}
m
Ku
er

e) Evaluate the following


nd

postfix
re

notation of expression: 2
Vi

20,30,+,50,40,-,*

MODEL PAPER 1 FOR 2008-09:

c) Write a function in C++ to perform


Insert operation in a dynamically
allocated Queue containing names of
students. 4

struct NODE
149
True, False, AND, True, True, NOT, OR,
AND

Ans)

MODEL PAPER 2 FOR 2008-09:


S)

c) Write a function in C++ to perform


C
T

Push operation on a dynamically


G
(P

allocated Stack containing real


ar

numbers. 4
m
Ku

Ans)
er
nd
re

struct NODE
Vi

{ float Data;
NODE *Link;
};
class STACK
{ NODE *Top;
public:
STACK();
void Push();
void Pop();
};
void STACK::Push()
{ NODE *Temp;
Temp=new NODE;
cin>>Temp->Data;
Temp->Link=Top;
Top=Temp;
11.DATA BASE CONCEPTS
}
DELHI 2010:

5. (a) What do you understand by


e) Evaluate the following postfix Candidate Keys in a table? Give a
notation of expression: 2 suitable example of Candidate Keys
150
from a table containing some identifies a tuple uniquely, all such
meaningful data. 2 attribute(s) are known as Candidate
Keys.
Ans) A table may have more than one
such attribute/group of attribute that
identifies a tuple uniquely, all such
attribute(s) are known as Candidate
Keys.

Table: Item

OUTSIDE DELHI 2009:

5. (a) What is the purpose of a key in a


table? Give an example of a key in a
table. 2
OUTSIDE DELHI 2010:
S)

Ans) An attribute/group of attributes


C
T
G

5. (a) What do you understand by in a table that identifies each tuple


(P

uniquely is known as a Key.


ar

Primary Key? Give a suitable example


m

OR
Ku

of Primary Key from a table containing


Any correct definition of Key / Primary
er

some meaningful data 2


nd

Key / Candidate Key / Alternate Key


re
Vi

Ans. An attribute or set of attributes


which are used to identify a tuple
uniquely is known as Primary Key.

Table: Item

Delhi 2008:
DELHI 2009:
5.a) Differentiate between Candidate
5.(a)What are candidate keys in a key and Primary key in context of
table? Give a suitable example of RDBMS.
candidate keys in a table. 2
Ans:
Ans A table may have more than one
such attribute/group of attribute that
151
Candidate Key: All attribute identifies a row in a relation) are
combinations inside a relation that Candidate Keys as they are candidates
can serve primary key are Candidate for the primary key position.)
Keys as they are candidates for the
primary key position. Outside Delhi 2007:

Primary Key: A primary key is a set 5.a) What is the importance of a


of one or more attributes that can primary key in a table? Explain with
uniquely identify tuples within the suitable example.
relations.
Ans:
Outside Delhi 2008:
Primary Key: A primary key is a set
5.a) Differentiate between Candidate of one or more attributes that can
Key and alternate Key in context of uniquely identify tuples within the
RDBMS. relations. A primary key comprises a
single column or set of columns. No
Ans: two distinct rows in a table can have
the same value (or combination of
Candidate Key: All attribute values) in those columns. Depending
combinations inside a relation that on its designing, a table may have
can serve as primary key are arbitrarily many candidate keys but at
Candidate Keys as they are candidates most one primary key. The primary
for the primary key position. key is non redundant. Ie it does not
S)

have duplicate values in the same


C

Alternate Key: A candidate key that relation.


T
G
(P

is not the primary key is called an


ar

Alternate Key. Eg: Consider a table consists the


m
Ku

(Where Candidate Key: All attribute following attributes:


er

combinations inside a relation that AdmnNo,FirstName,LastName,SirNam


nd
re

can serve primary key(uniquely e,M1,M2,M3,Total,Avg,FName


Vi

identifies a row in a relation) are


Candidate Keys as they are candidates Here we can uniquely identify the rows
for the primary key position.) in the relation with following key
combinations:
Delhi 2007: a)AdmnNo
b)FirstName,LastName,SirName
5.a) Differentiate between primary key c)FirstName,LastName,FName, etc.
and alternate key. We can set any one of the above
candidate keys as primary key, others
Ans: are called as alternate keys.

Primary Key: A primary key is a set


of one or more attributes that can Delhi 2006:
uniquely identify tuples within the
relations. 5.a) What is an alternate key?

Alternate Key: A candidate key that Ans:


is not the primary key is called an Alternate Key: A candidate key that
Alternate Key. is not the primary key is called an
(Where Candidate Key: All attribute Alternate Key.
combinations inside a relation that (Where Candidate Key: All attribute
can serve primary key(uniquely combinations inside a relation that
152
can serve primary key(uniquely
identifies a row in a relation) are Candidate Key: All attribute
Candidate Keys as they are candidates combinations inside a relation that
for the primary key position.) can serve as primary key(uniquely
identifies a row in a relation) are
Outside Delhi 2006: Candidate Keys as they are candidates
for the primary key position.The
5.a) What are DDL and DML? number of rows in a relation is known
as cardinality of a relation.
Ans: DDL means Data Definition
Language. DDL provides statements 2003:
for the creation and deletion of tables
and indexes. DML Means Data 5.a) What is primary key in a table?
Manipulation Language. The DML (Define first normal form.- This is
provides statements to enter, out of syllabus)
update,delete data and perform
complex queries on these tables. The Ans:
SQL DDL (Data Definition Language)
provides commands for defining Primary Key: A primary key is a set
relation schemas, deleting relations, of one or more attributes that can
creating indexes and modifying uniquely identify tuples within the
relation schemas. relations.
The SQL DML (Data Manipulation
Language) includes a query language 2002:
S)

to insert, delete and modify tuples in


C

the database. 5.a) Differentiate between data


T
G
(P

DML is used to put values and definition language and data


ar

manipulate them in tables and other manipulation language.


m
Ku

database objects and DDL is used to


er

create tables and other database Ans: The SQL DDL(Data Definition
nd
re

objects. Language) provides commands for


Vi

defining relation schemas, deleting


Delhi 2005: relations, creating indexes and
modifying relation schemas.
5.a)What do you understand by the The SQL DML (Data Manipulation
terms primary key and degree of a Language) includes a query language
relation in relational data base? to insert, delete and modify tuples in
the database.
Ans: DML is used to put values and
Primary Key: A primary key is a set manipulate them in tables and other
of one or more attributes that can database objects and DDL is used to
uniquely identify tuples within the create tables and other database
relations.The number of attributes in objects.
a relation is called Degree of a relation
in relational data base. 2001

Outside Delhi 2005: 5.c) Explain Cartesian product of two


relations.
5.a) What do you understand by the
candidate key and cardinality of a Ans: The Cartesian product is a
relation in relational data base? binary operation and is denoted by a
cross(x). The Cartesian product of two
Ans: relations A and B is written as AXB.
153
The Cartesian product yields a new Science
3 Raheem Y P.Pavan Electronics
relation which has a degree (number
of attributes) equal to the sum of the
degrees of the two relations operated The resulting relation contains all
upon. The number of typles possible combinations of tuples of the
(cardinality) of the new relation is the two relations.
product of the number of tuples of the
two relations operated upon. The 1998:
Cartesian product of two relations
yields a relation with all possible 5.a) What is a relation? What is the
combinations of the tuples of the two difference between a tuple and an
relations operated upon. All attribute?
tuples of first relation are
concatenated with all the tuples of Ans: In relational data model, the
second realtion to form the tuples of data is organized into table (rows and
the new relation. columns). These tables are called
relations. A row in a table represents
Eg: There are two relations as a relationship among a set of values.
follows:
Relation 1: Student Rows of the relations are called
as tuples and columns of the relations
Student StudentName Hosteler are called as attributes.
Number
1 Ravi Y MODEL PAPER 1 FOR 2009-10:
2 Robert N
S)
C

3 Raheem Y 5.a) What do you understand by


T
G

Degree and Cardinality of a table? 2


(P
ar

Relation 2: Instructor
m

Ans)
Ku
er

InstructorName Subject
nd

K.Suman Computer Science Degree: Number of Columns in a table


re
Vi

P.Pavan Electronics
Cardinality: Number of rows in a
The Cartesian product of these two table
relations, Student X Instructor, will
yield a relation that have a degree of
5(3+2:sum of degrees of Student and
Instructor) and a cardinality 6 (3 X 2: MODEL PAPER 2 FOR 2009-10:
Product of cardinalities of two
relations). 5.a) What do you understand by
Primary Key & Candidate Keys? 2
The resulting relation is as follows:
Ans)
Stude Studen Ho Instructo Subject An attribute or set attributes which
nt t st r are used to identify a tuple uniquely is
Numb Name ele Name known as Primary Key. If a table has
er r more than one such attributes which
1 Ravi Y K.Suman Computer identify a tuple uniquely than all such
Science attributes are known as Candidate
1 Ravi Y P.Pavan Electronics Keys.
2 Robert N K.Suman Computer
Science
2 Robert N P.Pavan Electronics
3 Raheem Y K.Suman Computer

154
Q5.(a) What do you understand
by Degree and Cardinality of a table?2

Answer:
Degree of a table is total number of
attributes.
Cardinality of a table is total number
of rows.

MODEL PAPER 2 FOR 2008-09: b1)Write SQL commands for the


following statements: 4
5.(a)What do you understand by
Primary Key & Candidate Keys? 2 (i) To display details of all the items in
the Store table in ascending order of
Answer: LastBuy.
Ans. SELECT * FROM STORE ORDER
An attribute or set attributes which BY LastBuy;
are used to identify a tuple uniquely is
known as Primary Key. If a table has (ii) To display ItemNo and Item name
more than one such attributes which of those items from Store table whose
identify a tuple uniquely than all such Rate is more than 15 Rupees.
attributes are known as Candidate Ans.
Keys. SELECT ItemNo, Item..In FROM
STORE WHERE Rate >15;
S)
C
T

(iii) To display the details of those


12.STRUCTURED
G
(P

items whose Supplier code (Scode) is


ar

QUERY LANGUAGE 22 or Quantity in Store (Qty) is more


m
Ku

than 110 from the table Store.


er

Ans.
nd

DELHI 2010:
re

SELECT * FROM STORE WHERE


Vi

5.b) Consider the following tables Scode = 22 OR Qty >110;


STORE and SUPPLIERS and answer
(bl) and (b2) parts of this question: (iv) To display Minimum Rate of items
for each Supplier individually as per
Scode from the table Store.
Ans. SELECT Scode, MIN(Rate) FROM
STORE GROUP BY Scode;

b2)Give the output of the following


SQL queries: 2
Note: In all output Questions ignore
Column Headings

(i) SELECT COUNT(DISTINCT Scode)


FROM Store;
Ans. COUNT(DISTINCT Scode)

(ii) SELECT Rate*Qty FROM Store


WHERE ItemNo=2004;
Ans.
RATE*QTY
880
155
(ii) To display ItemNo and Item name
(iii) SELECT Item,Sname FROM Store of those items from Store table whose
S, Suppliers P WHERE Rate is more than 15 Rupees.
S.Scode=P.Scode AND ItemNo=2006; Ans. SELECT ItemNo, Item..In FROM
Ans. ITEM SNAME Gel Pen Classic STORE WHERE Rate >15;
Premium Stationers
(iii) To display the details of those
(iv) SELECT MAX(LastBuy) FROM items whose Supplier code (Scode) is
Store; 22 or Quantity in Store (Qty) is more
Ans. than 110 from the table Store.
MAX (LASTBUY) Ans. SELECT * FROM STORE WHERE
24-Feb-10 Scode = 22 OR Qty >110;

OUTSIDE DELHI 2010: (iv) To display Minimum Rate of items


for each Supplier individually as per
5.b) Consider the following tables Scode from the table Store.
STORE and SUPPLIERS and answer Ans. SELECT Scode, MIN(Rate) FROM
(bl) and (b2) parts of this question: STORE GROUP BY Scode;

(b2) Give the output of the following


SQL queries: 2
Note: In all output Questions ignore
Column Headings
S)

(i) SELECT COUNT(DISTINCT Scode)


C

FROM Store;
T
G
(P

Ans. COUNT (DISTINCT Scode)


ar
m
Ku

(ii) SELECT Rate*Qty FROM Store


er

WHERE ItemNo=2004;
nd
re

Ans. RATE*QTY
Vi

880

(iii) SELECT Item,Sname FROM Store


S, Suppliers P WHERE
S.Scode=P.Scode AND ItemNo=2006;
Ans. ITEM SNAME Gel Pen Classic
Premium Stationers

(iv) SELECT MAX(LastBuy) FROM


Store;
Ans. MAX (LASTBUY)
(b1) Write SQL commands for the 24-Feb-10
following statements: 4
DELHI 2009:
(i) To display details of all the items in
the Store table in ascending order of (b) Consider the following tables
LastBuy. GARMENT and FABRIC. Write SQL
Ans. SELECT * FROM STORE ORDER commands for the statements (i) to (iv)
BY LastBuy; and give outputs for SQL queries (v) to
(viii) 6

156
GARMENT table. (Display FCODE of
each GARMENT along with highest
and lowest price)
Ans SELECT FCODE, MAX (PRICE),
MIN(PRICE) FROM GARMENT GROUP
BY FCODE;

(v) SELECT SUM (PRICE) FROM


GARMENT WHERE FCODE = ‘F01’ ;
Ans SUM (PRICE)
26:10

(vi) SELECT DESCRIPTION, TYPE


FROM GARMENT, FABRIC WHERE
GARMENT.FCODE = FABRIC.FCODE
AND GARMENT. PRICE > = 1260 ;
Ans) DESCRIPTION TYPE
INFORMAL SHIRT COTTON
INFORMAL PANT COTTON
FORMAL PANT TERELENE

(vii) SELECT MAX (FCODE) FROM


FABRIC;
Ans MAX (FCODE)
S)

F04
C
T
G
(P

(viii) SELECT COUNT (DISTINCT


(i) To display GCODE and
ar

PRICE) FROM GARMENT ;


m

DESCRIPTION of each GARMENT in


Ku

Ans COUNT(DISTINCT PRICE)


descending order of GCODE
er

7
nd

Ans SELECT GeODE, DESCRIPTION


re
Vi

FROM GARMENT ORDER BY GCODE


OUTSIDE DELHI 2009:
DESC;
(b) Consider the following tables
(ii) To display the details of all the
DRESS and MATERIAL. Write SQL
GARMENTs, which have READYDA TE
commands for the statements (i) to (iv)
in between 08-DEC-07 and 16-JUN-
and give outputs for SQL queries (v) to
08(inclusive of both the dates).
(viii). 6
Ans) SELECT * FROM GARMENT
WHERE READYDATE BETWEEN’ 08-
DEC-07’AND , 16-JUN-08’ ;
OR
SELECT * FROM DRESS WHERE
LAUNCHDATE >= ‘08-DEC-07’
AND LAUNCHDATE<=’16-JUN-08’;

(iii) To display the average PRICE of


all the GARMENTs, which are made
up of FABRIC with FCODE as F03.
Ans) SELECT AVG (PRICE) FROM
GARMENT WHERE FCODE = ‘F03’;

(iv) To display FABRIC wise highest


and lowest price of GARMENTs from
157
Ans DESCRIPTION TYPE
(NO OUTPUT)

(vii) SELECT MAX(MCODE) FROM


MATERIAL;
Ans MAX (MCODE)
MOO4

(viii) SELECT COUNT(DISTINCT


PRICE) FROM DRESS;
Ans COUNT(DISTINCT PRICE)
(i) To display DCODE and 6
DESCRIPTION of each dress in
ascending order of DCODE. Delhi 2008:
Ans SELECT DCODE. DESCRIPTION
FROM DRESS ORDER BY DCODE ; 5.b) Consider the following tables
Product and Client. Write SQL
(ii) To display the details of all the commands for the statement (i) to (iv)
dresses which have LAUNCHDATE in and give outputs for SQL queries (v) to
between 05-DEC’-07 and 20-JUN-08 (viii)
(inclusive of both the dates).
Ans SELECT * FROM DRESS WHERE Table: PRODUCT
LAUNCHDATE BETWEEN ‘05-DEC-07’
AND ’20-JUN-08’ P_ID Product Manuf Price
S)

OR Name acture
C

r
T

SELECT * FROM DRESS WHERE


G
(P

LAUNCHDATE >= ‘05-DEC-07’ AND TP01 Talcom LAK 40


ar

Powder
m

LAUNCHDATE<= ’20-JUN-08’
Ku

FW05 Face Wash ABC 45


er

BS01 Bath Soap ABC 55


nd

(iii) To display the average PRICE of


re

all the dresses which are made up of SH06 Shampoo XYZ 120
Vi

material with MCODE as M003. FW12 Face Wash XYZ 95


Ans SELECT AVG(PRICE) FROM
GARMENT WHERE MCODE = ‘M003’ Table: CLIENT

(iv) To display materialwise highest C_ID Client Name City P_ID


01 Cosmetic Delhi FW05
and lowest price of dresses from
Shop
DRESS table. (Display MCODE of each 06 Total Health Mumbai BS01
dress along with highest and lowest 12 Live Life Delhi SH06
price) 15 Pretty Woman Delhi FW12
Ans SELECT MCODE, MAX(PRICE), 16 Dreams Banglore TP01
MIN (PRICE) FROM DRESS GROUP
BY MCODE (i) To display the details of those
Clients whose city is Delhi.
(v) SELECT SUM(PRICE) FROM Ans: Select all from Client where
DRESS WHERE MCODE=‘M001’; City=”Delhi”
Ans SUM(PRICE)
2700 (ii)To display the details of Products
whose Price is in the range of 50 to
(vi) SELECT DESCRIPTION, TYPE 100 (Both values included).
FROM DRESS, MATERIAL WHERE Ans: Select all from product where
DRESS.DCODE = MATERIAL.MCODE Price between 50 and 100
AND DRESS.PRICE>=l250;
158
(iii) To display the ClientName, City OUTSIDE DELHI 2008:
from table Client, and ProductName
and Price from table Product, with 5.b) Consider the following tables
their corresponding matching P_ID. Item and Customer. Write SQL
Ans: Select ClientName,City, commands for the statement (i) to (iv)
ProductName, Price from and give outputs for
Product,Client where SQL queries (v) to (viii)
Product.P_ID=Client.P_ID.
Table: ITEM
(iv) To increase the Price of all I_ID Item Man Price
Products by 10 Name ufact
Ans: urer
Update Product Set Price=Price +10 PC01 Personal ABC 35000
Computer
(v)SELECT DISTINCT Address FROM LC05 Laptop ABC 55000
Client. PC03 Personal XYZ 32000
Ans: ( The above question may consist Computer
DISTINCT City. If it is DISTINCT City, PC06 Personal COM 37000
the following is the answer) Computer P
LC03 Laptop PQR 57000
City Table: CUSTOMER
----- C_I Customer City I_ID
Delhi D Name
Mumbai 01 N.Roy Delhi LC03
S)

Bangalore 06 H.Singh Mumbai PC03


C
T

12 R.Pandey Delhi PC06


G
(P

(vi)SELECT Manufacturer, MAX(Price), 15 C.Sharma Delhi LC03


ar

Min(Price), Count(*) FROM Product


m

16 K.Agarwal Banglore PC01


Ku

GROUP BY Manufacturer;
er

Ans:
nd

(i) To display the details of those


re

Manufacturer Max(Price) Min(Price) Count(*)


Vi

LAK 40 40 1 Customers whose city is Delhi.


ABC 55 45 2 Ans: Select all from Customer Where
XYZ 120 95 2
City=”Delhi”
(vii)SELECT ClientName,
(ii)To display the details of Item whose
ManufacturerName FROM Product,
Price is in the range of 35000 to
Client WHERE
55000 (Both values included).
Client.Prod_Id=Product.P_Id;
Ans: Select all from Item Where
Ans: ClientName ManufacturerName
Cosmetic Shop ABC
Price>=35000 and Price <=55000
Total Health ABC
Live Life XYZ (iii)To display the CustomerName,
Pretty Woman XYZ City from table Customer, and
Dreams LAK ItemName and Price from table Item,
with their corresponding matching
(viii)SELECT ProductName, Price * 4 I_ID.
FROM Product. Ans: Select
ProductName Price*4 CustomerName,City,ItemName, Price
Talcom Poweder 160 from Item,Customer where
Face Wash 180 Item.I_ID=Customer.I_ID.
Bath Soap 220
Shampoo 480 (iv) To increase the Price of all Items
Face Wash 380 by 1000 in the table Item.

159
Ans: Update Item set ND08 ND02 P 16/j,Moore New
Dhingra Enclave Delhi
Price=Price+1000 KO19 MU15 A P Roy 2A,Central Kolkata
/avenue
(v)SELECT DISTINCT City FROM MU32 ND02 S mittal P 245, AB Mumbai
Colony
Customer.
ND48 MU50 B P jain 13,Block New
Ans: City d,a,viha Delhi
Delhi
Mumbai (i)To display the names of all
Bangalore consignors from Mumbai.
(vi)SELECT ItemName, MAX(Price), Ans: Select CnorName from Consignor
Count(*) FROM Item GROUP BY where city=”Mumbai”;
ItemName;
Ans: ItemName Max(Price) Count(*) (ii)To display the cneeID, cnorName,
Personal Computer 37000 3 cnorAddress, CneeName,
Laptop 57000 2
CneeAddress for every Consignee.
(vii)SELECT CustomerName, Ans: Select CneeId, CnorName,
Manufacturer FROM Item, Customer CnorAddress, CneeName,
WHERE CneeAddress from
Item.Item_Id=Customer.Item_Id; Consignor,Consignee where
Ans: CustomerName ManufacturerName Consignor.CnorId=Consignee.CnorId;
N.Roy PQR
H.Singh XYZ (iii)To display the consignee details in
R.Pandey COMP
C.Sharma PQR
ascending order of CneeName.
K.Agarwal ABC Ans: Select * from Consignee Orderby
S)

CneeName Asc;
C

(viii)SELECT ItemName, Price * 100


T
G
(P

FROM Item WHERE Manufacturer = (iv)To display number of consignors


ar

‘ABC’; from each city.


m
Ku

Ans: ItemName Price*100 Ans: Select city, count(*) from


er

Personal Computer 3500000 Consignors group by city;


nd

Laptop 5500000
re

(v)SELECT DISTINCT City FROM


Vi

CONSIGNEE;
Outside Delhi 2007:
Ans:
CneeCity
5.b) Consider the following tables
Consignor and Consignee. Write SQL Mumbai
command for the statements(i)to(iv) New Delhi
And give outputs for the SQL quries (v) Kolkata
to ( viii). 6
(vi) SELECT A.CnorName A, B.CneeName
B FROM Consignor A, Consignee B
TABLE : CONSIGNOR
WHERE A.CnorID=B.CnorID AND
B.CneeCity=’Mumbai’;
CnorI CnorNam CnorAddress City
Ans)
D e
ND01 R singhal 24,ABC Enclave New Delhi
ND02 Amit 123,Palm Avenue New Delhi
Kumar
MU15 R Kohil 5/A,South,Street Mumbai
MU50 S Kaur 27-K,Westend Mumbai
(vii)SELECT CneeName,CneeAddress
FROM Consignee WHERE CneeCity
TABLE : CONSIGNEE Not IN (‘Mumbai’, ‘Kolkata’);
Ans:
CneeI CnorID CneeNa CneeAddre CneeCit
D me ss y CneeName CneeAddress
MU05 ND01 Rahul 5,Park Mumbai P Dhingra 16/J,Moore Enclave
Kishore Avenue
160
B P Jain 13,Block D,A Vihar
(iii)To display the sender details in
(viii) SELECT CneeID, CneeName ascending order of SenderName.
FROM Consignee WHERE CnorID =
‘MU15’ OR CnorID = ‘ND01’; Ans: Select * from Sender order by
SenderName;
Ans: CneeID CneeName
MU05 Rahul Kishore (iv)To display number of Recipients
KO19 A P Roy from each city.

Delhi 2007: Ans: Select RecCity,Count(*) from


Recipient group by RecCity;
5.b)Consider the following tables.
Write SQL command for the (v) SELECT DISTINCT SenderCity
statements (i)to(iv)and give outputs for FROM Sender;
the SQL quries (v) to (viii). 6 Ans:
senderCity
TABLE : SENDER New Delhi
Mumbai
Sende Sende Sender Sender
rID rName Address City (vi) SELECT A.SenderName A,
ND01 R jain 2,ABC Appts New Delhi B.RecName FROM Sender A,
MU02 H sinha 12, Newton Mumbai Recipient B WHERE A.SenderID=B.
MU1 S haj 27/ A,Park New Delhi SenderID AND B.RecCity=’Mumbai’;
5 Street
S)

ND5 T Prasad 122-K,SDA Mumbai


Ans: SenderName RecName
C

R.Jain H.Singh
T

0
G
(P

S.Jha P.K.Swamy
ar

TABLE :RECIPIENT
m
Ku

(vii)SELECT RecName,RecAddress
er

FROM Recipient WHERE RecCity Not


nd

RecI Sen ReCNam RecAdd ReC


re

D derI e ress City IN (‘Mumbai’, Kolkata’);


Vi

D Ans: RecName RecAddress


KO05 ND01 R Bajpayee 5,Central Kolkat S Mahajan 116, A Vihar
Avenue a S Tripati 13, B1 D, Mayur Vihar
ND08 MU02 S Mahajan 116, A New
Vihar Delhi
MU19 ND01 H sing 2A,Andheri Mumb
(viii) SELECT RecID, RecName FROM
East ai Recipient WHERE SenderID = ‘MU02’
MU32 MU15 P K swamy B5, CS Mumb OR SenderID = ‘ND50’;
Terminus ai
ND48 ND50 S Tripathi 13, B1 New
Ans: RecID RecName
D,Mayur Delhi ND08 S Mahajan
Vihar ND48 S Tripathi

(i)To display the names of all senders OUTSIDE DELHI 2006:


from Mumbai.
Ans: Select * from Sender where 5.b) Study the following tables
SenderCity=’Mumbai’; FLIGHTS and FARES and write SQL
commands for the questions (i) to (iv)
(ii)To display the recID, senderName, and give outputs for SQL quires (v)
senderAddress, RecName, RecAddress to(vi).
for every recipt.
Ans: Select recID, SenderName,
SenderAddress, RecName, RecAddress
from Sender, Recipient where
Sender.Senderid=Recipient.RenderId;
161
Starting=”DELHI” AND
Ending=”MUMBAI”

TABLE: FLIGHTS (iv) Display the minimum fare “Indian


Airlines” is offering from the tables
FARES.
Ans: Select min(FARE) from FARES
Where AIRLINES=”Indian Airlines”

v)Select FL_NO,NO_FLIGHTS,
AIRLINES from FLIGHTS, FARES
Where STARTING = “DELHI” AND
FLIGHTS.FL_NO = FARES.FL_NO
Ans:

TABLE:FARES

(vi) SELECT count (distinct ENDING)


from FLIGHTS.
S)

Ans: 7
C
T
G
(P

DELHI 2006:
ar
m
Ku

5.b) Study the following tables


er

DOCTOR and SALARY and write SQL


nd
re

commands for the questions (i) to (iv)


Vi

(i) Display FL_NO and NO_FLIGHTS and give outputs for SQL queries (v) to
from “KANPUR” TO “BANGALORE” (vi) :
from the table FLIGHTS. TABLE: DOCTOR
Ans: Select FL_NO, NO_FLIGHTS
from FLIGHTS where
Starting=”KANPUR” AND
ENDING=”BANGALORE”

(ii) Arrange the contents of the table


FLIGHTS in the ascending order of
FL_NO.
Ans:
SELECT * FROM FLIGHTS ORDER BY
FL_NO;

(iii) Display the FL_NO and fare to be


paid for the flights from DELHI to
MUMBAI using the tables FLIGHTS
and FARES, where the fare to be paid
= FARE+FARE+TAX%/100.
Ans: Select FL_NO, FARE+FARE+(TAX
%/100) from FLIGHTS, FARES where
162
TABLE: SALARY
(5) Consider the following tables
EMPLOYEES and EMPSALARY. write
SQL commands for the Statements (i)
to (iv) and give outputs for SQL quires
(v) to (viii).

EMPLOYEES

(i) Display NAME of all doctors who


are in “MEDICINE” having more than
10 years experience from the Table
DOCTOR.
Ans: Select Name from Doctor where
Dept=”Medicine” and
Experience>10

(ii) Display the average salary of all


doctors working in “ENT”department EMPSALRAY
using the tables DOCTORS and
S)
C

SALARY Salary =BASIC+ALLOWANCE.


T
G

Ans: Select avg(basic+allowance) from


(P
ar

Doctor,Salary where Dept=”Ent” and


m

Doctor.Id=Salary.Id
Ku
er
nd

(iii) Display the minimum


re
Vi

ALLOWANCE of female doctors.


Ans: Select min(Allowance) from
Doctro,Salary where Sex=”F” and
Doctor.Id=Salary.Id

(iv) Display the highest consultation


fee among all male doctors.
Ans: Select max(Consulation) from (i) To display Firstname, Lastname,
Doctor,Salary where Sex=”M” and Address and City of all employees
Doctor.Id=Salary.Id living in Paris from the table
EMPLOYEES.
(v) SELECT count (*) from DOCTOR Ans: Select
where SEX = “F” Firstname,Lastname,Address,City
Ans: 4 from Employees where City=”Paris”
(vi) SELECT NAME, DEPT , BASIC (ii) To display the content of
from DOCTOR, SALRY Where DEPT = EMPLOYEES table in descending
“ENT” AND DOCTOR.ID = SALARY.ID order of FIRSTNAME.
Ans: Name Dept Basic
Ans: Select * from Employees Order
Jonah Ent 12000
By Firstname Desc

DELHI 2005:
163
(iii) To display the Firstname,
Lastname, and Total Salary of all
managers from the tables, where Total
Salary is calculated as Salary+Benifts.
Ans: Select
Firstname,Lastname,Salary+Benefits
from Employees, Empsalary where
Designation=”Manager” and
Employees.EmpId=EmpSalary.EmpId

(iv) To display the Maximum salary


among Managers and Clerks from the
table EMPSALARY.
Ans: Select Designation,max(Salary)
from EmpSalary where DESIG
Designation=”Manager” or
Designation=”Clerk”

(v) SELECT FIRSTNAME,SALARY


FROM EMPLOYEES,EMPSALARY
WHERE DESTINATION
=’Salesman’ AND
EMPOLYEES.EMPID=EMPSALARY.EMPID;
Ans: Firstname Salary
Rachel 32000
S)
C

Peter 28000
T
G
(P
ar

(vi) SELECT COUNT (DISTINT


m

(i) To display W_ID Firstname, address


Ku

DESIGNATION ) FROM EMPSALARY


and City of all employees living in New
er

Ans: 4
nd

York from the Table WORKERs


re

Ans: select W_ID


Vi

(vii) SELECT DESIGNATION ,


SUM(SALARY) ,firstname,address,city from workers
FROM EMPSALARY GROUP BY where city=”New York”
DESIGNATION HAVING COUNT(*)>2;
Ans: Designation Sum(Salary)
(ii) To display the content of workers
Manager 215000 table in ascending order of
Clerk 135000 LASTNAME.
Ans:Select * from Worker Order By
(viii)SELECT SUM (BENEFITS) FROM lastname Asc
EMPSALARY WHERE
DESIGNATION=’Clerk’; (iii) To display the FIRSTNAME,
Ans: 32000 LASTNAME and Total Salary of all
Clerks from the tables WORKERS And
OUTSIDE DELHI 2005: DESIG, where Total
salary is calculated as Salary +
5) Consider the following tables benifts.
WORKERS and DESIG. Write SQL Ans: Select firstname, lastname,
commands for the statements (i) to (iv) salary+benefits where
and give outputs for SQL queries (v) to worker.w_id=desg.w_id and
(viii). Designation=”Clerk”

164
(iv) To display the minimum salary
among managers and Clerks from the
tables DESIG.
Ans:
SELECT MIN(SALARY), DESIGNATION
FROM DESIG WHERE
DESIGNATION IN ('Manager'.'Clerk')
GROUP BY DESIGNATION;
OR
SELECT MIN(SALARY), DESIGNATION
FROM DESIG WHERE
DESIGNATION= ‘Manager’ OR
DESIGNATION='Clerk' GROUP BY
DESIGNATION;
TABLE:ISSUED
OR
SELECT MIN(SALARY) FROM DESIG
WHERE DESIGNATION=
‘Manager’ OR DESIGNATION='Clerk';
OR
SELECT MIN(SALARY) FROM DESIG
WHERE DESIGNATION IN
(‘Manager’,‘Clerk’);

(v) SELECT FIRSTNAME, SALARY Write SQL queries from b to g.


S)

FROM WORKERS, DESIG WHERE (b)To show Book name, Author name
C

DESIGINATION = “MANAGER” AND


T

and Price of books of EPB publisher.


G
(P

WORKERS.W_ID = DESIGN.W_ID Ans: select Book_name,Author_name,


ar

Ans: FIRSTNAME SALARY price from books where Publisher


m
Ku

Sam 75000 =”EPB”


er

Manila 70000
nd
re

George 75000 (c) To list the names of the books of


Vi

(vi)SELECT COUNT(DISTINCT FICTIONS type.


DESIGNATION) FROM DESIGN ; Ans: Select Book_name from books
Ans: 4 where type=”FICTION”
(vii) SELECT DESIGNATION,
SUM(SALARY) FROM DESIG GROUP (d) To display the names and prices of
BY DESIGNATION HAVING COUNT (*) the books in descending order of their
< 3; price.
Ans: Designation Sum(Salary) Ans: Select Book_name, price from
Director 85000 books order by price desc;
Salesman 60000
(e) To increase the price of all books of
(viii) SELECT SUM(BENIFTS) FROM First Pub.by 50.
DESIG WHERE DESIGINATION Ans: update books set price= price+50
=”salesman”; where publishers = “First Publ”
Ans: 15000
(f) To Display the Book_ID,
2004: Book_Name and Quantity Issued for
all books Which have been issued.
5. Give the following table for Ans:Select Book_ID, Book_Name,
database a LIBRARY. Quantity_Issued from Books,Issued
TABLE : BOOKS where Books.BookId=Issued.BookId;

165
(g) To insert a new row in the table
Issued having the following data:
“F0002”,4
Ans: insert into Issued
values(“F0002”,4)

(h) Give the output of the following


queries on the above tables: (b) To show all information about the
sofas from the INTERIORS table.
(i) Select Count(Distinct Publishers) Ans: Select * from INTERIORS where
From Books type= “sofa”
Ans: 3
(d) To list ITEMNAME and TYPE of
(ii) Select Sum(Price) From Books those items, in which DATEOFSTOCK
Where Quantity>5 is before 22/01/02 from the
Ans: 1350 INTERIORS table in descending order
(iii) Select Book_Name,Author_Name of ITEMNAME.
From Books Where Price<500 Ans: Select Itemname,Type From
Ans: Book_Name Author_Name Interiors Where
My First C++ Brian & Brooks Dateofstock<{22/01/02} order by
C++ Brainworks A.W.Rossaine Itemname
Fast Cook Lata Kapoor
(iv) Select Count(*) From Books
(e) To display ITEMNAME and
Ans: 5
DATEOFSTOCK of those items in
S)

which the Discount percentage is


2003:
C

more than 15 from INTERIORS.


T
G
(P

Ans: Select Itemname,Dateofstock


5.b Write SQL commands for (b) to (g)
ar

from Interiors Where Discount>15


m

and write the outputs for


Ku

(h) on the basis of tables TNTERIORS


er

(f) To count the number of items


nd

and NEWONES.
re

whose type is “Double bed”;


Vi

TABLE: INTERIORS
Ans: Select Count(*) from Interiors
Where Type=”Double Bed”

(g) To insert new row in the


NEWONES table with the following
data:
14, “True Indian “, “Office Table “,
{28/03/03},15000,20
Ans: Insert into Newones
values(14,”True Indian”,”Office
Table”,”{28/03/03},15000,20)

(h) Give the outputs for the following


SQL statements.

(i) Select COUNT (distinct TYPE) from


INTERIORS;
TABLE:NEWONES Ans: 5

(ii) Select AVG(DISCOUNT)from


INTERIORS where TYPE =”Baby cot”;
Ans: 13
166
Ans: Insert into Teacher
(iii) Select SUM(price)from INTERIORS values ,”Mersha”, ”Computer”,
where {1/1/2000),12000,”M”);
DATEOFSTOCK<{12/02/02};
Ans: 53000 2001:

2002: 5.b) Write the SQL commands for (i) to


(vii) on the basis of the table SPORTS
5. Given the following Teacher
Relation. TABLE: SPORTS
Write SQL Commands fro (b) to (g)

(i) Display the names of the students


who have grade ‘C’ in either Game1 or
S)

Game2 or both.
C

(b) To select all the information of Ans: Select Name From Sports Where
T
G

teacher in computer department Grade1=”C” OR Grade2=”C”


(P
ar

Ans: Select * from Teacher where


m
Ku

Department=”Computer” (ii) Display the number of students


er

getting grade ‘A’ in Cricket.


nd

(c ) To list the name of female teachers


re

Ans: Select Count(*) from Sports


Vi

in History Department. Where (Game1=”Cricket” and


Ans: Select Name from Teacher Where Grade1=”A”) or (Game2=”Cricket” and
Sex=”F” And Department=”History” Grade2=”A”)

(d) To list all names of teachers with (iii) Display the names of the students
date of admission in ascending order. who have same game for both game1
Ans: Select Name from Teacher Order and game2
By Dateofjoining Asc Ans: Select Name From Sports Where
Game1=Game2
(e) To display Teacher's Name,
Department, and Salary of female (iv) Display the games taken up by the
teachers students, whose name starts with ‘A’.
Ans: Select Name,Department,Salary Ans: Select Game1,Game2 From
from Teacher Where Sex=”F” Sports Where Name Like “A%”

(f)To count the number of items whose (v) Add a new column named ‘marks’.
salary is less than 10000 Ans: Alter Table Sports Add Marks
Ans: Select Count(*) from Teacher Number(5);
Where Salary<10000
(g) To insert a new record in the (vi) Assign a value 200 for marks for
Teacher table with the following data: all those who are getting grade ‘B’ or
8,”Mersha”,”Computer”, ‘A’ in both Game1 and Game2.
(1/1/2000),12000,”M”.
167
Ans: (Children, Try This Answer as an (f) Give the output of the following
assignment) SQL statements:

(vii) Arrange the whole table in the (i) select COUNT (distinct
alphabetical order of name. SPORTS)from CLUB;
Ans: Select * from Sports Order By Ans: 4
Name
(ii) select MIN(AGE) from CLUB where
2000 : SEX =”F”;
Ans: 34
5. Write SQL commands for the (b) to
(e) and write the outputs for (g) on (iii) select AVG(PAY) fromCLUB where
thse basis of table CLUB. SPORTS = “KARATE”;
Ans: 1100
TABLE: CLUB
(iv) select SUM(PAY) from CLUB where
DATAOFAPP>{31/01/98};
Ans: 7800

(G) Assuming that there is one more


table COACHES in the database as
shown below:

TABLE:COACHES
S)
C
T
G
(P
ar
m
Ku

(b) To show all information about the


er
nd

swimming coaches in the club.


re

Ans: Select * from Club


Vi

(c) To list names of all coaches with


their date of appointment (DATOFAPP)
in descending order.
Ans: Select Coachname from Club What will be the output of the
order by Dataofapp desc following query:
SELECT SPORTS PERSON,
(d) To display a report, showing COACHNAME
coachname, pay, age and bonus(15% FROM CLUB,COACHES
of pay) for all coaches. WHERE COACH_ID=COACH_NO
Ans: Ans:
Select Coachname,Pay,Age,Pay*0.15
from Club

(e) To insert a new row in the CLUB


table with following data:
11,”PRAKASH”,37,”SQUASH”,
{25/02/98},2500,”M” 1999:
Ans: Insert into Club Values
(11,”PRAKASH”,37,”SQUASH”, 5.) Given the following Teacher
{25/02/98}, 2500,”M”) relation: Write SQL commands for
questions (b) to (g).

168
TEACHER

(b)To show all information about the


teachers of history department.
Ans:select * from teacher where
department=’history’;

(c) To list names of female teacher who (b) To select all the information of
are in math department. patients of all cardiology department.
Ans: select name from teacher where Ans: Select all from Hospital where
sex=’female’ and department=’maths’; department=”Cardiology”

d) To list names of all teacher with (c) To list the names of female patients
their date of joining in ascending who are in ent department.
Ans:select name from Hospital where
S)

order.
C

Ans:Select Name From Teacher order Department=”Ent” and Sex=”F”


T
G
(P

by dateofjoing;
(d) To list names of all patients with
ar
m

their date of admission in ascending


Ku

(f) To count the number of teachers


er

with age >23. order.


nd

Ans: Select count(name) from teacher Ans: Select name,dateofadm from


re
Vi

where age>23; Hospital dateofadm.

(g) To insert a new row in the teacher (e) To display patients name, charges,
table with the following data: age, for only female patients.
9, “raja’, 26, “computer”, {13/5/95 }, Ans: Select Name,Charges,age from
2300, “M”. Hospital where sex=”F”
Ans: Insert into Teacher
values(9,”raja”,26, (f) To count the number of patients
”computer”, {13/05/95},2300,”M”); with age
1998: <30.
Ans: Select count(*) from hospitals
5. Write SQL commands for (b) to (g) where age<30
and write the outputs for (h) on the
basis of table HOSPITAL. (g) To insert the new row in the
hospital table with the following data:
11, “aftab”, 24, “surgery”, {25/2/98},
300, “M”.
Ans: insert into Hospital values(11,
“aftab”, 24, “surgery”, {25/02/98},
300, “M”)

(h) Give the output of the following


SQL statements:
169
b) Write SQL commands for the
(i) Select count (distinct charges)from flowing statements: 4
hospital;
Ans: 5 (i) To display the names of all
activities with their Acodes in
(ii) Select min(age) from hospital descending order.
where sex = “f’; Ans) SELECT Acodes, ActivityName
Ans: 16 FROM ACTIVITY ORDER BY Acode
DESC;
(iii) Select sum(charges) from hospital
where department = “ent”; (ii) To display sum of PrizeMoney for
Ans: 750 the Activities played in each of the
Stadium
(iv) Select avg(charges) from hospital separately.
where date of admission is Ans) SELECT SUM(PrizeMoney),
<{12/02/98}; Stadium FROM ACTIVITY GROUP BY
Ans:380 Stadium;

MODEL PAPER 1 FOR 2009-10: (iii) To display the coach's name and
ACodes in ascending order of ACode
5.a)Consider the following tables from the table COACH
ACTIVITY and COACH and answer (b) Ans) SELECT Name, Acode FROM
and (c) parts of this question: COACH ORDER BY Acode;
S)

(iv) To display the content of the


C

Activity table whose ScheduleDate


T
G
(P

earlier than 01/01/2004 in ascending


ar

order of ParticipantsNum.
m
Ku

Ans) SELECT * FROM ACTIVITY


er

WHERE SchduleDate<'01-Jan-2004'
nd
re

ORDER BY ParticipantsNum;
Vi

c) Give the output of the following


SQL queries: 2

(i) SELECT COUNT(DISTINCT


ParticipantsNum) FROM ACTIVITY;
Ans) 3

(ii)SELECT MAX(ScheduleDate),
MIN(ScheduleDate) FROM ACTIVITY;
Ans) 19-Mar-2004 12-Dec-2003
(iii) SELECT Name,ActivityName
FROM ACTIVITY A,COACH C WHERE
A.Acode= C.Acode AND
A.ParticipantsNum = 10;
Ans) Ravinder Discuss Throw

(iv) SELECT DISTINCT Acode FROM


COACH;
Ans)
1001
1003
170
1008 Ans) SELECT SUM(Prizemoney),Type
FROM Games GROUP BY Type;
MODEL PAPER 2 FOR 2009-10:
c) Give the output of the following
SQL queries: 2
5.a) Consider the following tables
GAMES and PLAYER and answer (b) (i) SELECT COUNT(DISTINCT
and (c) parts of this question: Number) FROM GAMES;
Ans) 2

(ii) SELECT MAX(ScheduleDate),


MIN(ScheduleDate) FROM GAMES;
Ans) 19-Mar-2004 12-Dec-2003

(iii) SELECT Name, GameName FROM


GAMES G, PLAYER P
WHERE G.Gcode=P.Gcode AND
G.PrizeMoney>10000;
Ans) Ravi Sahai Lawn Tennis

(iv) SELECT DISTINCT Gcode FROM


PLAYER;
Ans) 3
S)

MODEL PAPER 1 FOR 2008-09:


C
T
G
(P

(b) Consider the following tables


ar

ACTIVITY and COACH. Write SQL


m
Ku

commands for the statements (i) to (iv)


er

b) Write SQL commands for the and give outputs for SQL queries (v) to
nd

flowing statements: 4
re

(viii) 6
Vi

(i) To display the name of all GAMES


with their GCodes
Ans) SELECT GameName,Gcode
FROM GAMES;

(ii) To display details of those GAMES


which are having PrizeMoney more
than
7000.
Ans) SELECT * FROM Games WHERE
Prizemoney>7000;

(iii) To display the content of the


GAMES table in ascending order of
Schedule
Date.
Ans) SELECT * FROM Games ORDER i)To display the name of all activities
BY ScheduleDate; with their Acodes in descending order.

(iv) To display sum of PrizeMoney for Answer: SELECT ActivityName, ACode


each Type of GAMES FROM ACTIVITY ORDER BY Acode
DESC;
171
5.(b) Consider the following tables
(ii) To display sum of PrizeMoney for GAMES and PLAYER. Write SQL
each of the Number of participants commands for the statements (i) to (iv)
groupings (as shown in column and give outputs for SQL queries (v) to
ParticipantsNum 10,12,16) (viii) 6

Answer: SELECT SUM(PrizeMoney),


ParticipantsNum FROM ACTIVITY
GROUP BY ParticipantsNum;

(iii) To display the coach’s name and


ACodes in ascending order of ACode
from the table COACH

Answer: SELECT Name, ACode FROM


COACH ORDER BY ACode;

(iv) To display the content of the


ACTIVITY table whose ScheduleDate
earlier than 01/01/2004 in ascending
order of ParticipantsNum.

Answer: SELECT * FROM ACTIVITY


WHERE ScheduleDate<’01-Jan-2004’
S)

ORDER BY ParticipantsNum;
C

i)To display the name of all Games


T
G

with their Gcodes


(P

v)SELECT COUNT(DISTINCT
Answer:
ar

ParticipantsNum) FROM ACTIVITY;


m
Ku

SELECT GameName,Gcode FROM


er

Answer: GAMES;
nd

(ii)
re

3 To display details of those


Vi

games which are having PrizeMoney


(vi)SELECT MAX(ScheduleDate), more than 7000.
MIN(ScheduleDate) FROM ACTIVITY; Answer:
SELECT * FROM GAMES WHERE
Answer: PrizeMoney>7000

19-Mar-2004 12-Dec-2003 (iii) To display the content of the


GAMES table in ascending order of
(vii) SELECT SUM(PrizeMoney) ScheduleDate.
FROM ACTIVITY; Answer:
SELECT * FROM GAMES ORDER BY
Answer: 54000 ScheduleDate;

(viii) SELECT DISTINCT iv)To display sum of PrizeMoney for


ParticipantsNum FROM ACTIVITY; each of the Number of participation
groupings (as shown in column
Answer: 16 Number 2 or 4)
10
12 Answer: SELECT
SUM(PrizeMoney),Number FROM
MODEL PAPER 2 FOR 2008-09: GAMES GROUP BY Number;

172
v)SELECT COUNT(DISTINCT Number) (a) X+XY=X
FROM GAMES; (b)X(X+Y)+X
Answer: 2
(9) Third distributive Law: X+ Y=X+Y
(vi)SELECT MAX(ScheduleDate),
MIN(ScheduleDate) FROM GAMES; (10) Demorgan’s Theorems
Answer: 19-Mar-2004 12-Dec-2003 (a)
(b)
(vii)SELECT SUM(PrizeMoney) FROM
GAMES; DELHI 2010:
Answer: 59000
6. (a)Verify the following algebraically2
(viii) SELECT DISTINCT Gcode FROM (A’+B’).(A +B)=A’.B+A.B’
PLAYER;
Answer: 101 Ans. LHS
103 (A’ +B’ ) . (A+B)
108 = A’.A + A’.B + A.B’ + B’.B
= 0 + A’.B + A.B’+ 0
= A’.B + A.B’
13. Boolean Algebra = RHS (Verified)

(b) Write the equivalent Boolean


Laws: Expression for the following Logic
circuit: 2
(1)Properties of 0 and 1:
S)
C

0 + X = X,
T
G

1 + X = 1,
(P

0.X = 0,
ar
m

1.X = X
Ku
er
nd

(2) Idempotence Law:


re
Vi

(a)X +X = X
(b)X.X = X

(3) Involution Law: =A Ans. (P + Q’) . (Q + R’)

(4)ComplementaryLaw: (c) Write the POS form of a Boolean


function H, which is represented in a
(a)X + =1
truth table as follows:
(b)X. =0

(5)Commutative Law:
(a) X+Y =Y+X
(b)X.Y=Y.X

(6) Associative Law:


(a)X + (Y+Z)=(X+Y)+Z
(b)X.(Y.Z)=(X.Y).Z

(7) Distributive Law:


(a) X(Y+Z)=XY+XZ
(b) X+YZ=(X+Y)(X+Z)

(8) Absorption Law: Ans.


173
= 1.(X+Y).(X’ +Y’).1
(X + Y + Z’).(X’+ Y + Z’) . (X’+ Y’+ Z) = (X+Y).(X’+Y’)
OR = R.H.S.
H(X,Y,Z) = (1, 5, 6)
(b) Write the equivalent Boolean
(d) Reduce the following Boolean Expression for the following Logic
Expression using K-Map : 3 Circuit: 2

Ans.

F(U, V, W, Z) = (3, 5, 7, 10, 11, 13, 15)

Ans. (U’+V) . (V’+W)

(c) Write the SOP form of a Boolean


function G, which is represented in a
truth table as follows: 1
S)
C
T
G
(P
ar
m
Ku
er
nd
re
Vi

OUTSIDE DELHI 2010:


Ans)
6 (a)Verify the following algebraically:2 G(P,Q,R)=P’.Q.R’+P’.Q.R+P.Q’.R’+P.Q.R’+P.Q.R
OR
X’.Y + X.Y’ = (X’+Y’).(X+Y) G(P,Q,R) = (2,3,4,6,7)

Ans. R. H . S (d) Reduce the following Boolean


(X’+y’).(x+y) Expression using K-Map : 3
= x’.(x+y)+y’.(x+y) F (A,B,C,D) = (3,4,5,6, 7,13,15)
= x.x’+X’.y+y’.x+y’.y
= x’.y+y’.X
= x’.y+x.y’
So L.H.S=R.H.S

OR

L.H.S.
X’.Y + X.Y’
= (X’.Y+X) (X’.Y+Y’)
= (X’+X).(Y+X).(X’+Y’).(Y+Y’)
174
(c) Write the POS form of a Boolean
function H, which is represented in a
truth table as follows: 1

Ans)

F(A,B,C,D) = A’B + BD + A’CD


Ans)
DELHI 2009: (A+B+C).(A’+B+C’).(A’+B’+C)
S)
C

OR
T
G

6. (a) Verify X’Y + X.Y’ + X’Y’ = (X’ + Y’) H(A,B,C) = n (0, 5, 6)


(P
ar

using truth table. 2


m
Ku

(d) Reduce the following Boolean


er

Ans) Expression using K-Map : 3


nd
re
Vi

(b) Write the equivalent Boolean


Expression for the following Logic
Circuit: 2 F (P,Q,R,S = PQR’+R+ P’R

OUTSIDE DELHI 2009:

6. (a) State and verify absorption law


using truth table. 2

175
(b) Write the equivalent Boolean
Expression for the following Logic
S)

Circuit: 2
C
T
G
(P
ar
m
Ku
er
nd
re
Vi

(c) Write the POS form of a Boolean


function G, which is represented in a
truth table as follows: 1

2008 Outside Delhi:

6. (a) State and Verify Absorption law


in Boolean Algebra. 2

Ans)

176
OR
OR
Vi
re
nd
er
Ku

177
m
ar
(P
G
T
C
S)

OR
OR
OR
2008 Delhi:

6. (a) State and verify De Morgan’s law


in Boolean Algebra. 2

Ans)

(b) Draw a logical circuit diagram for


the following Boolean Expression:1
A.(B+C’)

Ans)

(c) Convert the following Boolean


S)

expression into its equivalent


C

Canonical Product of sum form (POS): (b) Draw a Logical Circuit Diagram for
T
G

A.B’C + A’.B.C + A’.B.C’. 2 the following Boolean Expression. 1


(P

X’.(Y’+Z)
ar
m
Ku

Ans)
er
nd
re
Vi

(c) Convert the following Boolean


expression into its equivalent
(d) Reduce the following Boolean Canonical Sum of Product Form
expression using K-map: 3 (SOP):
F(A,B,C,D) = ∑(0,1,2,,4,5,8,9,10,11) 2 (X’+Y+Z’).(X’+Y+Z).(X’+Y’+Z).
(X’+Y’+Z’)

Ans)

(d) Reduce the following Boolean


Expression using K-map. 3
F(A,B,C,D) = ∑(0,2,3,4,6,7,8,10,12)
178
following sum of product
Ans) expression: 2

F(X, Y,Z) = ∑ (0, 2,4,5)

Ans)

F(X, Y, Z) = p (1, 3, 6, 7)
OR
F=(X+Y+Z’)(X+Y’+Z’)(X’+Y’+Z)(X’+Y’+Z’)

(c) Write the equivalent Boolean


expression for the following logic
circuit 2

2007 Outside Delhi:

6. (a) State De Morgan’s Theorems


and verify the same using truth table.
2

Ans)
Ans)
F=A.B’+C’.D
S)
C
T
G
(P

(d) Reduce the following Boolean


ar
m

expression using K – Map : 2


Ku
er
nd

F(A, B, C, D,) = Π (5, 6, 7, 8, 9, 12,


re

13, 14, 15)


Vi

Ans)

OR

(b) Write the equivalent canonical


product of sum expression for the
179
Ans)

2007 Delhi:

6 (a) State Distributive law and verify d) Reduce the following Boolean
the same using truth table. 2 expression using K – Map : 2
Ans) F(U, V, W, Z) = ∑(0,1,2,3,4,10,11)

S)
C
T
G
(P
ar
m
Ku
er
nd
re
Vi

2006 Outside Delhi:


(b) Write the equivalent canonical
product of sum expression for the 6.(a)State and verify AssociativeLaw. 2
following sum of product
expression: 2 Ans)

F(X, Y,Z) = Π (1,3,6,7)

Ans)

(c) Write the equivalent Boolean


expression for the following logic
circuit 2

180
OR

(b) Write the equivalent expression for


the following Logic Circuit : 2

2006 Delhi:

6.(a) State and verify Distributive


Law. 2
Ans) Ans)
S)

(A+C)’.(A+B)’.(B+C)’ (a) A (B + C) = A B + A C
C
T

(b) A + (B C) = (A + B) (A + C)
G
(P

(c) Express P +Q’R in POS form. 1


ar
m

(P+Q’).(P+R)
Ku

OR
er
nd

(P+Q’+R).(P+Q’+R’).(P+Q+R)
re
Vi

(d) Reduce the following Boolean


expression using K – Map : 3
F(P, Q, R, S,) =
Π (0,3,5,6,7,11,12,15)

(b) Write the equivalent expression for


the following Logic Circuit : 2

181
OR
X.(X+Y)=X
OR
X+X’.Y=X+Y
OR

(c) Express P +Q’R in canonical SOP


form. 1
(P + Q’R)
= P ( Q+Q’)(R+R’) + Q’R(P+P’)
= (PQ +PQ’) (R + R’) + PQ’R + P’Q’R
= PQR + PQ’R + PQR’ + PQ’R’ + PQ’R
+ P’Q’R OR
= PQR + PQ’R + PQR’ + PQ’R’ + P’Q’R

(d) Reduce the following Boolean


expression using K – Map : 3
F(P, Q, R, S,) = ∑(0,3,5,6,7,11,12,15)
S)
C
T
G
(P
ar
m
Ku

OR
er
nd
re
Vi

OR

OR

2005 Outside Delhi

6. (a) State and verify Absorption Law


in Boolean algebra. 2

Ans)

Absorption Law: OR
X+X.Y=X
182
Algebraic Verification:
X+X.Y =X
X.1+X.Y =X
X.(1+Y) =X
X.1 =X
X =X

OR

X.(X+Y) =X
XX+X.Y =X
X.1+X.Y =X
X.(1+Y) =X
X.1 =X
X =X
Ans)
OR
(X+Y'+Z)(X'+Y+Z).(X'+Y'+Z)(X'+Y'+Z')
X+X’. Y =X+Y
(X+X’)(X+Y) =X+Y
(d) Reduce the following Boolean
1.(X+Y) =X+Y
expression using K – Map : 3
X+Y =X+Y
F(A, B, C, D,) =
OR
∑(0,1,2,3,4,5,10,11,15)
S)

X(X’+Y) =X.Y
C

XX’+X.Y =X.Y
T
G
(P

0+X.Y =X.Y
ar

X.Y =X.Y
m
Ku

(b) Write the equivalent expression for


er

the following Logic Circuit : 2


nd
re
Vi

Ans)

U.V’+U’.V+U’.V
2005 Delhi:
(c) Write the POS form of a Boolean
Function F, Which is represented by 6.(a) State and verify Associative law
the following truth table: 1 in Boolean Algebra. 2
Ans)

183
Ans)

(c) Write the SOP form of a Boolean


Function F, Which is represented by
S)

OR
C

the following truth table: 1


T
G
(P
ar
m
Ku
er
nd
re
Vi

Ans)

A'.B'.C' + A'.B.C + A.B.C' + A.B.C

(d) Reduce the following Boolean


(b) Write the equivalent Boolean
expression using K – Map : 3
expression for the following Logic
Circuit: 2
F(A, B, C, D,) =
Π (0,1,2,3,4,5,10,11,15)

Ans)

184
(b) Give the following truth table,
derive a sum of product (SOP) and
Product of Sum (POS) Form of
Boolean expression from it:

OR

(c) Obtain a simplified form for the


following Boolean Expression using
Karnaugh Map:

F(a,b,c,d) =
∑(0,1,2,4,5,7,8,9,10,11,14)
d)Draw the logic circuit for a Half
Adder using NAND gates Only. (Out
S)
C

OR of Syllabus now)
T
G
(P
ar

2003:
m
Ku
er

6. (a) State De Morgan’s Laws. Verify


nd

one of the De Morgan’s Laws using a


re
Vi

truth table.

(b) Verify X.Y’Z+X.Y’Z’+X’.Y’Z = X.Y’ +


Y’.Z algebraically.

(c) Write the dual of the Boolean


Expression: (B’+C).A
OR
(d) Obtain a simplified form for a
Boolean Expression:

F(U,V,W,Z,)=
∑(0,2,3,4,7,9,10,13,14,15)

(e) Draw the logic circuit for a half


adder. (Out of Syllabus now)

2002:
2004:
6. (a) State the Distributive law and
6.(a) State and prove the Absorption
verify the law using Truth table.1
law algebraically.

185
(b) Prove XY + YZ + Y’Z =XY + Z , (f) Derive the expression for a Full a
algebraically. 2 Adder (Out of syllabus now).
(c
) Obtain the simplified form, of a 2000:
Boolean expression using Karnaugh
map. 2 6. (a)State Absorption Laws. Verify
F(w,x,y,z)=∑(2,3,6,10,11,14) one of the Absorption Laws using a
truth table.
(d) Represent the Boolean expression
(X+Y)(Y+Z)(X+Z) with help of NOR (b) Prove
gates only. 1 X’.Y+Y’.Z=X’.Y.Z+X’.Y’.Z’+X.Y’.Z+X’.Y’.Z
algebraically.
(e) Given the following truth table,
write the product of sums form of the (c) Obtain simplified form for a
function. boolean expression
F(x,y,z,w)= ∑ (1,3,4,5,7,9,11,12,13,15)
using Karnaugh Map.

(d) Draw the logic circuit for a half


adder(Out of syllabus now).

(e) Represent the Boolean expression


X’Y+Y’Z with the help of NAND gates
only.
S)
C

(f) Write the Sum of Products form of


T
G

the function G(U,V,W) . Truthe table


(P
ar

2001: representation of G is as follows:


m
Ku
er

6. (a) State and verify Duality


nd
re

Principle.
Vi

(b) Prove algebraically: x’y’z’ + x’y’z +


x’yz’ + x.y’z = x’ + y’

(c)If F(a,b,c,d) =
Π (0,1,3,4,5,7,8,9,11,12,13,15),
Obtain the simplified form using K-map.

(d) Seven inverters are cascaded one 1999:


after another. What is the output if
the input is 1? 6.(a) State the distributive law. Verify
the law using truth table.
(e) Given the following circuit:
(b) Prove x+x'y=x+y algebraically.

(c) Write the dual of the Boolean


expression (x+y).(x'+y')

What if the output if (i) both inputs (d) Minimise F(w,x,y,z) using
are FALSE(0) (ii) one is FALSE and Karnaugh map.
the other is TRUE. F ( w,x,y,z) = Σ (0,4,8,12)

186
(e) Draw the logic circuit for a half-
adder. (Out of syllabus now)

(f) Represent the Boolean expression


(x+y)(y+z)(z+x) with the help of NOR
gates only.

Q 6 (g) Write sum of product form of


the function F(x,y,z). The truth table
representation for the function F is
given below:

Model Paper 1 for 2008-09:

6.(a)State & verify Demorgan’s Laws.2


Ans)
(X+Y)’ =X’.Y’
(X.Y)’ =X’+Y’

1998:
S)
C
T

6 (a) State Demorgan's laws. Verify


G
(P

one of the Demorgan's laws using


ar
m

truth tables.
Ku

(b)Write the equivalent Boolean


er

Expression for the following Logic


nd

(b) Prove X+Y'Z=(X+Y'+Z')(X+Y'+Z)


re

(X+Y+Z) algebraically. Circuit 2


Vi

(c) Write the dual of the Boolean


expression (U+W)(V'U+W)

(d) Obtain a simplified form for a


Boolean expression:
F( U, V, W,Z) =
π 0,1,3,5,7,9,10,11,12,13,14,15) Ans)

(e) Draw the logic circuit for a half- F(P,Q)=(P’+Q).(P+Q’)


adder (Out of syllabus now).
c)Write the POS form of a Boolean
(f) Represent the Boolean expression function F, which is represented in a
X+Y.Z' with the help of NOR gates truth table as follows:
only.

(g) Write the Product of Sum form of


the function H(U,V,W), truth table
representation of H is as follows:

187
(b)Write the equivalent Boolean
Expression for the following Logic
Circuit 2

Ans)

F(U,V,W) = (U+V+W’).(U+V’+W’).
(U’+V+W’)

(d) Reduce the following Boolean Ans)


Expression using K-Map: 3 F(U,V)=U’.V+U.V’
F(A,B,C,D)= Σ (0,1,2,4,5,6,8,10)
c) Write the SOP form of a Boolean
function G, which is represented in a
Ans)
truth table as follows: 1
S)
C
T
G
(P
ar
m
Ku
er
nd
re
Vi

Model Paper 2 for 2008-09:


Ans)
6.(a)State and algebraically verify G(P,Q,R) = P’.Q.R’+P.Q’.R’+P.Q.R’+P.Q.R
Absorbtion Laws. 2
d)Reduce the following Boolean
Ans) Expression using K-Map:
F(U,V,W,Z)= Π (0,1,2,4,5,6,8,10)
X+X.Y= X
L.H.S = X+X.Y Ans)
= X.1+X.Y
= X.(1+Y)
= X.1
= X
= R.H.S

X+X’.Y = X+Y
L.H.S. = X+X’.Y
(X+X’).
(X+Y)
= 1.(X+Y)
= X+Y
= R.H.S
188
Other Important Paper: c) Write the POS form of a Boolean
function F, which is represented in a
6. (a) State and verify Distributive law truth table as follows: 1
in Boolean Algebra. 2

(b) Draw a logical circuit diagram for


the following Boolean expression: A’.
(B+C) 1

(c)Convert the following Boolean


expression into its equivalent
Canonical Sum of Product
Form (SOP): 2
(U’+V’+W’).(U+V’+W’).(U+V+W).

(d) Reduce the following Boolean


Expression using K-Map: 3 Ans)

F(U,V,W) =
F(A,B,C,D)=
(U+V+W').(U+V'+W').(U'+V+W')
Π (1,3,4,5,7,9,11,12,13,14)
d) Reduce the following Boolean
MODEL PAPER 1 2009-10:
Expression using K-Map: 3
F(A,B,C,D)=Σ(0,1,2,4,5,6,8,10)
6.a) State and verify Demorgan's Laws
S)

algebraically. 2
C

Ans)
T
G
(P

Ans)
ar

(X+Y)' = X'.Y'
m
Ku

Verification
er

(X+Y)'.(X+Y) = X'.Y'.(X+Y)
nd
re

0 = X'.Y'.X + X'.Y'.Y
Vi

0 = X'.X .Y'+ X'.0


0 = 0 .Y'+ 0
0=0+0
0=0
L.H.S = R.H.S

b) Write the equivalent Boolean F(A,B,C,D)=A'C'+A'D'+B'D'


Expression for the following Logic
Circuit 2
MODEL PAPER 2 2009-10:

6.a) State and algebraically verify


Absorption Laws. 2
Ans)
X+X.Y = X
L.H.S = X+X.Y
= X.1+X.Y
Ans) = X.(1+Y)
F(P,Q)=(P'+Q).(P+Q') = X.1
=X
= R.H.S
X+X'.Y = X+Y
189
L.H.S. = X+X'.Y 14.COMMUNICATION AND
= (X+X').(X+Y)
= 1.(X+Y) NETWORK CONCEPTS
= X+Y
= R.H.S DELHI 2010:

b)Write the equivalent Boolean 7. (a) What was the role of ARPANET
Expression for the following Logic in the Computer Network? 1
Circuit 2
Ans. The first computer network was
Ans) F(U,V)=U'.V+U.V' jointly designed by The Advanced-
Research Projects Agency (ARPA) and
c) Write the SOP form of a Boolean Department of Defence (DoD) of
function G, which is represented in a United States in 1969 and was called
truth table as follows: 1 ARPANET. It was an experimental
project, which connected a few
computers from some of the reputed
universities of USA and DoD.
ARPANET allowed access to computer
resource sharing projects. This
ARPANET was handed over to Defence
Communication Agency (DCA) for
further development.

(b) Which of the following is not an


S)
C

unit for data transfer rate? 1


T
G

(i) bps
(P

(ii) abps
ar
m

(iii) gbps
Ku
er

(iv) kbps
nd

Ans)
re
Vi

Ans. (ii)abps
F(P,Q,R) = P'.Q'R'+P'.Q'R+P'.Q.R+P.Q'.R
(c) What is the difference between
d)Reduce the following Boolean Trojan Horse and Virus in terms of
Expression using K-Map: 3 computers? 1
F(U,V,W,Z)= Π (0,1,2,4,5,6,8,10)
Ans) Ans.

TROJAN HORSE: “Malware”


computer programs presented as
useful or harmless in order to induce
the user to install and run them.
VIRUS: Virus is a malicious program
that damages data and files and
causes harm to computer system.

(d) What term we use for a


software/hardware device, which is
used to block, unauthorized access
F(U,V,W,Z)=UV+WZ+UZ
while permitting authorized
communications. This term is also
used for a device or set of devices
configured to permit, deny, encrypt,
190
decrypt, or proxy all (in and out)
computer traffic between different
security domains based upon a set of
rules and other criteria. 1

Ans. Firewall

(e) “Learn Together” is an educational


NGO. It is setting up its new campus
at Jabalpur for its webbased activities.
The campus has 4 compounds as
shown in the diagram below:

OR

S)
C
T
G
(P
ar
m
Ku

(e2) Suggest the most suitable place


er
nd

(i.e. compound) to house the server for


re

this NGO. Also, provide a suitable


Vi

reason for your suggestion. 1

Ans. Training Compound as it


contains maximum number of
computers.

(e3) Suggest the placement of the


following devices with justification : 1
(i) Repeater
(ii) Hub/Switch

Ans.

(i) A Repeater should be placed when


the distance between any two
connecting compounds exceeds 70 m.

(ii) Every compound will need one Hub


/ Switch, to send signals to all of the
workstations connected to it

OR
191
Any diagrammatic representation with resource sharing projects. This
valid justification ARPANET was handed over to Defence
Communication Agency (DCA) for
(e4) The NGO is planning to connect further development.
its International office situated in
Mumbai, which out of the following (b) Which of the following is not a unit
wired communication link, you will for data transfer rate? 1
suggest for a very high speed (i) mbps
connectivity? 1 (ii) kbps
(i) Telephone Analog Line (iii) sbps
(ii) Optical Fiber (iv) gbps
(iii) Ethernet Cable
Ans. (iii) sbps
Ans. (ii) Optical Fiber
(c) What is the difference between
(f)Write the full forms of the Virus and Worms in the computers?1
following:1
(f1) GNU Ans.
(f2) XML
Virus: Virus is a malicious program
Ans (f1) GNU’s not Unix that damages data and files and
(f2) eXtensible Markup Language causes harm to computer system.

(g) Write one advantage of each for Worms: Worms disrupt services and
S)

Open Source Software and Proprietary create system management problems.


C

Software. 1 In some cases worms can install


T
G
(P

viruses that cause damage to system.


ar

Ans. An Open Source Software is


m
Ku

freely and liberally licensed because of (d) What term do we use for a
er

which users have right to study, software/hardware device, which is


nd
re

change. and improve its design and used to block unauthorized access
Vi

source code. A Proprietary Software while permitting authorized


has a copyright owner, who can communications? This term is also
restrict the user's control over the used for a device or set of devices
software, its modification, or configured to permit, deny, encrypt,
restrictions in publishing of modified decrypt, or proxy all (in and out)
or unmodified versions. computer traffic between different
security domains based upon a set of
OUTSIDE DELHI 2010: rules and other criteria. 1

7. (a) What was the role of ARPANET Ans. Firewall


in the Computer Network? 1
(e) “Vidya for All” is an educational
Ans. The first computer network was NGO. It is setting up its new campus
jointly designed by The Advanced at Jaipur for its web-based activities.
Research Projects Agency (ARPA) and The campus has four buildings as
Department of Defence (DoD) of shown in the diagram below: 4
United States in 1969 and was called
ARPANET. It was an experimental
project, which connected a few
computers from some of the reputed
universities of USA and DoD.
ARPANET allowed access to computer
192
(e2) Suggest the most suitable place
(i.e. building) to house the server for
this NGO. Also, provide a suitable
reason for your suggestion.

Ans. Training Building as it contains


maximum number of computers.

(e3) Suggest the placement of the


following devices with justification:
(i) Repeater
(ii) Hub/Switch

Ans.
(i) A Repeater should be placed when
the distance between any two
connecting buildings exceeds 70 m.
(ii) Every building will need one Hub /
Switch, to send signals to all of the
workstations connected to it

(e4) The NGO is planning to connect


its International office situated in
Delhi. Which out of the following wired
S)

communication links, will you suggest


C

for a very high speed connectivity ?


T
G
(P

(i) Telephone Analog Line


ar

(ii) Optical Fiber


m
Ku

(iii) Ethernet Cable


er
nd
re

Ans. (ii) Optical Fibre


Vi

(f)Writethe full forms of the following:1


(f1) FTP
(f2) FSF

Ans.
(f1) FILE TRANSFER PROTOCOL
(f2) FREE SOFTWARE FOUNDATION

(g) Name any two common Web


browsers. 1

Ans.
Internet explorer
Firefox
Netscape
Chrome
Opera
Safari
OR any other Web Browser

DELHI 2009:
193
TCP/IP OR HTTP
7. (a) What is difference between Star
Topology and Bus Topology of (d) Name two switching techniques
network? 1 used to transfer data between two
terminals(computers).1
Ans)
Ans Message Switching and Packet
Bus Topology: It is characterised by Switching
common transmission medium shared OR
by all the connected hosts, managed Circuit Switching and Message
by dedicated nodes. It offers Switching
simultaneous flow of data and control. OR
Circuit Switching and Packet
Star Topology: It is characterised by Switching
central switching node
(communication controller) and (e) Freshminds University of India is
unique path (point to point link) for starting its first campus in Ana Nagar
each host. It is easy to add and of South India with its center
remove additional hosts by upgrading admission office in Kolkata. The
the centralised node. university has 3 major blocks
comprising of Office Block, Science
Block and Commerce Block in the 5
KM area Campus. As a network
expert, you need to suggest the
S)

network plan as per (El) to (E4) to the


C

authorities keeping in mind the


T
G
(P

distance and other given parameters.


ar
m
Ku
er
nd
re
Vi

(b)Expand the following


abbreviations1
(i) GSM
(ii) CDMA

Ans
(i) Global System for Mobile
Communication
(ii) Code Division Multiple Access

(c) What is protocol? Which protocol is


used to search information from
internet using an internet browser? 1

Ans A protocol is the set of rules for


governing communication between two
communication devices. It also infers
documentation, negotiations and
establishment of rules. Protocol used (E1) Suggest the authorities, the cable
to search information from internet layout amongst various blocks inside
using an internet browser is :
194
university campus for connecting the 7. (a) What is the difference between
blocks. 1 LAN and WAN? 1

Ans) Ans LAN (Local Area Network):

Interconnects a high number of access


or node points or stations within a
confined physical area. An example is
the territory covered in a single office
building that houses various
departments/offices. All these areas
are interconnected using a LAN.

(E2) Suggest the most suitable place


(i.e. block) to house the server of this
university with a suitable reason. 1

Ans)Science Block as it contains


maximum number of computere.
WAN (Wide Area Network)
Note: 1 mark if Commerce Block is
written with valid justification eg.
It is used to connect systems with no
Minimum wiring needed
limitation of geographical area. It is
used to serve many locations
S)

(E3) Suggest an efficient device from


C

distributed over a large geographical


T

the following to be installed in each of


G

area. A system of overnight teller


(P

the blocks to connect all the


ar

machines used by a banking


m

computers: 1
Ku

organisation covering the North of


(i) MODEM
er

India is an example of a WAN. Internet


nd

(ii) SWITCH
re

is also an example of the same.


Vi

(iii) GATEWAY

Ans SWITCH

(E4) Suggest the most suitable. (very


high speed) service to provide data
connectivity between Admission Office
located in Kolkata and the campus
located in Ana Nagar from the
following options: 1
_ Telephone line
_ Fixed-Line Dial-up connection
_ Co-axial Cable Network
_ GSM b)Expand the following
_ Leased line abbreviations:1
_ Satellite Connection (i) HTTP
(ii) ARPANET
Ans Satellite Connection
OR Ans
Leased line
OUTSIDE DELHI 2009:
(i) Hyper Text Transfer Protocol

195
(ii) Advanced Research Projects Agency
Network

(c) What is protocol? Which protocol is


used to copy a file from/to a remotely
located server? 1

Ans A protocol is the set of rules for


governing communication between two
communication devices. It also infers
documentation, negotiations and
establishment of rules. Protocol used
to copy a file fromlto a remotely
located server is FTP (File Transfer
Protocol)

(d) Name two switching techniques


used to transfer data between two
terminals (computers). 1

Ans Message Switching and Packet


Switching (E1) Suggest to the authorities, the
OR cable layout amongst various
Circuit Switching and Message buildings inside the university campus
S)

Switching for connecting the buildings. 1


C

OR
T
G
(P

Circuit Switching and Packet Ans)


ar

Switching
m
Ku
er

(e) Eduminds University of India is


nd
re

starting its first campus in a small


Vi

town Parampur of Central India with


its center admission office in Delhi.
The university has 3 major buildings
comprising of Admin Building,
Academic Building and Research
Building in the 5 KM area Campus. As
a network expert, you need to suggest
the network plan as per (E1) to (E4) to
the authorities keeping in mind the (E2) Suggest the most suitable place
distances and other given parameters. (i.e. building) to house the server of
this organisation, with a suitable
reason. 1

Ans Academic Building as it contains


maximum number of computers.
Note: 1 mark if any suitable
place/building is suggested with valid
justification

(E3) Suggest an efficient device from


the following to be installed in each of

196
the buildings to connect all the (iii) File Transfer Protocol
computers : 1 (iv) Transfer Control Protocol/Internet
(i) GATEWAY Protocol
(ii) MODEM
(iii) SWITCH 3) How is Coaxial cable different from
Optical Fibre? 1m
Ans SWITCH
Ans)
(E4) Suggest the most suitable (very
high speed) service to provide data Coaxial Cable: Comparatively Slow,
connectivity between Admission Economic, convenient to lay down,
Building located in Delhi and the used in Bus topology of networks
campus located in Par am pur from Optical Fibre: Very fast, expensive,
the following options: 1 reliable, no interference
_ Telephone line
_ Fixed-Line Dial-up connection
_ Co-axial Cable Network 4) “Bias methodologies” is planning to
_ GSM expand their network in India, starting
_ Leased line with three cities in India to build
_ Satellite Connection infrastructure for research and
development of their chemical
Ans products. The company has planned
Satellite Connection to setup their main office in
OR Pondicherry – at three different
S)

Leased line locations and have named their offices


C

as “Back Office”, “Research Lab” and


T
G
(P

“Development Unit”. The company has


ar

DELHI 2008: one more Research office namely


m
Ku

“Corporate Office” in “Mumbai”. A


er

1) What is a Hub? 1 rough layout of the same is as follows:


nd
re
Vi

Ans)

A Hub is used for a central connection


between two or more computers on a
network.
OR
A Hub is a network device used to
connect two or more computers.
OR
A Hub is an unintelligent network
device to connect computers.

2) Expand the following terms with


respect to Networking: 2m
i) MODEM ii) WLL
iii) FTP iv) TCP/IP
Approximate distance between these
offices is as follows:
Ans)
(i) Modulator - Demodulator
(ii) Wireless Local Loop
OR
Wireless in Local Loop
197
Optical Fibre

iv) Suggest a cable/wiring layout for


connecting the company’s local office
units located in Pondicherry. Also,
suggest an effective method/
technology for connecting the
company’s office unit located in
Mumbai.
In continuation of the above , the Ans)
company experts have planned to
install the following number of Local office units at Pondicherry to be
computers in each of their offices: connected using LAN / MAN / star
Topology / Tree Topology

Mumbai Office to be connected using


Satellite/WAN

1) Suggest the kind of network


required (out of LAN, MAN, WAN) for
connecting each of the following office
units:
S)
C
T
G

i) Research Lab and Back Office


(P
ar

ii) Research Lab and Development


m
Ku

Unit
er
nd

Ans)
re
Vi

Research Lab and Back Office - LAN


Research Lab and Development Unit - MAN
OUTSIDE DELHI: 2008
2) Which one of the following devices
1) What is a Modem? 1m
will you suggest for connecting all the
computers with in each of their office
Ans)
units?
i) Switch/Hub ii) Modem
Modem is a Modulation Demodulation
iii) Telephone
device that converts analog signal to
Ans)
digital signal and vice versa.
Switch / Hub

3) Which of the following


2) Expand the following terms with
communication media, you will
respect to Networking: 2m
suggest to be procured by the
i) PPP ii) GSM
company for connecting their local
iii) XML iv) HTTP
office units in Pondicherry for very
effective (High Speed) communication?
Ans)
i) Telephone cable
ii) Optical Fibre
(i) Point To Point Protocol
iii) Ethernet Cable
(ii) Global System for Mobile
Ans)
198
Communication
(iii) eXtensible MarkUp Language
(iv) Hyper Text Transfer Protocol

3)How is a Hacker different from a


Cracker? 1

Ans)

Hackers are the ones who get into


someone’s code or computer without
any malicious intentions, where as In continuation of the above, the
Crackers are the one’s who get into company experts have planned to
someone’s code or computer with install the following number of
malicious intentions. computers in each of their offices:

4)”China Middleton Fashion” is


planning to expand their network in
India, starting with two cities in India
to provide infrastructure for
distribution of their product. The
company has planned to setup their
main office in Chennai at three
different locations and have named
S)

their offices as “Production Unit”, 1) Suggest the kind of network


C

“Finance Unit” and “Media Unit “.The


T

required (out of LAN, MAN, WAN) for


G
(P

Company has its corporate unit in connecting each of the following office
ar

Delhi. A rough layout of the same is as


m

units:
Ku

follows: i) Production Unit and Media Unit


er
nd

ii) Production Unit and Finance Unit


re

Ans)
Vi

Production Unit and Media Unit : MAN


Production Unit and Finance Unit : LAN

2) Which one of the following devices


will you suggest for connecting all the
computers with in each of their office
units?
i) Switch/Hub ii) Modem
iii) Telephone
Ans)
Switch / Hub
Approximate distance between these
Units is as follows: 3) Which of the following
communication media, you will
suggest to be procured by the
company for connecting their local
office units in Chennai for very
effective (High Speed) communication?
i) Telephone cable
ii) Optical Fibre
iii) Ethernet Cable
199
Ans) 3) Which of the following unit
Optical Fibre measures the speed with which data
can be transmitted from one node to
4) Suggest a cable/wiring layout for another node of a network? Also, give
connecting the company’s local office the expansion of the suggested unit.1
units located in Chennai. Also, i) Mbps ii) KMps
suggest an effective iii) MGps
method/technology for connecting the
company’s office unit located in Delhi. Ans)
Ans)
Mbps (Mega Bits Per Second)

4) “Bhartiya Connectivity Association


“is planning to spread their offices in
four major cities in India to provide
regional IT infrastructure support in
the field of Education & Culture. The
company has planned to setup their
head office in New Delhi in three
locations and have named their New
Delhi offices as “Front Office “,”Back
Office “and “Work Office “.The
company has three more regional
offices as “South Office “,”East
DELHI 2007:
S)

Offfice”and “West Office “ located in


C

other three major cities of India. A


T
G

1) What is the significance of Cyber


(P

rough layout of the same is as follows:


law? 1m
ar

4m
m

Ans)
Ku

Cyber law encompasses a wide variety


er
nd

of political and legal issues related to


re
Vi

the Internet and other


communications technology, including
intellectual property, privacy, freedom
of expression, and jurisdiction.
OR

Cyber law helps prevent Cyber Crime,


Hacking, Data theft, Software Piracy
and protects rights of Cyber Users.

2) Expand the following terms with


respect to networking: 2m
i) CDMA ii) WLL
iii) FTP iv) HTML
Approximate distance between these
Ans) offices as per network survey team is
as follows
(i) Code Division Multiple Access
(ii) Wireless Local Loop Pla Plac
(iii) File Transfer Protocol ce From e To Distance
Back Office Front Office 10 KM
(iv) Hyper Text Markup Language
Back Office Work Office 70 KM
Back Office East Office 1291KM
200
Back Office West Office 790 KM effective method /technology for
Back Office South Office 1952KM connecting the company’s regional
offices –“East Office”, “West Office
In continuation of the above, the “and “South Office” with offices located
company experts have planned to in New Delhi.
install the following number of
computers in each of their offices: Ans)

Back Office 100


Front Office 20
Work Office 50
East Office 50
West Office 50
South Office 50

1) Suggest network type(out of


LAN,MAN,WAN) for connecting each of
the following set of their offices:
Back Office and Work Office
Back Office and south Office

Ans)

Back Office and Work Office – LAN OR


S)

Back Office and South Office – WAN


C
T
G
(P

2) Which device you will suggest to be


ar

produced by the company for


m
Ku

connecting all the computers with in


er

each of their offices out of the


nd
re

following devices?
Vi

Switch/Hub
Modem
Telephone
OUT SIDE DELHI 2007:
Ans)
Switch / Hub 1) What is the significance of Cyber
law? 1m
3) Which of the following
communication medium, you will Ans)
suggest to be produced by the
company for connecting their offices in Cyber law encompasses a wide variety
New Delhi for very effective and fast of political and legal issues related
communication? to the Internet and other
Telephone Cable communications technology, including
Optical Fibre intellectual property, privacy, freedom
Ethernet Cable of expression, and jurisdiction.
OR
Ans) Optical Fibre Restricting unauthorized access to
user accounts. Promoting,
4) Suggest a cable/writing layout for coordinating and controlling e-
connecting the company’s local offices business.
located in New Delhi. Also, suggest an
201
2) Expand the following terms with Approximate distance between these
respect to networking: 2m offices as per network survey team is
i) XML ii) WWW as follows
iii) WLL iv) TCP/IP

Ans)

(i) XML eXtensible MarkUp Language


(ii) WWW World Wide Web
(iii) WLL Wireless in Local Loop
(iv) TCP/IP Transmission Control
Protocol/Internet Protocol

3) Which of the following unit


measures the speed with which data In continuation of the above, the
can be transmitted from one node to company experts have planned to
another node of a network? Also, give install the following number of
the expansion of the suggested unit computers in each of their offices:
1m
i) KMps ii) Mbps Head Office 100
iii) MGps Sales Office 20
Tech Office 50
Ans) Kolkata Office 50
Ahmadabad Office 50
(ii) Mbps
S)

Coimbatore Office 50
C

Mega bits per second


T
G
(P

1) Suggest network type(out of


ar

4) “Hindustan Connecting World LAN,MAN,WAN) for connecting each of


m
Ku

Association “is planning to start their the following set of their offices:
er

offices in four major cities in India to Head Office and Tech Office
nd
re

provide regional IT infrastructure Head Office and Coimbatore Office


Vi

support in the field of Education &


Culture. The company has planned to Ans)
set up their head office in New Delhi in
three locations and have named their Head Office and Tech Office: LAN
New Delhi offices as “Sales Office Head Office and Coimbatore Office: WAN
“,”Head Office “and “Tech Office “.The
company’s regional offices are located
at “Coimbatore”,”Kolkata”and 2) Which device you will suggest to be
“Ahmadabad”. A rough layout of the produced by the company for
same is as follows: 4m connecting all the computers with in
each of their offices out of the
following devices?
Modem
Telephone
Switch/Hub

Ans)

Switch / Hub

3) Which of the following


communication media, will suggest to
202
be procured by the company for DELHI: 2006
connecting their local offices in New
Delhi for very effective and fast 1) Differentiate between Internet and
communication? Intranet 1
Ethernet Cable, Optical
Fibre,Telephone Cable Ans)

Ans) Internet is a network of computer


networks which operates world-wide
Optical Fibre using a common set of
communications protocols.
Intranet is an inter-connected
O network within one organization that
uses Web technologies for the sharing
O of information internally.
4) Suggest a cable/writing layout for
connecting the company’s local offices 2) Expand the following terms: 2m
located in New Delhi. Also, suggest an i) CDMA ii) URL
effective method /technology for iii) HTTP iv) WAN
connecting the company’s regional Ans)
offices at “Kolkata”,”Coimbatore”and (i) Code Divison Multiple Access
“Ahmadabad”. (ii) Uniform Resource Locator (Location) /
Universal Resource Locator (Location)
Ans) (iii) Hype Text Transfer (Transmission)
Protocol
S)
C

Optical Fiber/Star Topology (iv) Wide Area Network


T
G

3) Write one advantage of STAR


(P

Wireless
ar

topology as compared to BUS topology


m
Ku

1m
er

Ans)
nd
re

Fault detection is easy.


Vi

Fault isolation is easy.

4) UNIVERSITY OF
CORRESPONDENCE in Allahabad is
setting up the network between its
different wings. There are 4 wings
named as Science (S), Journalism (J),
ARTS (A) and Home Science (H).
OR
Distances between various wings are
given below:

Number of Computers
Optical Fiber/Bus Topology
Wireless Wing A 150

203
Wing S 10
Wing J 05 (i) XML Extensible Markup Language
Wing H 50 (ii) GSM Global System for Mobile
(iii) SMS Short Messaging Service
{Message/Messaging both acceptable}
i) Suggest a suitable Topology for
(iv) MAN Metropolitan Area Network
networking the computer of all wings.
1m
3) Difference between Hackers and
Ans)
Crackers? 1
Star or Bus or any other valid
topology or diagram.
Ans)
ii) Name the wing where the Server to
Hackers: Computer enthusiasts who
be installed. Justify your answer. 1m
enjoy learning about computer
Ans)
systems and get into other
Wing A, because maximum number of
system/network for gaining more
computers are located at Wing A.
knowledge or may find flaws in the
system for rectification purposes.
iii) Suggest the placement of
Hub/Switch in the network. 1m
Crackers: Malicious programmers
Ans)
who break into secure systems for
Hub/Switch in all the wings.
stealing and corrupting/spoiling data.
OR
Correct diagram depicting placement
4) INDIAN PUBLIC SCHOOL in
of Hub/Switch in all the wings.
Darjeeling is setting up the network
S)
C

between its different wings. There are


T

iv) Mention in economic technology to


G

4 wings named as SENIOR(S),


(P

provide internet accessibility to all


ar

JUNIORS (J), ADMIN (A) and


m

wings. 1m
Ku

HOSTEL (H).
Ans)
er
nd

Coaxial cable / Modem / LAN / TCP-


re

Distance between various wings is


Vi

IP / Dialup/ DSL/ Leased Line


given below:
OR any other valid technology (any one).
Number of Computers
OUTSIDE DELHI 2006:
Wing A 10
1) Name two transmission media for
networking. 1m Wing S 200
Wing J 100
Ans) Wing H 50

Optical Fiber i) Suggest a suitable Topology for


Ethernet Cable or twisted pair cable or UTP or STP networking the computer of all
Co-axial Cable wings.1
Infrared Ans)
Radio Link OR Radiowave Star Topology
Microwave link OR Microwave OR
Satellite Link Bus Topology

2) Expand the following terms: 2m ii) Name the wing where the server to
i) XML ii) GSM be installed. Justify your answer. 1m
iii) SMS iv) MAN
Ans)
Ans)
204
Wing S the network is specified. All the
as it has the maximum number of computers packets are stored in the main
OR memory instead of disk. As a result
WingA accessing time of packets is reduced.
as it is placed in the Admin Wing (for security reasons)

iii) Suggest the placement of


Hub/Switch in the network. 1m

Ans)
Inside all the four wings

iv) Mention in economic technology to


provide internet accessibility to all
2) Expand the following terminologies:
wings. 1m
2m
i) TCP/IP ii) XML
Ans:
iii) CDMA iv) WLL
Ans)
Any one of the following:
(i) Tranmission Control
Dialup, TCP/IP, DSL, Modem,
Protocol/Internet Protocol
Broadband, Cable, ISDN, Telephone
(ii) eXtensible Markup Language OR
Line, Co-axial, Ethernet Cable,
extendable Markup Language
Radiowave
(iii) Code Division Multiple Access
(iv) Wireless in a Local Loop
S)

DELHI 2005:
C

3) Write two application of Cyber Law.


T
G
(P

1m
1) What is the difference between
ar

Ans)
m

Message Switching technique and


Ku

Packet Switching technique? 1m


er

Cyber law encompasses a wide variety


nd
re

of political and legal issues related


Vi

Ans)
to the Internet and other
communications technology, including
Message switching: The saurce
intellectual property, privacy, freedom
computer sends data (message) to the
of expression, and jurisdiction.
switching office, which stores data in a
buffer. It then looks for a free link
4) The Great Brain Organization has
to another switching office and sends
set up its new Branch at Srinagar for
data to that office. This process
its office and web based activities .It
continues until data is delivered to the
has 4 Wings of buildings as shown in
destination computer. This type of
the diagram:
switching technique is also known as
‘store and forward’ switching.

Packat switching: A fixed size of


packet that can be transmitted across

205
Center to center distances between Telephone Link (Most Suitable answer 2)
various blocks OR
Microwave
Wing X to Wing Z 50 m OR
Wing Z to Wing Y 70 m Radio Link/Radio Wave
Wing Y to Wing X 125 m OR
Wing Y to Wing U 80 m Satellite Link
Wing X to Wing U 175 m OR
Wing Z to Wing U 90 m WAN

Number of computers OUT SIDE DELHI: 2005

Wing X 50 1) Compare Optical Fiber and Coaxial


Wing Z 30 transmission media. 1m
Wing Y 150
Wing U 15 Ans)

Coaxial Cable: Comparatively Slow,


1) Suggest a most suitable cable
Economic, convenient to lay down,
layout of connections between the
used in Bus topology of networks;
Wings, and topology 1
Ans)
[½ Mark for drawing / mentioning any Optical Fibre: Very fast, expensive,
suitable cable layout] reliable, no interference
[½ Mark for mentioning the topology] 2) Expand the following terminologies:
S)

i) HTML ii) GSM


C

2) Suggest the most suitable place


T
G

(i.e., Wing)to house the server of this


(P

Ans)
ar

organization with a suitable reason, Hyper Text Markup Language


m
Ku

with justification. 1m Global System for Mobile communication


er
nd
re

Ans) Wing Y as it has largest number 3) What is the difference between XML
Vi

of computers and HTML? Write two differences.1m

3) Suggest the placement of the Ans)


following devices with justification:1
(i) Repeater (ii) Hub/Switch eXtensible Markup Language:
It contains user defined tags
Ans) Hyper Text Markup Language:
[½ Mark for mentioning Switch/Hub It contains predefined tags
placement in each of the building]
[½ Mark for suggesting the placement of
repeater for the distances higher than 70 m] 4) What do you understand by the
terms Cookies and Firewall? 1m
4) The organization is planning to link
its head office situated in Delhi with Ans)
the offices at Srinagar.1m Suggest an
economic way to connect it; the Cookies: A small piece of information
company is ready to compromise on that a server sends to a client When
the speed of connectivity. Justify your you visit a Web site with cookie
answer. capabilities, its server sends certain
information about you to your
Ans) browser, which is stored on your hard
TCP/IP Dial Up (Most Suitable answer 1) drive as a text file. At some later time
OR (such as returning to the site the next
206
day),the server retrieves the cookie. organization with a suitable reason,
It’s a way toi the server to remember with justification. 1m
things about you.
Ans)
Firewall: Any of a number of security Wing Z as it has largest number of
schemes (hardware/software) that computers
prevent unauthorized users from
gaining access to a computer network 3) Suggest the placement of the
or that monitor transfers of following devices with justification:1m
information to and from the network. (i)Repeater (ii) Hub/Switch

5) The Cyber Mind Organization has 4) The organization is planning to link


set up its new Branch at Mizoram for its head office situated in Delhi with
its office and web based activities. It the offices at Srinagar.1m Suggest an
has 4 Wings of buildings as shown in economic way to connect it; the
the diagram: company is ready to compromise on
the speed of connectivity. Justify your
answer. 2m

Ans)

TCP/IP Dial Up (Most Suitable answer 1)


OR
Telephone Link (Most Suitable answer 2)
S)

OR
C

Microwave
T
G
(P

OR
ar

Radio Link/Radio Wave


m

Center to center distances between


Ku

OR
er

various blocks Satellite Link


nd
re

OR
Vi

Wing X to Wing Z 40 m WAN


Wing Z to Wing Y 60 m
Wing Y to Wing X 135 m DELHI 2004:
Wing Y to Wing U 70 m
Wing X to Wing U 165 m 1) Write two advantages and two
Wing Z to Wing U 80 m disadvantages for STAR topology? 1m

Number of computers 2) Write one difference between


Coaxial and optical cable? 1m
Wing X 50
Wing Z 130 3) Explain the following terms in
Wing Y 40 short. 2m
Wing U 15 i) FTP ii) URL

1) Suggest a most suitable cable 4) Define Packet switching? 1m


layout of connections between the
Wings, and topology 1m DELHI: 2003

1)What is the purpose of using a repeater


2) Suggest the most suitable place in the context of networking? 1
(i.e., Wing) to house the server of this

207
2) Write an advantage and a
disadvantage of using optical fibre 3) Write the two advantages and two
cables? 1m disadvantages of BUS Topology in
network? 2
3) Write one advantage and one
disadvantage of the following 4) What is the difference between LAN
topologies in network: 2m and WAN? 1m
i)STAR Topology
ii)BUS Topology
DELHI 1999:
4) What is the difference between MAN
and WAN? 1m 1) What is a bridge? 1m
2) What is the purpose of using FTP?1
DELHI 2002:
3) Give two advantages and
1) What is a Modem? 1m disadvantages of following network
topologies: 2m
2) Write the following abbreviations in i)BUS ii)Tree
their full form. 1m
i) FTP ii) WAN 4) What is the difference between WAN
iii) WWW and MAN. 1m

3) Mention one difference between DELHI 1998:


circuit switching and pocket
S)

switching. 2m 1) What are repeaters? 1m


C
T
G
(P

4) Write two advantages and 2) What is the difference between LAN


ar

disadvantages of the following and MAN? 1m


m
Ku

topologies in a Network. 1m
er

i) BUS ii)RING 3) Describe the following in brief:2m


nd
re

i)MOSAIC ii)Usenet
Vi

DELHI 2001: 4) What do you understand by a


backbone network? 1m
1) What is NFS? 1m
MODEL PAPER 1 FOR 2009-10:
2) Mention one advantage of
networking. 1m 7.a) Compare any two Switching
techniques. 1
3) Name two communication channels
used in networking and explain any Ans)
one. 2m
Appropriate comparison between any
4) Mention one difference between two out of Circuit Switching, Message
Linear and Star topologies in Switching, Packet Switching
networking. 1m
b) Which of the following is not a
DELHI 2000: Client Side script: 1
(i) VB Script (ii) Java Script
1) What are Routers? 1m (iii) ASP (iv) PHP

2) What is the purpose of using a Ans)


MODEM? 1
208
(iii) ASP and (iv) PHP are not client side
scripts

c) If someone has hacked your


Website, to whom you lodge the
Complain? 1

Ans)
The complaint has to be lodged with
the Police under IT Act.

d) What do you mean by IP Addre


ss? How is it useful in Computer
Security? 1
e1) Suggest a cable layout of
Ans) connections between the blocks.

An Internet Protocol (IP) address is a Ans)


numerical identification and logical
address
that is assigned to devices connected in a
computer network.
An IP Address is used to uniquely identify
devices on the Internet and so one can
quickly know the location of the system in
S)
C

the network.
T
G
(P
ar

e)Knowledge Supplement Organisation


m
Ku

has set up its new center at Mangalore


er

for its office and web based activities.


nd

It has 4 blocks of buildings as shown


re
Vi

in the diagram below: 4

e2) Suggest the most suitable place


(i.e. block) to house the server of this
organization with a suitable reason.

Ans)

The most suitable place / block to


house the server of this organisation
would be Block C, as this block
contains the maximum number of
computers, thus decreasing the
cabling cost for most of the computers
as well as increasing the efficiency of

209
the maximum computers in the
network.

e3) Suggest the placement of the


following devices with justification
(i) Repeater
(ii) Hub/Switch

Ans)

(i) For Layout 1, since the cabling


distance between Blocks A and C, and
that between B and C are quite large,
so a repeater each, would ideally be
needed along their path to avoid loss
of signals during the course of data
flow in these routes.

e4) The organization is planning to


link its front office situated in the city
in a hilly region where cable
connection is not feasible, suggest an
economic way to connect it with
reasonably high speed?
S)
C
T
G

Ans)
(P
ar
m

The most economic way to connect it


Ku

For layout 2, since the distance


with a reasonable high speed would be
er

between Blocks A and C is large so a


nd

to use radio wave transmission, as


re

repeater would ideally be placed in


Vi

they are easy to install, can travel long


between this path.
distances, and penetrate buildings
easily, so they are widely used for
communication, both indoors and
outdoors. Radio waves also have the
advantage of being omni directional,
which is they can travel in all the
directions from the source, so that the
transmitter and receiver do not have
to be carefully aligned physically.

f) What do you mean by Spam Mails?


How can you protect your mailbox
from Spams?
(ii) In both the layouts, a hub/switch
each would be needed in all the Ans)
blocks, to interconnect the group of
cables from the different computers in Spam mails, also known as junk e-
each block. mail, is a subset of spam that involves
nearly identical messages sent to
numerous recipients by e-mail.
We can protect our mailbox from
spams by creating appropriate filters.
210
g) Mention any two advantages of The first benefit of XML is that
Open Source Software over Proprietary because you are writing your own
Software. markup language, you are not
restricted to a limited set of tags
Ans) defined by proprietary vendors.
Rather than waiting for standards
Open Source's proponents often claim that bodies to adopt tag set enhancements
it offers significant benefits when (a process which can take quite some
compared to typical Proprietary Software. time), or for browser companies to
Proprietary Software typically favour adopt each other's standards (yeah
visible right!), with XML, you can create your
features (giving marketing advantage) over own set of tags at your own
harder-to measure qualities such as pace.
stability,security and similar less
glamorous attributes. c) How firewall protect our Network? 1
Open Source Software developers are
evidently motivated by many factors but Ans)
favouring features over quality is not
noticeable amongst them. For many A firewall is a part of a computer
developers, peer review and acclaim is system or network that is designed to
important, so it's likely that they will prefer block unauthorized access while
to build software that is admired by their permitting authorized
peers. Highly prized factors are clean communications. It is a device or set
design, reliability and maintainability, with
S)

of
C

adherence to standards and shared devices configured to permit, deny,


T
G

community values preeminent.


(P

encrypt, decrypt, or proxy all (in and


ar

out) computer traffic between different


m

MODEL PAPER 2 FOR 2009-10:


Ku

security domains based upon a set of


er

rules and other criteria.


nd

7. a) Define the term Bandwidth. Give


re
Vi

any one unit of Bandwidth. 1 d) What is the importance of URL in


networking? 1
Ans)
Ans)
Bandwidth is referred to the volume of
information per unit of time that a A Uniform Resource Locator (URL) is
transmission medium (like an Internet used to specify, where an identified
connection) can handle. resource is available in the network
OR and the mechanism for retrieving it. A
The amount of data that can be URL is also referred to as a Web
transmitted in a fixed amount of time address.
is known as bandwidth.
For digital devices, the bandwidth is e) Ravya Industries has set up its new
usually expressed in bits per center at Kaka Nagar for its office and
second(bps) or bytes per second. For web based activities. The company
analog devices, the bandwidth is compound has 4 buildings as shown
expressed in cycles per second, or in the diagram below: 4
Hertz (Hz).

b) When do you prefer XML over HTML


and why? 1

Ans)
211
e2) Suggest the most suitable place
(i.e. building) to house the server of
this organization with a suitable
reason.

Ans)

The most suitable place / block to


house the server of this organisation
would be Raj Building, as this block
contains the maximum number of
computers, thus decreasing the
cabling cost for most of the computers
as well as increasing the efficiency of
the maximum computers in the
network.

e3) Suggest the placement of the


following devices with justification:
(i) Internet Connecting
Device/Modem
(ii) Switch

Ans)
S)
C

(i)Raj Building
T
G
(P

(ii) In both the layouts, a hub/switch


ar

each would be needed in all the


m
Ku

buildings, to interconnect the group of


e1) Suggest a cable layout of
er

cables from the different computers in


nd

connections between the buildings.


re

each block
Vi

Ans)
e4) The organisation is planning to
link its sale counter situated in
various parts of the same city, which
type of network out of LAN, MAN or
WAN will be formed? Justify your
answer.

Ans)

The type of network that shall be


formed to link the sale counters
situated in various parts of the same
city would be a MAN, because MAN
(Metropolitan Area Networks) are the
networks that link computer facilities
within a city.

f)Compare freeware and Shareware. 1

Ans)

212
Freeware, the name derived from experimental project, which connected
words "free" and"software". It is a a few computers of some of the
computer software that is available for reputed universities of USA and DoD.
use at no cost or for an optional fee. ARPANET allowed access and use of
Freeware is generally proprietary computer resource sharing projects.
software available at zero price, and is Later Defence Data Network (DDN)
not free software. The author usually was born in 1983.
restricts one or more rights to copy,
distribute, and make derivative works b)Expand the following terminologies:1
of the software. (i) CDMA (ii) GSM
Shareware is usually offered as a trial
version with certain features only Ans)
available after the license is
purchased, or as a full version, but for Code Division Multiple Access
a trial period. Once the trial period Global System for Mobile Communication
has passed the program may stop
running until a license is purchased. c)Give two major reasons to have
Shareware is often offered without network security. 1
support, updates, or help menus,
which only become available with the Ans)
purchase of a license. The words "free
trial" or "trial version" are indicative of Two major reasons to have Network
shareware. Security are
(i) Secrecy: Keeping information
S)

g) How Trojan Horses are different out of the reach of unauthorized


C

from Worms? Mention any one


T

users.
G
(P

difference. 1 (ii) Authentication: Determining


ar
m

the authorized user before sharing


Ku

Ans) sensitive information with or entering


er
nd

into a business deal.


re

A Trojan horse is a term used to


Vi

describe malware that appears, to the


d)What is the purpose of using a Web
user, to per form a desirable function
Browser? Name any one commonly
but, in fact, facilitates unauthorized
used Web Browser. 1
access to the user's computer system.
A computer worm is a self-replicating
Ans)
computer program. It uses a network
to send copies of itself to other nodes
The Web Browser fetches the page
(computers on the network) and it may
requested, interprets the text and
do so without any user intervention.
formatting commands that it contains,
and displays the page properly
MODEL PAPER 1 FOR 2008-09:
formatted on the screen.
Example of a Web Browser:
7.a)What is the significance of
Mozilla Firefox OR Internet Explorer
ARPANET in the network? 1
OR Netscape Navigator OR Safari OR
OPERA
Ans)
e)Knowledge Supplement Organisation
The first evolution of network was
has set up its new center at
jointly designed by The Advanced
Mangalore for its office and web
Research Projects Agency (ARPA) and
based activities. It has 4 blocks of
Department of Defence (DoD) in 1969
buildings as shown in the diagram
and was called ARPANET. It was an
below:
213
e2) Suggest the most suitable place
(i.e. block) to house the server of this
organisation with a suitable reason. 1

Ans)

The most suitable place / block to


house the server of this organisation
would be Block C, as this block
contains the maximum number of
computers, thus decreasing the
cabling cost for most of the computers
as well as increasing the efficiency of
the maximum computers in the
network.

e3) Suggest the placement of the


following devices with justification 1
i)Repeater
ii)Hub/Switch

Ans)
S)

For Layout 1, since the cabling


C
T

distance between Blocks A and C, and


G
(P

e1) Suggest a cable layout of that between B and C are quite large,
ar

so a repeater each, would ideally be


m

connections between the blocks.1


Ku

needed along their path to avoid loss


er
nd

Ans) of signals during the course of data


re

flow in these routes


Vi

Layout 1:

For layout 2, since the distance


between Blocks A and C is large so a
Layout Option 2: repeater would ideally be placed in
Since the distance between Block A between this path
and Block B is quite short

214
In both the layouts, a hub/switch Bandwidth is the capability of a
each would be needed in all the medium to transmit an amount of
blocks, to interconnect the group of information over a distance.
cables from the different computers in Bandwidth of a medium is generally
each block measured in bits per second (bps) or
more commonly in kilobits per second
(kbps)

b)Expand the following terminologies:1


(i) HTML (ii) XML

Ans)

Hypertext Markup Language


Extended Markup Language

c)Define the term firewall. 1

Ans)

Firewall is a feature used for Network


Security. In a Network there is always
danger of information leaking out or
S)

e4) The organization is planning to


C

leaking in. Firewall is a feature which


link its front office situated in the city
T
G

forces all information entering or


(P

in a hilly region where cable


leaving the network to pass through a
ar

connection is not feasible, suggest an


m

check to make sure that there is no


Ku

economic way to connect it with


unauthorized usage of the network.
er

reasonably high speed? 1


nd
re
Vi

Ans) d)What is the importance of URL in


networking? 1
The most economic way to connect it
Ans)
with a reasonable high speed would be
to use radio wave transmission, as
they are easy to install, can travel long URL stands for Uniform Resource
distances, and penetrate buildings Locator. Each page that is created for
easily, so they are widely used for Web browsing is assigned a URL that
communication, both indoors and effectively serves as the page’s
outdoors. Radio waves also have the worldwide name or address. URL’s
advantage of being omni directional, have three parts: the protocol , the
which is they can travel in all the DNS name of the machine on which
directions from the source, so that the the page is located and a local name
transmitter and receiver do not have uniquely indicating the specific
to be carefully aligned physically. page(generally the filename).

MODEL PAPER 2 FOR 2008-09: e)Ravya Industries has set up its new
center at Kaka Nagar for its office and
7.a)Define the term Bandwidth. Give web based activities. The company
unit of Bandwidth. 1 compound has 4 buildings as shown
in the diagram below:
Ans)
215
Ans)

The most suitable place / block to


house the server of this organisation
would be Raj Building, as this block
contains the maximum number of
computers, thus decreasing the
cabling cost for most of the computers
as well as increasing the efficiency of
the maximum computers in the
network.

e3) Suggest the placement of the


following devices with justification:1
i)Internet Connecting Device/Modem
ii)Switch

Ans)

(i)Raj Building
(ii)In both the layouts, a hub/switch
each would be needed in all the
buildings, to interconnect the group of
S)

cables from the different computers in


C
T

each block
G
(P
ar
m

e4) The organisation is planning to


Ku

e1) Suggest a cable layout of


link its sale counter situated in
er

connections between the buildings.1


nd

various parts of the same city, which


Ans)
re
Vi

type of network out of LAN, MAN or


Layout 1:
WAN will be formed? Justify your
answer. 1

Ans)

The type of network that shall be


formed to link the sale counters
situated in various parts of the same
Layout 2: Since the distance between city would be a MAN, because MAN
Fazz Building and Jazz Building is (Metropolitan Area Networks) are the
quite short networks that link computer facilities
within a city.

NETWORKS
FULL FORMS
e2) Suggest the most suitable place
(i.e. building) to house the server of TCP/IP – Transmission Control
this organisation with a suitable Protocol / Internet Protocol
reason. 1 LAN – Local Area Network
216
MAN – Metropolitan Area Network (Txd – Transmit, Rxd – Receive,
WAN – Wide Area Network RTS – Request to Send
Modem – Modulation(tor)/ CD – Carrier Detect,
Demodulation(tor) DSR – Data Set Ready,
URL – Uniform Resource Location CTS – Clear to Send
FTP – File Transfer Protocol DTR – Data Terminal Ready)
HTTP – Hyper Text Transfer Protocol RJ45 – Registered Jack – 45
PPP – Point to Point Protocol BNC – Bayone – Neill –
GSM – Global System for Mobile Concelman
CDMA – Code Division Multiple AUI – Attachment Unit Interface
Access SNA – Systems Network
WLL(WiLL)–Wireless in Local Loop Architecture
SMS – Short Message Service VFIR – Very Fast Infrared
WWW – World Wide Web URI – Uniform Resource Identifier
HTML – Hyper Text Markup URN – Uniform Resource Name
Language MIME – Mail and Multipurpose
XML – eXtensible Markup Internet Mail Extensions
Language POP – Post Office Protocol
NFS – Network File System SMTP – Simple Mail Transfer
Protocol
ARPANET – Advanced Research NNTP – Network News Transfer
Projects Agency Protocol
NSFnet – National Science Foundation HTTP – Hyper Text Transfer
NIU – Network Interface Unit Protocol
S)

NIC - Network Interface Card NTP – Network Time Protocol


C

TAP – Terminal Access Point IMAP – Internet Mail Transfer


T
G
(P

(NIU = NIC = TAP) Protocol


ar

VGM – Voice Grade Medium SLIP – Serial Line Internet


m
Ku

DGM – Data Grade Medium Protocol


er

STP – Shielded Twisted Pair IPCP – IP Control Protocol


nd
re

UTP – Unshielded Twisted Pair NCP – Network Control Protocol


Vi

LED – Light Emitting Diode LCP – Link Control Protocol


LD – Laser Diode PC – Personal Computer
Kbps – Kilo bits Per Second ISP – Internet Service Provider
KBps – Kilo Bytes Per Second SIM – Subscriber Identity Module
Mbps - Mega Bits Per Second TDMA – Time Division Multiple
MBps – Mega Bytes Per Second Access
Gbps - Giga Bits Per Second TDM – Time Division Multiplexing
GBps – Giga Bytes Per Second IDEN – Integrated Digital Enhanced
OFC – Optic Fiber Cable, Fiber Network
Optic Cable WCDMA –Wideband CDMA
KHz – Kilo Hertz PSTN – Public Switched Telephone
MHz – Mega Hertz Network
GHz – Giga Hertz 3G – Third Generation
THz – Tera Hertz UMTS – Universal Mobile
Bps – Bytes Per Second Telecommunications System
bps - Bits Per Second /Universal Mobile Telephone
PDA – Personal Digital Assistants System
P-P - Point to Point EDGE – Enhanced Data rates for
AM – Amplitude Modulation Global Evolution
FM - Frequency Modulation SMSC – Short Message Service
PM – Phase Modulation Center
A/F – Audio Frequency HLR – Home Location Register
217

Você também pode gostar