You are on page 1of 78

1. How are abstraction and encapsulation inter-related ?

Ans. Encapsulation wraps up data and functions under single unit and ensures
that only essential features get represented without representing the background
details which is nothing but Abstraction. Therefore, encapsulation also implements
abstraction.
2. How many times is the following loop executed ?
int s = 0, i = 0 ;
while (i < 5)
s += i++ ;
Ans. 5 times.
3. How many times is the following loop executed ?
int s = 0, i = 0;
do
s+= i ;
while (i < 5) ;
Ans. Infinite loop.
4. What is an inline function ?
Ans. An inline function is that which is not invoked (i.e., loaded afresh) at the time
of function call rather its code is replaced in the program at the place of function call
during compilation. Thus, inline functions save the overheads of a function call.
5.
Name the header file to be included for the use of following built-in
functions :
(i) frexp()
(iii) getc( )
(v) isupper()
(vii) exp( )
(ix) strcpy( )
(xi) log( )
(xiii) strcat( )
(xv) getchar()
(xvii) strcpy( )
(xix) puts( )
(xxi) cos( )

(ii) toupper()
(iv) strcat( )
(vi) setw( )
(viii) strcmp()
(x) isdigit( )
(xii) puts( )
(xiv) scanf( )
(xvi) clrscr( )
(xviii) getxy( )
(xx) gets( )
(xxii) setw( )

(xxiii) toupper( )

(xxiv) strcpy( )

(xxv) isalnum()
(xxvii) fabs( )

(xxvi) gets( )
(xxviii) strlen( )

(i) math.h
(iii)
stdio.h
(v)
ctype.h
(vii) math.h
(ix) string.h
9911396565

(ii) ctype.h
(iv) string.h
(vi) iomanip.h
(viii) string.h
(x) ctype.h
1

(xi) math.h
(xiii) string.h
(xv) stdio.h
(xvii) string.h
(xix) stdio.h
(xxi) math.h
(xxiii)ctype.h
(xxv) ctype.h
(xxvii)math.h

(xii) stdio.h
(xiv) stdio.h
(xvi) conio.h
(xviii) conio.h
(xx) stdio.h
(xxii) iomanip.h
(xxiv) string.h
(xxvi) stdio.h
(xxviii) string.h

6. Write the names of the header files, which is/are essentially required to
run/execute the following C++ code
void main( )
{
char C, String[ ] = "Excellence Overload";
for (int i = 0; String[i] != '\0'; i++)
if (String [i] == )
cout endl ;
else
{
C = toupper (String[i]) ;
cout << C ;
}
}
(i) iostream.h ctype.h.
7. Which C++ header file(s) will be essentially required to be included to
run/execute the following C++ code ?
void main( )
{
int Rno = 24;
char Name[ ] = "Amen SinOania" ;
cout << setw(10) << Rno << setw(20) << Name << endl ;
}
(i) iostream.h(ii) iomanip.h
8. Write the names of the header files to which the following belong :
(i) setw( )
(ii) sqrt( )
Ans. (i) iomanip.h (ii) math.h
9. What is object oriented programming ? How is it diff erent from
procedural programming?

9911396565

Ans. The object oriented programming depicts a problem in terms of classes and
objects involved. An object oriented program not only defines the classes and
objects involved but also provides a full set of operations in the class. It makes
use of principles of data hiding, encapsulation, abstraction, inheritance and
polymorphism.
The procedural programming depicts a problem in terms of a list of instructions where
each statement tells the computer to do something. The focus is not on the data but
on processing i.e., algorithm needed to perform the desired computation.
The OOP focuses mainly on data and associated functions whereas procedural
programming focuses on processing.
10.

Explain the following:

Data abstraction refers to the act of representing the essential features without
including the background details or explanations. For example, in a 'switch board', you
only press certain switches according to your requirement. What-is happening inside,
how it is happening, you needn't know. This is abstraction.
Encapsulation is the wrapping up of data and functions (that operate on the data)
into a single unit (called class). Encapsulation ensures that data of a class can be
accessed only by authorized functions (member functions and friend functions of a
class). The data cannot be accessed directly, thus, it is safe from accidental
alteration.
Inheritance refers to the capability, of one class of things to inherit capabilities or
properties from another class. For instance, the class 'car' inherits some of its
properties from the class 'Automobiles' which inherits some of its properties from
another class 'Vehicles'. The inheritance not only ensures the closeness with real world
but also supports reusability of code.
Polymorphism is the property by which the same message can be sent to objects of
several different classes, and each object can respond to it in a different way
depending upon its class. For example, 6 +9 results into 15 but 'X' + YZ' results into
'XYZ. The same operator symbol '+' is able to distinguish between the two
operations (summation and concatenation) depending upon the data type it is
working on.
11.What is a base class ? What is a derived class ? How are these two
interrelated ?
Ans. A derived class is a class that inherits properties from some other class. It is
also known as sub class.
A base class is a class whose properties are inherited by its derived class. It is also
known as super class.
A derived class inherits properties from base class but reverse is not true.
12.

What is the difference between a keyword and an identifier ?

9911396565

Ans. Keyword is a special word that has a special meaning and purpose. Keywords
are reserved and are a few. For example, goto, switch, else etc. are keywords in C++.
Identifier is the user-defined name given to a part of a program viz. variable, object,
function etc. Identifiers are not reserved. These are defined by the user and they can
have letters, digits & a symbol underscore. They must begin with either a letter or
underscore. For instance, _chk, chess, trial etc. are valid identifiers in C+ +.

(a) strcmp() ) is contained in string.h (b) randomize( ) is contained


in stdlib.h
(c) setw( ) is contained in iomanip.h(d) isalnum( ) is contained in
ctype.h
(d) sin( ) is contained in math.h (f) gotoxy( ) is contained in conio.h
13.

What is the different type of Casting?

Explicit Type Casting is used by the programmer to convert value of one type to
another type. It is forced type conversion. It is done by putting the target datatype in
parentheses before the data to be converted, for example, in the following statement
15 would be type cast into 15.0 first.
float x = (float)15 / 4;
//3.75 will be assigned as result.
Automatic Type Conversion is the type conversion done by the compiler itself
wherever required. It is implicit type conversion, e.g., in the following code before
assigning the value 3 to float x, it will be automatically converted to 3.0.
float x = 3;
14.
What are actual and formal parameters of a function ? Can both take
the same names ?
Ans. The parameters that appear in a function call statement are called actual
parameters and the parameters that appear in function header of called function are
called formal parameters. For example,
int main( )
{
int a ; char b;
.
.
check (a, b) ;
.
.
}
void check (int x, char y)

}
In the above code, a and b are actual parameters and x and y are formal
parameters.
Yes, both actual and formal parameters can take the same names. But even after
having same names they'll remain different because their scopes will be different.
9911396565

15.What is the difference between Local Variable and Global Variable ? Also,
give a suitable C++ code to illustrate both.
The differences between a local variable and global variable are as given below
:
Local Variable

Global Variable

1. It is a variable which is declared


within a function or within a block
2. It is accessible only within a
function/block in which it is declared

It is variable which is declared


outside all the functions
It is accessible throughout the
program

16.What is the difference between call by value and call by reference ?


Give an example in C++ to illustrate both.
In call by value method, the called function creates its own copies of the original
values sent to it. Any changes, that are made, occur on the called function's copy of
values and are not reflected back to the calling function.
In call by reference method, the called function accesses and works with the original
values using their references. Any changes, that occur, take place on the original
values and are reflected back to the calling code.
Call By Value
int main( )
Call By Reference
{ int a = 5 ;
int main( )
{ int a = 5 ;
cout << " a = " << a ; change
cout << " a = " << a ; change
(a) ;
(a) ;
cout << " \n a = " << a return
cout << " \n a = " << a return
0;
0;
}
}
void change (int b) { b = 10
;
}
Output will be :
a = 5;
a = 5;

void change (int & b)


{ b = 10 ;
}
Output will be :
a=5
a= 10

17.
Will the following program execute successfully ? If not, state the
reason(s).
#include<stdio.h>
void main( )
{ int s1, s2, num ;
sl = s2 = 0 ;
for (x = 0;x<11;x++)
{
cin<< num ;
if (num > 0)
s1 += num ;
9911396565

else
s2 = / num ;
}
cout << s1 << s2 ;
}
Ans. x not declared
cin << num is wrong.
s2 = /num ; is wrong.

It should be cin >> num ;


It should be s2 / = num ;

18. What output will be produced by following codes ?


(a) Int i;
(b) int i;
i = -12 ;
= -12 ;
do
do
{
{
cout << i << endl ;
cout << i << endl ;
i=i-1;
i=i-1;
}
}
while (i > 0) ;
while (i < 0) ;
Ans. (a) - 12.
(b) It is an endless loop. It will keep displaying values -12, -13, -14, ..
19. Describe the output produced by the following program
#include<iostream.h>
#include<conio.h>
void main( )
{
clrscr( ) ;
int Z[3][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} ;
int a, b ;
for(a = 0 ; a < 3 ; ++a)
for( b = 0 ; b < 4 ; + + b )
if(Z[a][b] % 2 == 1)
Z[a][b]-- ;
for (a = 0; a < 3 ; ++a)
{

cout << endl ;


for(b = 0 ; b < 4 ; ++b)
cout << Z[a][b] << "\t" ;

}
}
Ans. The above program checks whether an array element is odd or not. If it
is, it is decremented by 1 and later the entire array is printed as follows :
0
2
2
4
9911396565
6

4
8

6
10

6
10

8
12

20. Observe the following program and find out, which output(s) out of (i)
to
(iv)
will
not
be
expected from the program? What will be the minimum and the
maximum
value
assigned to the variable Turn?
#include<iostream. h >
#include<stdlib.h>
void main( )
{
randomize( ) ;
int Game[ ] = {10, 16}, P;
int Turn = random(2) + 5 ;
for (int T = 0 ; T < 2 ; T++)
{
P = random(2) ;
cout<< Game[P] + Turn<< "#" ;
}
}
(i) 15#22#
(ii) 22#16# (iii) 16#21#(iv) 21#22#
Ans. Outputs (i), (iii) and (iv) will not be expected.
(ii) Minimum value = 5, Maximum value = 6

21. Find the output of the following program :


#include<iostream.h>
#include<ctype .h>
typedef char Str80[80] ;
void main( )
{
char *Notes ;
Str80 Str = "vR2GooD" ;
int L = 6 ;
Notes = Str ; while(L >= 3)
{
Str[L] = (isupper(Str[L]) ? tolower(Str[L]) : toupper(Str[L])) ;
c ou t<< No te s<< e n dl ;
L-- ;
Notes++ ;
}
}
Ans.
v R2 G o od
R2GoOd
2GOOd
gOOd
22. Find the output of the following program :
#include<iostream.h>
9911396565

#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#
19#17#
(iii) 19#16#
(iv) 20#16#
r
Ans. Output (1), (ii) and (iv) would not be expected. Minimum . value = 10,
Maximum value =11.
23. Go through the C++ code shown below, and find out the possible
output.
#include <iostream.h>
#include <stdlib.h>
void main( )
{
randomize( ) ;
int MyNum, Max = 5;
MyNum = 20 + random (Max) ;
for (int N = MyNum ; N <= 25 ; N++)
cout << N << "*";
(i) 20*21*22*23*24*25
(iii) 23*24*

(ii) 22*23*24*25*
(iv) 21*22*23*24*25

Ans. (ii) 22*23*24*25*


Minimum possible value =20, Maximum possible value
=24
24. Find the output of the following program :
#include<iostream.h>
#include<ctype.h>
void ChangeIt(char Text[ ], char C)
{
for (int K = 0 ; Text[K]!= '\0'
; K++)
{
if(Text[K] >= 'F' && Text[K] <= 'L')
Text[K] = tolower(Text[K]) ;
else if(Text[K] = = 'E' I I Text[K] = = 'e')
Text[K] = C ;
else i f ( K % 2 = = 0 )
Text[K] = toupper(Text[K]) ;
9911396565

else
Text[K] = Text[K 1];
}
}
void main( )
{
char OldText[ ] = "pOwERALone" ;
Changelt (OldText, '%') ;
cout <<"New TEXT: "<< OldText << endl ;
}
Ans. P P W % R R l l N %
25. The following code is from a game, which generates a set of 4 random
numbers : Yallav is playing this game, help him to identify the correct
option(s) out of the four choices given below as the possible set of such
numbers generated from the program code so that he wins the game. Justify
your answer.
#include <iostream.h>
#include <stdlib.h>
const int LOW = 15 ;
void main( )
{
randomize( ) ;
int POINT = 5, Number ;
for (int I = 1 ; I < = 4 ; I++)
{
Number = LOW + random(POINT) ;
c ou t << Nu mb e r<< ":" ;
POINT-- ;
}
}
(i)
19 : 16 : 15 : 18 :
(ii)
14 : 18 : 15 : 16 :
(ii)
19 : 16 : 14 : 18 :
(iv)
19 : 16 : 15 : 16 :
Ans. (iv)
19 : 16 : 15 : 16 :
Reason being
For first pass Number is low + random (5)
i.e.,
For 2nd pass Number is 15 + is random (4)
i.e.,
For 3rd pass Number is 15 + random (3)
For 4th pass Number is 15 + random (2)
Only option (iv) matches the ranges generated.

15 + (0 - 4) i.e., 15 to 19
15 to 18
i.e., 15 to 17
i.e., 15 to 16

26. Study the following program and select the possible output from it :
#include <iostream.h>
#include <stdlib.h>
const int LIMIT = 4 ;.
void main( )
{
randomize( ) ;
int Points ;
Points = 100 + random (LIMIT) ;
for (int P = Points ; P >= 100 ; P- -)
cout << P << "#" ;
cout << endl ;
9911396565

}
(i) 103#102#101#100#
(ii) 100#101#102#103#
(iii) 100#101#102#103#104# (iv) 104#103#102#101#100#
Ans. (i) 103#102#101#100#.

9911396565

10

27. Study the following program and select the possible output from
it :
#include <iostream.h>
#include <stdlib.h>
const int MAX = 3;
void main( )
{
randomize( ) ;
int Number ;
Number = 50 + random (MAX) ;
for (int P = Number ; P >= 50 ; P- -)
cout << P << "#" ;
cout << endl ;
}
(i) 53#52#51#50#
(ii) 50#51#52#(iii) 50#51#
(iv) 51#50#
Ans. (iv) 51#50#
28. In the following program, find the correct possible output(s) from the
options :
#include <stdlib.h>
#include <iostream.h>
void main( )
{
randomize( ) ;
char City [ ] [10] = {"DEL","CHN","KOL","BOM","BNG"} ;
int Fly ;
for (int i =0; i <3 ; i++)
{
Fly = random(2) + 1 ;
cout << City[ Fly] << ":" ;
}
}
Outputs :
(i) DEL : CHN : KOL :
(ii) CHN : KOL : CHN :
(iii) KOL : BOM : BNG : (iv) KOL : CHN : KOL :
Ans. (ii) and (iv) will give correct possible outputs.
29.Find the output of the following program :
#include<iostream.h>
#include<string.h>
#include<ctype.h>
void Convert(char Str[ ], int Len)
{
for(int Count = 0 ; Count < Len ; Count++)
{
if(isupper(Str[Count]))
Str[Count] = tolower(Str[Count]) ;
else if (islower(Str[Count]))
Str[Count] = toupper(Str[Count]) ;
else if (isdigit (Str[Count]))
Str[Count] = Str[Count] + 1 ;
else Str[Count] = '*' ;

}
}
void main()
{
char Text[ ] = "CBSE Exam 2005" ;
int Size = strlen(Text) ;
Convert (Text, Size) ;
cout << Text << endl;
for (int C = 0, R = Size - 1 ; C <= Size/2 ; C++, R--)
{
char Temp = Text[C] ;
Text[C] = Text[R] ;
Text[R] = Temp ;
}
c o u t < < Tex t < < e n d l ;
}
Ans. cbse*eXAM*3116
6113*MAXe*esbc
30. What will be the output of the following program :
#include<iostream.h>
void main( )
{
int v1 = 5, v2 = 10;
for (int x = 1 ; x < = 2 ; x++)
{
c o u t < < + + v 1 < < "\ t "< < v 2 - - < < e n d l ;
cout << -- v2 < < "\ t "< < vl ++ << endl ;
}
}
Ans.
6
10
8
6
8
8
6
8
31.
Give the output of the following program segment :
void main( )
{
char *NAME = "CoMPutER" ;
for (int x = 0 ; x < strlen(NAME) ; x++)
if(islower(NAME[x]))
NAME[x] = toupper(NAME[x]);
else if (isupper(NAME[x]))
if (x % 2 = = 0)
NAME[x] = tolower(NAME[x]) ;
else
NAME[x] = NAME[x - 1] ;
puts( NAME) ;
}
Ans.
cOmmUTee
32. Find the output of the following program :
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 <<"#";
cout << endl ;
for (L = 0 ; L < 2 ; L++)
cout << C[L] << "#" ;
}
Ans.
7#9#5#
30#50#70#40#
2100#1200#
33. Find the output of the following program :
#include<iostream.h>
struct POINT
{ int X, Y, Z ; } ;
void Stepin(POINT &P, int Step = 1)
{
P.X += Step ;
P.Y -= Step ;
P.Z += Step ;
}
void StepOut(POINT &P, int Step = 1)
{
P.X -= Step ;
P.Y += Step ;
P.Z -= Step ;
}

Ans.

void main( )
{
POINT P1 = {15, 25, 5}, P2 = {10, 30, 20} ;
StepIn(P1) ;
StepOut(P2, 4) ;
cout << Pl.X << ","<< Pl.Y << "," << Pl.Z << endl ;
cout << P2.X << "," << P2.Y << "," << p2.z << endl ;
Stepin(P2, 12) ;
cout << P2.X << "," << P2.Y << "," << p2.z << endl ;
}
16,
24,
6
6,
34,
16

18,

22,

28

35. Find the output of the following program :


#include <iostream.h>
#include <ctype.h>
void main( )
{
char Text( ] = "Mind@Work!" ;
for (int i = 0 ; Text [i] != '\0 ' ; i++)
{
if (!isalpha (Text[i]))
Text(i] = "*" ;
else if (isupper (Text[i]))
Text[i] = Text[i] + 1 ;
else
Text[i] = Text [i + 1] ;
}
cout << Text ;
}
Ans.Nnd@*Xrk !*
36. Find the output of the following program : softzone
#include<iostream.h>
struct Package
{
int Length, Breadth, Height ;
};
void Occupies(Package M)
{
cout << M.Length << "x" << M.Breadth << "x" ;
cout << M.Height << endl ;
}
void main( )
{
Package P1 = {100, 150, 50}, P2, P3 ;
++P1.Length ;
Occupies(P1) ;
P3= P1;
++P3.Breadth ;
P3.Breath++ ;
Occupies(P3) ;
P2= P3;
P2.Breadth += 50 ,
P2.Height - -;
Occupies(P2) ;
}
Ans. 101 x 150 x 50
101 x 152 x 50
101 x 202 x 49
37. Give the output of the following program :
#include < iostream.h>

int g = 20 ;
void func(int &x, int y)
{
x=x-y;
y= x* 10;
c o u t < < x < < ' , ' < < y < < "\ n " ;
}
void main( )
{
int g = 7 ;
func(g, ::g) ;
c o u t < < g < < ' , ' < < : : g < < "\ n "
func (:: g, g) ;
cout<<
g < < ' , ' < < : : g "\ n "
}
Ans.
-13, -130
-13, 20
33, 330
-13, 33

;
;

38.What is abstract class ?


Ans. An abstract class is a class that defines an interface, but does not necessarily
provide implementations for all its member functions. No objects of an abstract
class exist i.e., it cannot be instantiated.
39.What is polymorphism in software terms ?
Ans. Polymorphism is a way to implement multiple behaviors in response to one
situation. Polymorphism is the attribute that allows one interface to be used with
multiple situations.
40.How is polymorphism implemented in C++ ?
Ans. Polymorphism is implemented in C++ through virtual functions and
overloading function overloading and operator overloading.
41. What is function overloading ?
Ans. A function name having several definitions that are differentiable by the
number or types of their arguments is known as an overloaded function and
this process is known as function overloading.
42.What is the importance of function overloading ?
A n s . Fu n c ti on ov e r l o ad i n g n ot on l y implements polymorphism but also
reduces number of comparisons in a program and thereby makes the
program run faster.
43.What is access specifier ?
Ans. Access specifier is a way to specify scope and accessibility of members of a
Class. Access specifi ers can be either private, protected or public.
44.What is a constructor ?
Ans. A member function with the same name as its class is called constructor
and it is used to create and initialize the objects of that class type with a legal
initial value.

45. What is a destructor ?


Ans. A destructor is also a member function whose name is the same as the class
name but is preceded by tilde
( ~ ). A destructor destroys the objects that have been created by a constructor. It
destroys the values of the object being destroyed.
46.
When is a constructor called ?
Ans. A constructor is automatically called at the time of object declaration and
creation.
47.
When is a destructor called ?
Ans. A destructor is automatically called Allen an object goes out of scope.
48. What is a copy constructor ?
Ans. A copy constructor is a constructor that is invoked when an object is
defined and i n i ti a l i z e d wi t h an ot h e r o b j e ct . A c o p y constructor takes the
following form :
classname (classname &)
49.
What does inheritance mean ?
Ans. Inheritance is the capability of one class of things to derive capabilities
or properties from another class. In C++, a class inheriting its properties from
another class, is known as subclass or derived class. The class, whose properties
are inherited, is known as base class or super class.
50.
Why is protected accessibility needed ?
Ans. The members having protected accessibility are hidden from outside
world (like private members) but when inherited, they remain visible in the
derived class (unlike private members).
51.
What are the advantages and
disadvantages of inline function's ?
Ans. The main advantage of inline functions is that they save on the overheads of a
function call as the function is not invoked, rather its code is replaced in the
program.
The major disadvantage of inline functions is that with more function calls,
more memory is wasted as for every function call, the same function code is
inserted in the program. Repeated occurrences of same function code waste
memory space.
52. What do you understand by a default constructor ? What is its role ?
How is it equivalent to a constructor having default arguments ?
Ans. A default constructor is the one that takes no arguments. It is automatically
invoked when an object is created without providing any initial values. In case, the
programmer has not defined a default constructor, the compiler automatically
generates it.
It is equivalent to a constructor having default arguments because when no
initial values are provided for an object at the time of its declaration, the
constructor having default argument values is invoked same way as the default
constructor is invoked. Therefore, these two are considered equivalent.
53. How many times is the copy constructor called in the following
code ?
Sample func(Sample u)

{
Sample v(u) ;
Sample w = v ;
return w ;
}
void main( )
{
Sample x ;
Sample y = func(x) ;
Sample z = func(y);
}
Ans The copy constructor is called 8 times in this code. Each call to the function func(
) requires calls to the copy constructor :
(i) When the parameter is passed by value by u
(ii) when v is initialized
(iii) when w is initialized
(iv) when w is returned.
54. What is the difference between the members in private visibility
mode and the members in protected visibility mode inside a class ?
Also, give a suitable C++ code to illustrate both.
Ans. The protected members of the base class are inherited by the derived class
and are accessible to the derived class.
The private members of the base class are not directly accessible to the derived
class.
Example :
class A
{ private :
int val ;
protected
int value ;
public :
void fl( ) ;
};
class B : public A
{
}
Now protected member value of class A would be directly accessible by members of
class B but the private member val of class A would not be directly accessible by
members of class B.
55. Answer the questions (i) and (ii) after going through the following
program :
class Match
{
int Time ;
public:
Match( )
//Function 1
{
Time = 0 ;
cout <<"Match commences" <<endl ;
}

void Details( )
//Function 2
{
cout<< "Inter Section Basketball Match" << endl ;
}
Match(int Duration)
//Function 3
{
Time = Duration ;
cout<< "Another Match begins now"<< end I ;
}
Match(Match &M )
//Function 4
{
Time = M. Duration ;
cout << "Like Previous Match" << endl ;
}
(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.

Ans. (i) Copy constructor. It is used to copy the data from an existing object to
another being constructed.
(ii)
Match M ;
//Function 1
Match N(10) ;
//Function 3
56. Answer the questions (i) and (ii) after going through the
following class :
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) Constructor Overloading (or Function Overloading or
Polymorphism).
(ii) Destructor. A destructor is invoked when an object goes out of
scope.
57.
Consider the following code fragment:
int x = 5;
int y = 3;
class Outer
{
public:
int x;
int a;
static int s;
class inner
{
int a ;
public :
void f(int i)
{ x = i;
s=i;
y = i;
a=i;
}
};
Inner I1 ;
void g(int i)
{
x= i;
y= I;
s=i;
}
};
//Outer definition over.
Outer O1 ;
//Outer object
int main( )
{
O1.I1.f(3) ; //statementl
01.g(8) :
//statement2
return 0 ;
}
What will be the values of ::x, : y, Outer::x, Outer::a, Outer::s, Inner::a
after statement 1 and statement 2 of above code ?
After statement 1
::x = 5 ; ::y = 3 ; Outer: :x = 3 ; Outer: :a = Not Defined ; Outer: :s = 3 ;
Inner::a = 3
After statement 2

::x = 5 ; ::y = 8 ; Outer: :x = 8 ; Outer: :a = 8 ; Outer: :s = 8 ; Inner: :a = Its


previous value.
58.
Show the output of the following program :
# incIude <iostream h >
class Base
{
public :
Base( )
{ c o u t < < " B a se " < < e n d l ; }
Base(int i)
{ cout << "Base" << i << endl ; }
~Base( )
{ cout < < "Destruct Base" < < endl ; }
};
class Der : public Base
{
public :
Der( )
{ c ou t < < "D e r" < < e n dl ; }
Der(int j) : Base( i )
{ cout < < "Der" < < i << endl ; }
~Der( )
{ cout < < "Destruct Der" < < endl ; }
};
int main( )
{
Base a;
Der d(2) ;
return 0 ;
}
Ans.
Base
Base 2 .
Der 2
Destruct Der
Destruct Base
Destruct Base
59.
Define a class CARRENTAL in C++ with the following
description :
Private Members
CarlD of type long int
AboutCar of type string
Cartype of type string
Rent of type
float
A member function AssignRent( ) to assign the following values for Rent as per
given Cartype
Cartype
Small

Public Members

Rent
1000

Van

800

SUV

2500

A function GETCar( ) to allow user to enter values for CarID, AboutCar,


Cartype and call function AssignRent( ) to assign Rent.
A function ShowCar( ) to allow user to view the content of all the data
members.
Ans.
class CARRENTAL
{
long int CarID ;
char AboutCar[20] ;
char Cartype[6] ;
float Rent ;
void AssignRent( ) ;
public :
void GetCar( ) ;
void ShowCar( ) ;
};
void CARRENTAL : : AssignRent( )
{
if(strcmp(Cartype, "Small") == 0)
Rent = 1000 ;
else if(strcmp(Cartype, "Van") == 0)
Rent = 800 ;
else if(strcmp(Cartype, "SUV") == 0)
Rent = 2500 ;
}
void CARRENTAL : : GetCar( )
{
cout < < "Car ID : " ; cin >>CarID ;
cout < < "Description : " ; gets(AboutCar)
;
cout < < "Car Type : " ; gets(Cartype) ;
AssignRent( ) ;
}
void CARRENTAL : : ShowCar( )
{
c o u t < < " C ar ID : " < < C a r ID < < e n d l ;
cout < < "De scrip tion : " < < AboutCar
< < endl ;
cout << "Car Type : " < < Cartype < < endl ;
c o u t < < " Re n t : " < < Re n t < < e n d l ;
}
60.
Define a class Candidate in C++ with the following description
Private Members
A data member RNo (Registration Number) of type long
A data member Name of type string
A data member Score of type float
A data member Remarks of type string

A member function AssignRem( ) to assign Remarks as per the Score


obtained by a candidate. Score range and the respective Remarks are
shown as follows :
Score
>=50
Less than 50

Remarks
Selected
Not Selected

Public Members
A function ENTER() to allow user to enter values for RNo, Name,
Score and call function AssignRem() to assign the remarks.
A function DISPLAY() to allow user to view the content of all the data
members.
Ans.
class Candidate
{
long RNo ;
char Name[30] ;
float Score ;
char Remarks[50] ;
void AssignRem( )
{
if(Score >= 50)
strcpy(Remarks, "Selected") ;
else
strcpy(Remarks, "Not Selected") ;
}
public :
void ENTER( )
{
cout << "Enter Registration No : " ;
cin >> RNo ;
cin.ignore( ) ;// to empty the input stream
cout <<"Enter Name : " ;
cin.getline(Name, 30) ;
cout << "Enter Score : " ;
cin >> Score ;
AssignRem( ) ;
}
void DISPLAY( )
{
cout << "Registration No. : " << RNo << endl ;
cout << "Name : " << Name << endl ;
cout << "Score : " << Score << endl ;
cout << "Remarks : " << Remarks << endl ;
}
};
61.

Define a class Garments in C++ with the following descriptions :


Private Members
GCode
GType
GSize

:
of type string
of type string
of type integer

GFabric
GPrice

of type string
of type float

A function Assign( ) which calculates and assigns the value of GPrice as follows :
For the value of GFabric "COTTON",
GType

GPrice(Rs.)

TROUSER
1300
SHIRT
1100
For GFabric other than "COTTON" the above mentioned GPrice gets
reduced by 10%
Public Members:
A constructor to assign initial values of GCode, GType and GFabric with
the word "NOT ALLOTTED" and GSize and GPrice with 0.
A function Input( ) to input the values of the data members GCode, GType,
GSize and GFabric and invoke the Assign( ) function.
A function Display( ) which displays the content of all the data
members for a Garment.
Ans.
class Garments
{
char GCode[ 15] ;
char GType[ 15] ;
int GSize ;
char GFabric[15] ;
float GPrice ;
void Assign( )
{
if (strcmp(GFabric, "COTTON") == 0)
{
if(strcmp(GType, "TROUSER") == 0)
GPrice = 1300 ;
else if (strcmp(GType, "SHIRT") == 0)
GPrice = 1100 ;
}
else
{
if(strcmp(GType, "TROUSER") == 0)
GPrice = 1300 - 0.10 * 1300 ;
else if(strcmp(GType, "SHIRT") == 0)
GPrice = 1100 - 0.10 * 1100 ;
}
}
public:

Garments( )
{
strcpy(GCode, "NOT ALLOTED") ;
strcpy(GType, "NOT ALLOTED") ;
strcpy(GFabric, "NOT ALLOTED") ;
GSize = 0 ;
GPrice = 0 ;
}
void Input( )
{
cout << "Enter Garment Code" ;
cin>> GCode ;
cout << " \n Enter Garment Type (TROUSER/SHIRT)" ;
cin>> GType ;
cout << "\n Enter Garment Size : "
gets(GSize) ;
cout << "\n Enter Garment Fabric : " ;
gets(GFabric) ;
Assign( ) ;
}
void Display( )
{
cout << " Garmen t C ode : " << GC od e << endl ;
cout << "Garment Type : " << GType << endl ;
c ou t << " Garmen t Si ze : " << GS i ze << e n dl ;
cout << "Garment Fabric : " << GFabric endl ;
cout << "Garment Price : " << GPrice << endl ;
}

62.

Define a class Tour in C++ with the descriptions given below :


P riv at e Me m be rs
TCode
of type string
NoofAdults
of type integer
NoofKids
of type integer
Kilometres
of type integer
TotalFare
of type float

Public Members :
A constructor to assign initial values as follows :
TCode with the word "NULL"
NoofAdults as 0
NoofKids as 0
Kilometres as 0
TotalFare as 0

A function AssignFare( ) which calculates and assigns the value of the data member Total
as follows
For each Adult
Fare(Rs)
500
300
200
For each kid the above Fare
table
For example .

For
Kilometers
>=1000
< 1000 &
>=500
<500
will be 50% of the Fare mentioned in the above

If Kilometres is 850, NoofAdults = 2 and NoofKids = 3


Then TotalFare should be calculated as
NoofAdults * 300 + NoofKids * 150
i.e., 2 * 300 + 3 * 150 = 1050
A function EnterTour( ) to input the values of the data members TCode,
NoofAdults, NoofKids and Kilometres ; and invoke the AssignFare( )
function.
A function ShowTour( ) which displays the content of all the data members
for a Tour.
Ans.
class Tour
{
char TCode[15] ;
int NoofAdults ;
int NoofKids ;
int Kilometres ;
float TotalFare ;
public :
Tour( )
{
strcpy(TCode, "NULL") ;
NoofAdults = 0 ;
NoofKids = 0 ;
Kilometres = 0 ;
TotalFare = 0 ;
}
void AssignFare( )
{
int i , j ;
TotalFare = 0 ;
for(i = 0 ; i < NoofAdults ; i++)
{
if(Kilometres >= 1000)

TotalFare += 500 ;
else if(Kilometres >= 500)
TotalFare += 300 ;
else
TotalFare += 200 ;
}
for(j = 0 ; j < NoofKids ; j++)
{
if(Kilometres >= 1000)
TotalFare += 500/2 ;
else if(Kilometres > = 500)
TotalFare += 300/2 ;
else
TotalFare += 200/2 ;
}
}
void EnterTour( )
{
cout << "Enter TCode : " ;
gets(Tcode) ;
cout << "NoofAdults : " ;
cin>> NoofAdults ;
cout<< "NoofKids : " ;
cin >>Noof Kids ;
cout << "How many Kilometres" ;
cin >> Kilometres ;
AssignFare( ) ;
}
void showTour( )
{
cout << "Tcode : "<< Tcode << endl ;
cout << "Number of Adults : " << NoofAdults << endl ;
cout << "Number of Kids : " << NoofKids << endl ;
cout << "Kilometres : " << Kilometres << endl ;
cout << "Total Fare : " << TotalFare << endl ;
}
}
63.
Define a class TravelPlan in C++ with the following
descriptions Private Members :
Private Members
PlanCode
of type long
Place
of type character array (string)
Number_of_travellers
of type integer
Number_of_buses
of type integer
Public Members

A constructor to assign initial values of PlanCode as 1001, Place as


"Agra", Number_of_travellers as 5, Number_of_buses as 1
A fun ction Ne wPl an ( ) whi ch allows u se r to enter Pl an Code , Pl ace
and Number_of_travellers. Also, assign the value of Number_of_buses as
per following conditions :
Number_of_travellers
Number_of_buses
Less than 20
Equal to or more than 20 and
Equal to 40 or more than 40

1
2
3

A function ShowPlan( ) to display the content of all the data members on


screen.
Ans.
class TravelPlan
{
long PlanCode ;
char * Place ;
int Number_of_travellers ;
int Number_of_buses ;
public :
TravelPlan( )
{
PlanCode = 1001 ;
strcpy(Place, "Agra") ;
Number_of_travellers = 5 ;
Number_of_buses = 1 ;
}
void NewPlan( )
{
cout << "Enter Travel Code, Place and No. of travellers\n" ;
cin >> PlanCode ;
gets (Place) ;
cin >>
Number_of_travellers ;
if (Number_of_travellers <
20)
Number_of_buses = 1 ;
else if (Number_of_travellers < 40)
Number_of_buses = 2 ;
else
Number of_buses = 3 ;
}
void ShowPlan( )
{
cout << "Plan Code : " << PlanCode << endl ;
cout << "Place : " << Place << endl ;
cout << "No. of Travellers : " << Number_of_travellers <<
endl ;
cout << "No. of Buses : " << Number of_buses << endl ;
}
}

64.

Define a class Play in C++ with the following specifications:


Private members of class Play
Playcode
integer
PlayTitle
25 character
Duration
float
Noofscenes
integer
Public member function of class Play
A constructor function to initialise duration as 45 and Noofscenes as 5.
NewPlay( ) function to accept values for Playcode and PlayTitle.
Moreinfo( ) function to assign the values of Duration and Noofscenes
with the help of corresponding values passed as parameters to this
function.
Shoplay( ) function to display all the data members on the screen.

Ans. class Play


{
int Playcode ;
charPlayTitle[25] ; float
Duration ;
int Noofscenes ;
public :
Play( )
{
Duration = 45 ;
Noofscenes = 5 ;
}
void Newplay( )
{
cout << "\nEnter the code for Play : " ;
cin >>Playcode ;
cout<< "\nEnter the title of a Play : "
gets(PlayTitle) ;
}
void Moreinfo(float dur, int nos)
{
Duration = dur ;
Noofscenes = nos ;
}
void Shoplay( )
{
cout <<"\nPlay Code: "<<Playcode ;
cout << "\nPlayTitle : " << PlayTitle ;
cout <<"\nDuration : "<< Duration ;
cout<< "\nNo of episodes : "<<Noofscenes;
}
};

65.

Define a class Student for the following specifications :


Private members of the Student are :
roll_no
integer
name
array of characters of size 20
class_st
array of characters of size 8
marks
array of integers of size 5
percentage
float
calculate
that calculates overall percentage marks and
returns the percentage
Public members of the Student are :
readmarks
reads marks and invokes the calculate function
displaymarks prints the data

Ans.
class Student
{
int roll_no ;
char name[20] ;
char class_st[8] ;
int marks[5] ;
float percentage ;
float calculate( ) ;
public:
void read marks( ) ;
void displaydata( ) ;
};
float Student :: calculate( )
{
fl oat p = 0 ;
int tot = 0 ;
for(int i = 0 ; i < 5 ; i++)
tot += mark[i] ;
p = (tot/500.0) * 100 ;
return p ;
}
void Student :: readmarks( )
{
cout << "Enter roll number : " ;
cin >> roll_no ;
cout << "Enter name : " ;
gets(name) ;
cout <<"Enter class : " ;
gets (class_st) ;
cout <<"Enter marks in 5 subjects : " ;
for(int i = 0 ; < 5 ; i++)
cin >>marks[i] ;
percentage = calculate( ) ;
}

void Student : : displaydata( )


{
cout <<"Roll number : " << roll_no < < endl ;
cout <<"Name : " <<name << endl ;
cout <<"Class : " <<class1 <<endl ;
cout << "Marks in 5 subjects : " ;
for(int i = 0 ; i < 5 ; i++)
c ou t <<ma rk s[i ] <<" ," ;
cout << endl ;
cout<< "Percentage : << percentage<< "%" ;
}
66.
Declare a class to represent bank account of 10 customers with the
following data members. Name of the Depositor, Account Number, Type of
Account, (S for Savings and C for Current), Balance amount. The class
also contains member functions to do the following :
(i) To initialize data members
(ii) To deposit money
(iii)
For withdrawal of money after checking the minimum balance (minimum
balance is 1000)
(iv) To display the data members.
Ans. class Account
{
char name[31] ;
int acc_no ;
char act ;
float balance ;
public:
void initial( )
{
cout << "Name :" ;
cin.getline(name, 31) ,
cout << "Account Number :" ;
cin >> acc_no ;
int cc = 1 ;
while(cc)
{
cout << "Account type saving/Current(S/C) :" ;
cin >> act ;
if( (toupper(act) = = 'S' II toupper(act) == 'C'))
break ;
else
cout << "Enter S or C only!\n" ;
}
act = toupper(act) ;
cout << "Balance :" ;
cin >> balance ;
cout << endl ;
}
void deposit(float amt );

void withdraw(float amt) ;


void display( ) ;
int getacno( )
{
return acc_no ;
}
};
void Account :: deposit(float amt)
{
balance += amt ;
cout << "\n.Amount Deposited\n" ;
}
void Account :: withdraw(float amt)
{
if(balance - amt >= 1000))
{
balance - = amt ;
cout << "\n Amount Withdrawn\n" ;
}
else
{
cout << "Minimum balance has to be 1000/- " << endl ;
cout << "You can withdraw upto" << balance - 1000 <<
"Rupees" << endl ;
cout << "\nPress a key to continue...\n" ;
}
}
void Account :: display( )
{
cout << "Account Number :" << acc_no << endl ;
cout < < "Account Holder :" ;
cout.write(name, 31) ;
cout << "\nAccount type : " << act << endl ;
cout << "Balance(Rs.) :" << balance << endl ;
}
67.

Define a class report with the following specification

Private Members
adno
name
marks
average
getavg()

4 digit admission number


20 characters
an array of 5 floating point values
average marks obtained
to compute the average obtained in five subjects

Public Members
readinfo( )
function to accept values for adno, name, marks and
invoke the function
getavg( )
d i spl ayi n f o()
function to display all data members of report on the
screen
You should give function definitions.

Ans.
class report
{
int adno ;
char name
[21] ;
float marks
[5] ;
fl oat average
;
float
getavg( )
{
return (marks [0] + marks [1] + marks [2] +
marks [3] + marks [4]) /5;
}
public :
void readinfo( )
;
void
displayinfo( ) ;
};
void report :: readinfo( )
{
cout << "Enter admission no, name, marks in 5
subjects" ;
cin >> adno ;
gets (name) ;
for (int i = 0 ; i < 5
; i++)
cin >> marks[i] ;
average = getavg( ) ;
}
void report :: displayinfo( )
{
cout << " Ad missi on Nu mbe r :" << adn o <<
en dl ;
cout << "Name :" << name << endl ;
cout << "Marks in 5 subjects are :\n" ;
cout << marks[0] << << marks[1] <<
<< marks[2]
<< << marks [3] << <<marks[4]
<< endl ;
cout << "Average Marks :" << average
<<endl ;
}
68.

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


class PUBLISHER
{
char Pub[ 12] ;

double Turnover ;
protected :
void Register( ) ;
public :
PUBLISHER( ) ;
void Enter( ) ;
void Display( ) ;
} ;
class BRANCH
{
char CITY[20];
protected :
float Employees ;
public :
BRANCH( ) ;
void Haveit( ) ;
void Giveit( ) ;
};
class AUTHOR: private BRANCH, public PUBLISHER
{
int Acode ;
char Aname[20]
float Amount ;
public :
AUTHOR( ) ;
void Start( ) ;
void Show( ) ;
};
(i) Write the names of data members, which are accessible from objects belonging to
class AUTHOR.
(ii)
Write the names of all the member functions which are accessible from objects
belonging to the BRANCH.
(iii)
Write the name of all the members which are accessible from member functions
of class AUTHOR.
(iv)
How many bytes will be required by an object belonging to the AUTHOR ?
Ans.
(i) None of the data members are accessible from objects belonging to class AUTHOR
(ii)
Haveit( ), Giveit( )
(iii) Data members
Employees, Acode, Aname, Amount
Member function :
Register( ), Enter( ), Display( ), Haveit( ), Giveit( ), Start( ), Show( ).
(iv) 70 bytes
69.

Answer the questions (i) to (iv) based on the following


class ORGANIZATION
{
char Address[20] ;
double Budget, Income ;
protected :

void Compute( ) ;
public :
ORGANIZATION() ;
void Get( ) ;
void Show( ) ;
};
class WORKAREA : public ORGANIZATION
{
char Address[20] ;
int Staff ;
protected :
double Pay ;
void Calculate( ) ;
public :
WORKAREA( ) ;
void Enter( ) ;
void Display( ) ;
};
class SHOWROOM : private ORGANIZATION
{
char Address[20] ;
float Area ;
double Sale ;
public :
SHOWROOM( ) ;
void Enter( ) ;
void Show() ;
};
(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
SHOWROOM.
(iii)Write the names of all the member functions, which are accessible from objects
belonging to class WORKAREA.
(iv)Write the names of all members, which are accessible from objects of class
SHOWROOM.
Ans. (i) Hierarchical Inheritance
(ii) Address, Area, Sale
(iii) Get( ), Show( ), Enter( ), Display( )
(iv) Enter( ), SHOWROOM :: Show( )

70.

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


class Student
{
int Rno ;
char Name[20] ;
float Marks ;
protected :
void Result( ) ;
public :
Student( ) ;
void Register( ) ;

void Display() ;
};
class Faculty
{
long FCode ;
char FName [20] ;
protected :
float Pay ;
public :
Faculty( ) ;
void Enter( ) ;
void Show( ) ;
};
class Course : public Student, private Faculty
{
long CCode[10] ; char CourseName[50] ;
char StartDate[8], EndDate[8] ;
public :
Course( ) ;
void Commerce( ) ;
void CDetail( ) ;
};
(i) Which type of inheritance is illustrated in the above C++ code ?
(ii) Write the names of all the data members, which is / are accessible from member
function Commerce of class Course.
(iii)Write the name of member functions, which are accessible from objects of
class Course.
(iv)Write the names of all members, winch are accessible from objects of class
Faculty.
Ans. (i) Multiple Inheritance
(ii) CCode, CourseName, StartDate, EndDate, Pay
(iii) Commerce( ), CDetail( ), Register( ), Display( )
(iv) Enter( ), Show( )

71.
Answer the questions (i) to (iv) based on the following
code : class Dolls
class Dolls
{
char DCode[5] ;
protected:
float Price ;
void CalcPrice(float) ;
public:
Dolls( ) ;
void Dlnput( ) ;
void DShow( ) ;

};
class SoftDolls : public Dolls
{
char SDName[20] ;
float Weight ;
public:
SoftDolls() ) ;
void SDlnput( ) ;
void SDShow( ) ;
};
class ElectronicDolls : public Dolls
{
char EDName[20] ;
char BatteryType[10] ;
int Batteries ;
public:
Electronic Dolls( ) ;
void EDInput( ) ;
void EDShow( ) ;
};
(i) Which type of Inheritance is shown in the above example ?
(ii) How many bytes will be required by an object of the class ElectronicDolls ?
(iii)Write name of all the data members accessible from member functions of the
class SoftDolls.
(iv)Write name of all the member functions accessible by an object of the class
ElectronicDolls.
Ans. (i) Multilevel Inheritance
(ii) 65 Bytes
(iii)Price, SDName, Weight
(iv)DInput( ), DShow( ), SDInput( ), SDShow( ), EDInput( ), EDshow( )
72.
Answer the questions (i) to (iv) based on the following
code :
class Toys
{
char TCode[5] ;
protected :
float Price ;
void Assign(float) ;
public :
Toys( ) ;
void TEntry( ) ;
void TDisplay( ) ;
};
class SoftToys : public Toys
{
char STName[20] ;
float Weight ;

public :
SoftToys( ) ;
void STEntry( ) ;
void STDisplay( ) ;
};
class ElectronicToys : public Toys
{
char ETName [20] ;
int No_of_Batteries ;
public :
ElectronicToys( ) ;
void ETEntry( ) ;
void ETDisplay( ) ;
};
(i) Which type of Inheritance is shown in the above example ?
(ii) How many bytes will he required by an object of the class SoftToys ?
(iii) Write name of all the data members accessible from member functions of the class
SoftToys.
(iv)Write name of all the member functions accessible by an object of the class
ElectronicToys
Ans. (i) Hierarchical Inheritance
(ii) 33 bytes
(iii) Price, STName, Weight
(iv) TEntry( ), TDisplay( ), STEntry( ), STDisplay( ), ETEntry( ), ETDisplay( ).
73.

Answer the questions (i) to (iii) based on the following code :


class stationary
{
char Type ;
char
Manufacturer[1
0] ; public:
stationary( ) ;
void
Read_sta_details( ) ;
void
Disp_sta_details( ) ;
} ;
class office : public
stationary
{
int
no_of_types ;
float cost_of_sta ;
public :
void
Read_off_details( ) ;
void
Disp_off_details( ) ;
} ;

class printer : private


offi ce
{
int no_of_users ;
char deliver_date[10] ;
public :
void
Read_pri_d
etails( ) ;
void
Disp_pri_d
etails();
};
void main( )
{
printer MyPrinter ;
}
(i)

Mention the member names which are accessible by MyPrinter declared in main( )
function.
(ii)
What is the size of MyPrinter in bytes ?
(iii)
Mention the names of functions accessible from the member function
Read_pri_details( ) of class printer.
Ans.
(i)
(ii)
(iii)

74.

Data Members
Member Functions
29 Bytes
Member Functions

None
Read_pri_details( ), Disp_pri_details( )
Read_sta_details( ), Disp_sta_details( ),
Read_off_details( ), Disp_off_details( ),
Read_pri_details( ), Disp_pri_details( )

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


class Drug
{
char Category[10] ;
char Date_of_manufacture[10] ;
char Company[20] ;
public :
Drug( ) ;
void enterdrugdetails( ) ;
void showdrugdetails( ) ;
};
class Tablet : public Drug
{
protected :
char tablet_name[30] ;
char Volume_label[20] ;
public :
float Price ;

Tablet( ) ;
void entertabletdetails( ) ;
void showtabletdetails( ) ;
};
class PainReliever : public Tablet
{
int Dosage_units ;
char Side_effects[20] ;
int Use_within_days ;
public :
PainReliever( ) ;
void enterdetails( ) ;
void showdetails( ) ;
};
(i) How many bytes will be required by an object of class Drug and an object of
class PainReliever respectively ?
(ii) Write names of all the member functions accessible from the object of class
PainReliever.
(iii)
Write names of all the members accessible from member functions of
class Tablet.
(iv)Write names of all the data members which are accessible from objects of class
PainReliever.
Ans. (i) Drug type object 40 bytes
PainReliver type object 118 bytes
(ii) enterdetails( ), showdetails( ), entertabletdetails( ),
showtabletdetails( ), enterdrugdetails( ), showdrugdetails( )
(iii)Data Members : tablet_name, volume_label, price
Member functions : enterdrugdetails( ), showdrugdetails(
), entertabletdetails( ),
showtabletdetails( )
(iv) Price
75.Consider the following and answer the questions given below
class MNC
{
int Cname[25] ; //Company name
protected :
char Hoffice[25] ; //Head offi ce
public :
MNC( ) ;
char Country[25] ;
void EnterData( ) ;
void DisplayData( ) ;
};
class Branch : public MNC
{
int NOE ;
//Number of employees
char Ctry[25] ;
//Country
protected :
void Association( ) ;

public :
Branch( ) ;
void Add( ) ;
void Show( ) ;
};
class Outlet : public
Branch
{
char
State[25] ;
public :
Outlet( ) ;
void Enter( ) ;
void Output( ) ;
};
(i) Which class's constructor will be called first at the time of declaration of an object of
class Outlet ?
(ii) How many bytes does an object belonging to class Outlet require ?
(iii)Name the member function(s), which are accessed from the object(s) of class
Outlet.
(iv)Name the data member(s), which are accessible from the object(s) of class
Branch.
Ans. (i)
First of all constructor of class MNC will be called, then of Branch
and then at last of Outlet.
(ii)
127
(iii)MNC:: EnterData( ), MNC: : DisplayData( ), Branch : : Add( ), Branch : :
show( ), Outlet :: Enter( ), Outlet
: : Output( ).
(iv)
MNC :: Country.
76.

Give the output of the following program :


#include<iostream.h>
#include<string.h>
class per
{
char name[20] ;
float salary ;
public :
per(char * s, float a)
{
strcpy(name, s) ;
salary = a ;
}
per * GR(per & x)
{
if(x.salary >= salary)
return & x ;
else
return this ;
}

void display( )
{
cout << "Name : "<< name << "\n" ;
cout<< "Salary" : << sal ary << "\n" ;
}
};

Ans.

77.

void main( )
{
per P1( "REEMA", 10000), P2( "KRISHANAN", 20000),
P3( "GEORGE" , 5000) ;
pe r * P ;
P = P1.GR(P3) ;
P -> display( ) ;
P = P2.GR(P3) ;
P -> display( ) ;
}
Name
REEMA
Salary
10000
Name
KRISHNAN
Salary
20000

What is meant by Base Address of an array ?

Ans. The starting address of the very first element of an array is known as base
address of the array.
78. .What do you mean by garbage collection ?
Ans. Garbage collection is the process by which the deleted nodes (i.e., released
memory) are added to the AVAIL list.
79.

Define

Ans. An array is a group of homologous elements. A pointer is a variable that holds a


memory address, usually the location of another variable in memory.
The relationship between the two is that the name of an array is actually a pointer
pointing to the first element of the array.
80. How does C++ organize memory when a program is run ?
Ans. Once a program is compiled, C++ creates four logically distinct regions of
memory :
(i) area to hold the compiled program code
(ii) area to hold global variables
(iii)the stack area to hold the return addresses of function calls, arguments passed to the
functions, local
variables for functions, and the current state of the CPU.
(iv)the heap area from which the memory is dynamically allocated to the program.
81. What do you understand by memory leaks ? What are the possible
reasons for it ? How can memory leaks be avoided?
Ans. If the objects, that are allocated memory dynamically, are not deleted using
delete, memory block remains occupied even at the end of the program. Such
memory blocks are known as orphaned memory blocks.

These orphaned memory blocks when increase in number, bring as adverse effect
on the system. This situation is known as memory leak. The possible reasons for
this are :
(i) a dynamically allocated object not deleted using delete.
(ii) delete statement is not getting executed because of some logical error.
(iii)assigning the result of a new statement to an already occupied pointer.
The memory leaks can be avoided by
(i) making sure that a dynamically allocated object is deleted.
(ii) a new statement stores its return value (a pointer) in a fresh pointer.
82. What is 'this' pointer ? What is its significance ?
Ans. The member functions of every object have access to a sort of magic pointer
named this, which points to the object itself. Thus any member function can find out
the address of the object which it is a member.
The this pointer represents an object that invokes a member function. It stores
the address of the object that is invoking a member function and it (this
pointer) is an implicit argument to the member function being invoked.
The this pointer is useful in returning the object (address) of which the function is
a member.
83.Distinguish between
int *ptr = new int(5) ;
int *ptr = new int[5] ;
Ans. The first statement allocates memory of one integer to ptr and initializes it with
value 5. The second statement allocates memory of 5 contiguous integers (i.e., an
array of 5 integers) and stores beginning address in pointer ptr.
84.

Find the output of the following program :


#include<iostream.h>
struct Game
{
char Magic[20] ;
int Score ;
};
void main( )
{
Game M = { "Tiger",540} ;
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.M ag ic << N. Score << endl ;
Ans.

TiLeP550
AiLJP430

85.Find the output of the following program :


#include <iostream.h>
void main( )
{
int Track[ ] = { 10, 20, 30, 40}, *Striker ;
Striker = Track ;
Track [1] += 30 ;
cout << "Strikers>" << *Striker << endl ;
*Striker -= 10 ;
Striker++ ;
cout << "Next @"<< *Striker<< endl ;
Striker += 2 ;
cout << "Last
@"< < * S t r i ke r < < e n d l ;
cout << "Reset To" << Track[0] << endl ;
}
Ans

Striker > 10
Next @50
Last @40
Reset To 0

86.

Find the output of the following program :


#include<iostream.h>
void main( )
{
int Array[] = {4, 6, 1 70, 12} ;
int *pointer = Array ;
for int I=1 ; I<= 3; I++)
{
cout << *pointer << "#" ;
pointer++ ;
}
cout << endl ;
for(I = 1 ; I <= 4 ; I++)
{
( *pointer) * = 3 ;
--pointer ;
}
for(I = 1 ; I < 5 ; I++)
cout << Array[I - 1] << "" ;
cout << endl ;
}

Ans.

4 # 6 # 10#
12@18@30@36@

87.

What will be the output of the following program :

#include<iostream.h>
#include<ctype.h>
#include<string.h>
void Newtext(char String[ ], int & Position)
{
char *Pointer = string ;
int Length = strlen(String) ;
for (; Position < Length -2 ; Position += 2, Pointer++)
{
*(Pointer + Position) = toupper (*(inter + Position)) ;
}
}

Ans.

void main( )
{
int Location = 0 ;
char Message[] = "Dynamic Act" ;
Newtext (Message, Location) ;
Cout << Message << "#" << Location ;
}
DynAmiCACt#10

88.Write a function in C++ to find sum of each row for a two dimensional
integer array having 3 rows and 4 columns which is passed as
parameter of the function.
Ans.
void MatAdd(int M[ ][4], int N, int M)
{
for(int R=0; R<N; R++)
{
int SumR = 0 ;
for(int C = 0 ; C < M ; C++)
sumR += M[R][C] ;
cout << "Sum of Row" << R + 1 << ":" << SumR << endl
89. Write a function ALTERNATE (int A[ ][3], int N, int M) in C++
to display all alternate elements from two-dimensional
array A (starting from A[0] [0]).
For Example :
If the array is containing :
23 54 76
37 19 28
62 13 19
The output will be : 23

76

19

62 19

Ans.
void ALTERNATE(int A[ ][3], int N, int M)
{
int display = 1 ;
for(int i= 0 ; i < N ; i++)
for(int j = 0 ; j < M ; j++)

{
if(display = = 1)
cout << A[i][j] ;
display *= -1 ;
}
}
90.
Write a COLSUM( ) function in C++ to find sum of
each column of a N x M Matrix.
Ans.
void COLSUM(int A[ ] [ ], int N, int M)
{
int r, c, csum[N] ;
for( c = 0 ; c < M ; c++)
{
csum[c] = 0 ;
for(r = 0 ; r < N ; r++)
csum[c] += A[r][c] ;
}
for(c = 0 ; c < M ; c++)
cout <<" Su m of column" << c <<"i s" << csu m[ c] <<
en dl ;
}
91.Write a User defined in C++ to display the sum of row element of two
dimensional array A [5][6] containing integer.
Ans.
void RowSum(int A[5][6], int r, int c)
{
int sum[5], i, j ;
for(i = 0 ; i < r ; i++)
{
sum[i] = 0 ;
for(j = 0 ; j < c ; j++)
{
sum[i] += A[i][j] ;
}
c o u t << " S u m o f row " < < ( i + 1) < < " : " <<
s u m [i ] < < e n d l ;
}
}
92.
What is the
difference between an array and a stack housed in an array ?
Why
is
stack
called a LIFO data structure ? Explain how push and pop
operations
are
implemented
on
a stack.

An array is a group of homogeneous elements stored in contiguous memory


locations. The elements in an array can be processed from anywhere in the
array.
A stack implemented as an array also has elements stored in contiguous
memory locations. But a stack is always processed in a LIFO manner i.e., Last In
First Out manner wherein the elements can be added or removed from the top
end of the stack. That is why a stack is also called a LIFO data structure.
An addition to the stack is known as PUSH. The new element is added at the top
and the top (variable or pointer) is made to refer to the new element.
A removal of an element from a stack is known as POP. The elements (being
pointed to by top) is removed and the top is made to point to the next element
in the row.

111. Find the output of the following program :


#include<iostream.h>
void main( )
{
int X[ ] = {10, 25, 30, 55, 110} ;
int *p = X ;
while (*p < 110)
{
if (*p % 3 != 0)
*p = *p + 1 ;
else
*p = *p + 2 ;
p++ ;
}
for (int I = 4 ; I > = 1; I --)
{
cout << X[I] << "*" ;
if (I % 3 == 0)
cout < < endl ;
}
cout << X[0] * 3 < < endl ;
}
Ans. 110*56*
32*26*33
112. Predict and explain the output of following program :
# include <iostream.h >
void junk(int, int *) ;
int main( )
{
int i = 6, j = - 4 ;
junk(i, &j),;
cout << "i =" << i << ", j =" << j << "\n" ;
return 0 ;
}
void junk(int a, int *b)
{
a = a *a ;
*b = *b * *b ;
}
Ans. The output of this program will be i = 6, j= 16
Explanation While calling the function junk( ), the value of i (call-by-value) and the
address of j (call-by-reference) are passed to it. Naturally, in junk( ), a is declared as an
ordinary int (storing value of i) whereas b is declared as a pointer to int (pointing to j).
Even though the value of a is changed to 36 in junk( ), it is not reflected back in main( )
because of call-by-value mechanism. As against this, since b is an address of j, any change
in *b in junk( ) is reflected back in main( ) because of call-by-reference mechanism.
Hence j stores the result of (*b) * (*b) i.e., - 4 * - 4 =16.
113. Give the output following program :
# include<iostream. h>

int a = 13 ;
void main( )
void demo(int &, int, int*) ;
int a = 7, b = 4 ;
demo(:: a, a, &b) ;
cout << ::a << " " << a << " " << b << endl ;
void demo(int &x, int y, int *z)
{
a += x ;
y *= a ;
*z = a + y ;
c o u t < < x < < " " < < y < < " " < < *z < <
endl ;
}
Ans. 26
26

182
7

208
208

114. Write a function in C++ which accepts an integer array and its size as
arguments and replaces elements having odd values with thrice its value
and elements having even values with twice its value.
Example . If an array of five elements initially contains the elements
as .
3, 4, 5, 16, 9
then the function should rearrange the content of
the array as
9, 8, 15, 32, 27
Ans.
void RearrangeArray(int A[ ], int size)
{
for(int i = 0 ; i < size ; i++)
{
if(A[i] % 2 == 0)
A[i] *= 2 ;
else
A[i] *= 3 ;
}
}
115. Write a function in C++ which accepts an integer array and its size as
arguments / parameters and exchanges the values of first half side elements
with the second half side elements of the array.
Example : If an array of eight elements has initial content as
2, 4, 1, 6, 7, 9, 23, 10
The function should rearrange the array as
7, 9, 23, 10, 2, 4, 1, 6
Ans.
void Swap(int A[ ], int size)
{
int i, j, tmp, mid = size / 2 ;
if (size % 2 == 0)
j = mid ;
else
j = mid + 1 ;

for(i = 0 ; i < mid ; i++, j++)


{
tmp = A[i] ;
A[i] = A[j] ;
A[j] = tmp ;
}
}
116.
An array P[20][30] is stored in the memory along the column with
each of the element occupying 4 bytes, find out the Base Address of the
array, if an element P[2][20] is stored at the memory location 5000.
Ans. Given :
Base Address
B=?
Element size
W =4 bytes
No. of Rows
R =20
No. of Columns
C= 30
Location of P[2][20] is @ 5000
P[I][ J] in column Major is calculated as :
P[1][J] = B+ W ((I - 0) + R x (J - 0))
[0, 0 are lowest row and lowest
column]
Given P[2] [20] = 5000
5000 = B + 4 (2 - 0 + 20 x (20 - 0))
= B+ 4(402)
5000 = B+1608
B = 5000-1608 = 3392
Base Address = 3392
117.
An array S[10][30] is stored in the memory along the column with
each of the elements occupying 2 bytes. Find out the memory location of
S[5][10], if the element S[2][15] is stored at the location 8200.
Ans.
Base Address B=?, Rows ( R) = 10, Columns (C)= 30
S[2][15] @ 8200
element size W = 2 bytes
S[5][10] =?
In Column Major (if array indices begin with 0)
S[i][j] = B+W((i -0) + R(j -0))
S[2][15] = B+2(2 +10(15))
= B+2(152)
8200 = B+304
B= 7896
NowS[5][10] = 7896 + 2((5 -0) + 10(10 -0))
=7896+2(105)=7896+210
=8106
118.
An array P[50][60] is stored in the memory along the column with
each of the element occupying 2 bytes, find out the memory location
for the element P[10][20], if the Base Address of the array is 6800.
Ans. Size W = 2 ; Lowest row and column indices L r and L C = 0 each ;
No of rows M = 50 ; No of Columns N = 60
Address of P[i][j] = BaseAddress + W(i - L r)+(j - LC) *M)
Address of P[10][20] =6800 +2(10 -0)+ (20 -0)*50)
=6800 + 2 *1010 =6800+2020 =8820

119.
An array Arr[40][30] is stored in the memory along the column
with each of the element occupying 4 bytes. Find out the base
address and address of element S[20][15], if an element S[15][10]
is stored at the memory location 7200.
Ans. Given : array S[40][30]
Rows R = 40,
Columns C=30,
Width W = 4 bytes
address of 5[15][10] = 7200
To find address of 5[20][15]
Address of S[i][j] along the column is calculated as :
S[i][j] =B + W(( i - Lr ) + R(J- L c))
where B = Base address, Lr = lowest row index and L c = lowest column index.
7200 = B + 4((15 -0)+40(10-0))
7200 = B + 1660
B= 7200-1660 = 5540
address of S[20][15] = B + W ((20 - 0) + R (15 - 0))
= 5540 + 4 (20 + 40 x 15) = 5540 + 2480
=8020
Base address =5540
address of S[20][15] = 8020
120.
An array Arr[50][10] is stored in the memory along the row with
each element occupying 2 bytes. Find out the address of the location
Arr[20][50] if the location Arr[10][25] is stored at the address 10000.
Ans. Given :
No. of rows R = 50,
No. of cols C=10, Element size W =2 bytes
Base Address B=?,
Lowest row Lr = 0,
Lowest col L c =0
Given that Arr[10][25] has address =10000
Arr
[P] [Q] = B+W(C(P- L r )+(Q - L c ))
10000 = B+2(10(10-0)+(25 -0))
= B+2(125)
= B+250
B= 9750
Arr[i][j] = Arr[20][50]
= B+W(C( I Lr )+(j - L c))
= 9750 +2(10(20 - 0) + (50 - 0))
= 9750 +2(250)
= 10250.
121.
An array Arr[15][20] is stored in the memory along the row with
each element occupying 4 bytes, of memory. Find out the Base Address
and the address of element Array[3][2], if the element Arr[5][2] is stored
at the address 1500.
Ans. Total No. of Rows R=15,
Total No. of columns C = 20
Lowest row Lr = 0,
Lowest column L c = 0, Element size W =4 bytes
Arr[i][j] i.e., Arr[5][2] is @1500
Arrangement Order : Row wise
Base Address B= ?
Arr[i][j] = B+W (C(i Lr )+(j - L c))
Arr[5][2] = B+ 4(20 (5 - 0) + (2 - 0))

1500 = B + 408
B= 1092
Base Address is @1092
Arr[3][2] = B+ W (C(3 -0) + (2 -0))
=1092 +4(20(3-0)+(2 -0))
= 1092 + 248 =1340
Arr[3][2] is @1340
122.
An array X[30][10] is stored in the memory with each element
requiring 4 bytes of storage. If the base address of X is 4500, find out
memory locations of X[12][18] and X[2][14], if the content is stored
along the row.
Ans. B= 4500, W = 4
L r=0,
ur =29
L c =o,
uc = 9
Address of X[i][j] = B+W(n(I- Lr )+ (J - Lc ))
where n is number of columns and here n =10
Address of X[12] [8] = 4500 + 4 (10 (12 -0) + (8 -0))
= 4500 + 512 =5012
Address of X [2][14]= 4500 + 4 (10 (2 -0) + (14 -0))
=4500 + 136 = 4636
123.
The array A[20][10] is stored in the memory with each element
requiring one byte of storage if the base address of A is Co, determine
the location of A[10][5] when the array A is stored by column major.
Ans. Address of Ith, Jth element of array in column major 1's given by
A[i][j]= B+W (m(j -l 2)+ (i -l 1))
B= Base address, W = Size of each element,
m= no. of rows,
1 2 = column lower bound,
l 1 = row lower bound
A[10][5]= Co + 1(20 (5 -0) + (10 -0))
= Co + (20 (5) + 10)
= Co +110
124.
An array VAL[1..15][1..10] is stored in the memory with each
element requiring 4 bytes of storage. If the base address of array VAL is
1500, determine the location of VAL[12][9] when the array VAL is stored
(i) Row wise (ii) Column wise.
Ans. Base address B=1500
Element size w =4 bytes
Rows
r =15 -1+1=15
(U-L+1)
Columnsc =10 -1 + 1=10
[i][j] =[12][9]
Row wise := B+ w(C( i -1)+ ( j -1))
=1500 + 4 (10 x (12 -1) + (9 -1)) =1500 + 472 = 1972.
Column wise : = B + w ((I -1) + r( 1 -1))
=1500 + 4 ((12 -1) + 15 (9 -1)) =1500 + 524 = 2024.
125.
An array A[5][25] is stored in the memory with each element
requiring 4 bytes of storage. If the base address of array in the memory is
1000, determine the location of A[5][7] when the array is stored as (i)
Row major (ii) Column major.
Ans. Base Address
B =1000
No. of rows r =15

No. of columns c = 25
Width
w =4
A[i][j] = A[5][7]

i.e.,

i = 5,

j=7
Lower bound of rowsL r =0 (According to C+ +)
Lower bound of columns Lc =0 (According to C+ +)
Row Major
A[i][j]=B+ w(c(i-Lr)+(j - Lc))
=1000+ 4(25(5 -0)+(7-0))
=1000 + 4 (125 + 7)=1000 + 528 = 1528
Column Major
A[i][j]= B+ w ((i - Lr )+ r(j -Lc))
=1000 + 4((5 -0)+15(7-0))
=1000 + 480 = 1480.
126.
An array S[10][15] is stored in the memory with
each element requiring 4 bytes of storage. If the base
address of S is 1000, determine the location of S[8][9]
when the array is S stored by (i) Row major (ii) Column
major.
Ans. Base address
B=1000
Element size
w = 4 bytes
No. of rows
r =10
No. of Columns
c =15
Row Major
S[i] [j]= B+ w[c(i-0)+(j 0)]
S[8][9] =1000 + 4 [15 (8 - 0) + (9 0)]
=1000 + 4 [129] =1000 + 516 = 1516.
Column Major
S[i] [j]=B + w [ r ( i - 0 ) + ( j - 0 ) ]
S[8] [9]=1000 + 4 [10 (8 - 0) + (9 - 0)]
=1000 + 4 [89] =1000 + 356 =1356.

127. Stack Implementation using Linked list


or
Dynamically implement stack
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
void push();
void pop();
void display();
struct node
{
int info;
struct node *next;
};
struct node *first=NULL,*temp;
void main()
{
int choice;
clrscr();
while(1)
//infinite loop is used to insert/delete infinite number of nodes
{
clrscr();
cout<<"\n1.Push\n2.Pop\n3.Display\n4.Exit\n";
cout<<"\nEnter ur choice:";
cin>>choice;
switch(choice)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(0);
}
}
}
void push()
{
int info;
temp=(struct node *)malloc(sizeof(struct node));
cout<<"Enter a node info :";
cin>>info;
temp->info=info;

temp->next=first;
first=temp;
}
void pop()
{
if(first!=NULL)
{
cout<<"The poped element is "<<first->info;
first=first->next;
}
else
{
cout<<"\nStack Underflow";
}
getch();
}
void display()
{
temp=first;
if(temp==NULL)
{
cout<<"\nStack is empty\n";
}
while(temp!=NULL)
{
cout<<"\t"<<temp->info;
temp=temp->next;
}
getch();
}
128. Queue Implementation using Linked list
#include<iostream.h>
#include<malloc.h>
#include<stdlib.h>
#define MAXSIZE 10
void insertion();
void deletion();
void display();
struct node
{
int info;
struct node *next;
}*temp,*temp1,*p,*front=NULL,*rear=NULL;
typedef struct node N;

void main()
{
int ch;
clrscr();
while(1)
{
cout<<"\n
cout<<"\n
cout<<"\n
cout<<"\n
cout<<"\n
cin>>ch;

1.Insertion";
2.Deletion";
3.Display";
4.Exit";
Enter your choice : ";

switch(ch)
{
case 1:insertion();
break;
case 2:deletion();
break;
case 3:display();
break;
case 4:exit(0);
default:
cout<<"\nPlease Enter Valid Choice";
}
}
}
void insertion()
{
int info;
temp=(N*)malloc(sizeof(N));
cout<<"\nEnter the info : ";
cin>>info;
temp->info=info;
temp->next=NULL;
if(front==NULL)
front=temp;
else
rear->next=temp;
rear=temp;
}
void deletion()
{
if(front==NULL)
cout<<"\nQueue is empty";
else
{
p=front;
cout<<"\nDeleted element is : %d",p->info;
front=front->next;
free(p);

}
}
void display()
{
if(front==NULL)
cout<<"\nQueue is empty";
else
{
cout<<"\nThe elements are : ";
temp1=front;
while(temp1!=NULL)
{
cout<<\t"<<temp1->info;
temp1=temp1->next;
}
}
}
129.
Observe the program segment given below carefully, and answer the
question that follows :
class Labrecord
{
int Expno ;
char Experiment[20] ;
char Checked ;
int Marks ;
public :
//function to enter Experiment details
void EnterExp( ) ;
//function to display Experiment details
void ShowExp( ) :
//function to return Expno
Char RChecked( ) {return Checked ;}
//function to assign Marks
void Assignmarks (int M)
{ Marks = M ;}
};
void ModifyMarks( )
{
fstream File ;
File.open("Marks.Dat",ios:: binary I los:: in I ios :: out) ;
Labrecord L ;
int Rec = 0 ;
while(File.read((char*) &L, sizeof(L)))
{
if(L.RChecked( ) = = 'N')
L.Assignmarks(0) ;
else
L.Assignmarks(10) ;
//statement 1

//statement 2
Rec++ ;
}
File.close( ) ;
}
If the function ModifyMarks( ) is supposed to modify marks for the records in the file
MARKS.DAT based on their status of the member Checked (containing value either 'Y' or
'N'). Write C++ statements for the statement 1 and statement 2, where statement 1 is
required to position the file write pointer to an appropriate place in the file and
statement 2 is to perform the write operation with the modified record.
Ans.
Statement 1
File.seekp(- 1 *sizeof(L), ios :: cur) ;
Statement 2 :
File.write((char*) &L, sizeof(L)) ;
130.
Observe the program segment given below carefully and fill in the
blanks marked as Statement 1 and Statement 2 using seekg( ), seekp( ),
tellp( ) and tellg( ) functions for performing the required task.
#include <fstream.h>
class PRODUCT
{
int Pno ; char Pname [20] ; int Qty;
public :
void ModifyQty( );
// The function is to modify quantity of a PRODUCT
};
void PRODUCT:: ModifyQty( )
{
fstream File ;
Fil.open ("PRODUCT.DAT", ios:: binary l ios:: in l ios::out) ;
int MPno;
cout << "Product No to modify quantity :" ;
cin >> MPno;
while (Fil.read ((char*) this, sizeof (PRODUCT)))
{
if (MPno = = Pno)
{
cout << "Present Quantity :" << Qty << endI ;
cout << "changed Quantity :";
int Position = ______________ ; //Statement 1
____________________________ ; //Statement 2
Fil.write ( (char* this, sizeof (PRODUCT) ) ; // Re-writing
the record
}
}
Fil.close( );
}
Ans.
Statement 1 : int Position = Fil.tellg( );
Statement 2 : Fil.seekp(Position - sizeof(PRODUCT), ios : : beg);

131. Observe the program segment given below carefully and fill in the
blanks marked as Statement 1 and Statement 2 using tellg( ) and seekp( )
functions for performing the required task.
#include <fstream.h>
class Client
{
long Cno ; char Name[20], Email[30] ;
public :
//Function to allow user to enter the
//Cno, Name, Email
void Enter( ) ;
//Function to allow user to enter //(modify) Email
void Modify( ) ;
long ReturnCno( ) { return Cno ; }
} ;
void ChangeEmail( )
'
{
Client C ;
fstream F ;
F.open("INFO.DAT',ios : : binary l ios : : in l ios : : out) ;
long Cnoc ;
//Clients no. Whose Email needs to be changed
cin >> Cnoc ;
while (F.read((char*) &C, sizeof(C)))
{
if (Cnoc == C. ReturnCno( ))
{
C.Modify( ) ;
//Statement 1
int Pos = ________________
//To find the current position of file pointer
//Statement 2
_______________________________
//To move the file pointer
//to write the modified record back into the file for the
desired Cnoc
F.write((char*) &C, sizeof(C)) ;
}
}
F.close( ) ;
}
Ans.
Statement 1: F.tellg( ) ;
Statement 2: F.seekp (Pos . - sizeof(C)) ;
132. Observe the program segment given below carefully, and fill in the
blanks marked as Line 1 and Line 2 using fstream function for performing
the required task.
#include<fstream.h>
class Stock
{
long Ino ;
//Item Number
char Item[20]
//Item Name
int Qty ;
//Quantity
public :
void Get(int) ;
//Function to enter the content

void show( ) ;
//Function to display the content
void Purchase (int Tqty)
{
Qty += Tqty ;
} //Function to increment in Qty
long KnowIno( ) {return Ino ;}
}
void Purchaseitem (long PINo, int PQty)
//PINo -> Ino of the item purchased
//PQty -> Number of item purchased
{
fstream File ;
File.open("ITEMS.DAT", ios:: binary I ios : : in I ios : : out);
int Pos = -1 ;
Stock S ;
while (Pos == -1 && File.read((char*) &S, sizeof(S)))
if (S.KnowIno( ) == PINo)
{
S.Purchase (PQty) ;
//To update the number of Items
Pos = File.tellg( ) - sizeof(S) ;
//Line 1 : To place the file pointer to the required position
_________________________________
//Line 2 : To write the object S on to the binary file
____________________________________
}
if (Pos == - 1)
cout<< "No updation done as required Ino not found.." ;
File.close( ) ;
}
Ans.
Statement 1
File.seekp(Pos) ;
Statement 2
File.write((char*) & S, sizeof (S)) ;
133. Observe the program segment given below carefully, and answer the
question that follows :
class Candidate
{
long Cid ;
// Candidate's Id
char CName[20] ; // Candidate's Name
float Marks ;
// Candidate's Marks
public :
void Enter( ) ;
void Display( ) ;
void MarksChange( ) ;
//Function to change marks
long R_CId( ) {return CId ;}

};
void MarksUpdate (long ID)
{
fstream File ;
File.open ("CANDIDAT.DAT", ios : : binary I ios :: in | ios :: out) ;
Candidate C ;
int Record = 0, Found = 0 ;
while (!Found && File.read((char*)&C, sizeof(C)))
{
if (Id == C.R_CID( ))
{
cout << "Enter new Marks" ;
C. MarkChange( ) ;
____________________ //Statement 1
____________________ //Statement 2
Found = 1 ;
}
Record++ ;
}
if (Found == 1) cout << "Record Updated" ;
File.close( ) ;
}
Write the Statement1 to position the File Pointer at the beginning of the Record for which
the Candidate's Id matches with the argument passed, and Statement 2 to write the
updated Record at that position.
Ans.
Statement 1
File.seekg( -1* sizeof(C), ios : : cur) ;
Statement 2
File.write((char*)&C, sizeof(C)) ;
134.Write a function in C++ to count the word "this" (including "This"/"THIS"
too) present in a text file "DIARY.TXT".
Ans. void WordCount( )//assuming required header files are included
{
fstream File ;
File.open("DIARY.TXT, ios:: in) ;
char Word[20] ;
int Count = 0;
while(!File.eof( ))
{ File >> Word ;
if (!strcmp(Word, "this") || !strcmp(Word, "This") I I !strcmp(Word,
"THIS"))
Count++ ;
}
cout << "Number of this/This/THIS =" < < Count
<< endl File.close( ) ;
}
135. Write a function in C++ to count the number of alphabets present in a
text file "NOTES.TXT".
Ans. void CountAlphabet( )//assuming required header files are included
{

ifstream FIL("NOTES.TXT", ios : in) ;


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( ) ;
}
136.
Write a function in C++ to read the content of a text file
"PLACES.TXT" and display all those lines on screen, which are either
starting with 'P' or starting with 'S'.
Ans. void readfile( )
{
ifstream fin("PLACES.TXT", ios:: in) ;
char line[256] ;
while(!fin.eof( ))
{
fin.getline(Iine, 255) ;
if(line[0] == `P` I I line[0] == 'S')
cout << line ;
}
fin.close( ) ;
}
137.
Write a function in C++ to count the no. of "Me" or "My"
words
present
in
a
text
file
"DLARY.TXT".
If the file "DIARY.TXT"content is as follows
My first book was Me and My
family. It gave me change to be
known to the world.
The output of the function should be
Count of Me/My in file : 4
Ans. #include<fstream.h>
#include<string.h>
#include<process.h> // for exit( )
int count( )
{
ifstream ifile("DIARY.TXT") ;
if(!ifile)
{
cout << "could not open story.txt file" ;
exit(-1) ;
}
else
{
char s(20] ; int cnt = 0 ;
while(!ifile.eof( ))

{
ifi le >> s ;
if((strcmp(s, "Me") == 0) I I (strcmp(s, "My") == 0))
cnt++ ;
}
ifile.close( ) ;
cout << "Count of Me/My in file :" <<
cnt ; return cnt ;
}
}
138.Write a function in C++ to count the number of-lowercase alphabets
present in a text file "BOOK.TXT".
Ans- int countlower( )
{
ifstream fin("BOOK.TXT") ;
char ch ; int count = 0 ;
while (!fin.eof( ))
{
fin.get(ch) ;
if(islower(ch))
count++ ;
}
fin.close( ) ;
return count ;
}
139. Write a function to count the number of blanks present in a text file
named "PARA.TXT".
Ans. void countblanks( )
{
char ch ;
int count = 0 ;
ifstream fin("PARA.TXT", ios:: in) ;
while(! fin.eof( ))
{
fi n.get(ch) ;
if(fin.eof( ))
break ;
if(ch = = )
count++ ;
}
fin.close( ) ;
cout << count ;
}
140.

Assuming the class


Vehicle as follows :
class vehicle
{
char vehicletype[10] ;
int no_of_wheels ;
public:
void getdetails( )
{

gets(vehicletype);
cin >> no_of_wheels;
}
void showdetails( )
{
cout << "Vehicle Type" << vehicletype ;
cout << "Number of wheels =" << no_of_wheels ;
}
};
Write a function showfile( ) to read all the records present in an already existing binary file
SPEED.DAT and display them on the screen, also count the number of records present in the
file.
Ans. void showfile( )
{
ifstream fin ;
fin.open("SPEED.DAT", ios : in l l ios::
binary) ; vehicle VI ;
int count = 0 ;
while(!fin.eof( ))
{
fin.read((char *) &VI, sizeof(VI)) ;
count++ ;
VI.showdetails( ) ;
}
cout << "Total number of records are " << count ;
}

141.
Write a function in C++ to search for a Toy having a particular
ToyCode from a binary file "TOY.DAT" and display its details (Tdetails),
assuming the binary file is containing the objects of the following
class.
class TOYSHOP
{
int Tcode ;
//Toy Code
char Tdetails[20] ;
public:
int RTcode( )
{ return Tcode ; }
void AddToy( )
{ cin >> Tcode ; gets(Tdetails) ; }
void DisToy( )
{ cout << Tcode << Tdetails << endl ; }
};

Ans.

void ToySearch(int tc)


{
fstream FIL ;
FIL.open("TOY.DAT", ios : : binary I
ios : : in) ; TOYSHOP TS ;
int Found = 0 ;
while (FIL.read ((char*) &TS, sizeof(TS)))
{
if (TS.RTcode( ) == tc)
{
TS.DisToy( ) ; //details displayed
Found++ ;
}
}
if (Found == 0) cout << "Sorry! Toy not found!!!" <<
endl ;
FIL.close( ) ;

}
142. 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.
class STUD
{
int Rno ;
char Name[20] ;
public:
void Enter( )
void
Display( )

{ cin >> Rno ;


gets(Name) ; }
{ cout << Rno << Name <<
endl ; } ; }

};
Ans.

void Addnew()
{
fstream FIL ;
FIL.Open ("STUDENT. DAT", ios : : binary | ios : : app) ;
STUD S;
char CH;
do
{
S.Enter( ) ; //Read details in object
FIL.write((char*) &S, sizeof(S)) ;
cout << "More(Y/N) ?" ;
cin >> CH ;
} while(CH !='N') ;
FIL.close( ) ;
}

143.
Write a function in C+
+ to search for the details (Number and Calls) of those Mobile Phones,

which
have more than 1000 calls from a binary file "mobile.dat". Assuming that
this
binary
file
contains
records/objects of class Mobile, which is defined below.
class Mobile
{
char Number[10] ;
int Calls ;
public :
void Enter( ) { gets(Number) ; cin >> Calls ;}
void Billing( ){ cout << Number << "#" << Calls << endl ; }
int GetCalls( )
{ return Calls ; }
};
Ans. class Mobile
{
// as given in question
}
void Search( )
{
ifstream fin("mobile.dat", ios : : in I ios : :
binary) ; Mobile M ;
while(!fin.eof( ))
{
fin.read((char *) &M, sizeof(M)) ;
if(m.GetCalls( ) > 1000)
M.Billing( ).;
}
fin.close( ) ;
}

144. Write a function in C++ to search and display the details of all flights,
whose destination is "Mumbai" from a binary file "FLIGHT.DAT". Assuming the
binary file is containing objects of class.

class FLIGHT
{
int Fno ;
//Flight Number
char
//Flight Starting
From[20] ;
Point //Flight
char To[20] ;
Destination
public :
char*
{return From ;}
GetFrom( )
{return To ;}
char* GetTo( ) { cin >> Fno ; gets(From) ; gets(To) ; }
void Enter( )
{ cout << Fno << ":" << From << ":" << To
void Display( ) << endl ; }
};
{
FLIGHT f ;
ifstream fin ;
fin.open ("FLIGHT.TXT", ios : : in I ios : :
binary) ;
while (fin.read( (char*)&f, , sizeof(f) )
{
if ( strcmp (f.GetTo( ), " Mumbai ") = = 0)
f.Display( ) ;
}
fin.close( ) ;
}
145. Write a function in C++ to read and display the detail of all the members
whose membership type is 'L' or 'M' from a binary file "CLUB.DAT". Assume
the binary file "CLUB.DAT" contains objects of class CLUB, which is defined as
follows :
class CLUB
{ int Mno ;
//Member Number
char Mname[20]
//Member Name
; char Type ;
//Member Type : L Life Member M Monthly Member G Guest
public :
void Register(
//Function to enter the content
)
;
void
//Function to display all data members
Display( ) ;
{return Type ;}.
char
WhatType( )
}
;
{
CLUB C;
fstream fin ;
fin.open ( "CLUB.DAT ", ios :: binary I ios ::
in) ;
while (fin.read((char*) &C, sizeof(C)))
{
if (C.WhatType( ) = = 'L' I I C.WhatType( ) == 'M')
C.Display( ) ;
}
fin.close( ) ; }

146. Given a binary file PHONE.DAT, containing records of the following


structure type
class Phonlist
{
char Name[20] ; char Address[30] ; char AreaCode[5] ; char
PhoneNo[15] ;
public :
void Register( ) ;
Void Show( ) ;
int CheckCode(char AC[ ])
{
return strcmp(AreaCode, AC) ;
Write a function TRANSFER( ) in C++, that would copy all those records which are having
AreaCode as "DEL" from PHONE.DAT to PHONBACK.DAT.
Ans. void TRANSFER( )
{
ifstream fin ;
ofstream fout ;
Phonlist ph ;
fin.open("PHONE.DAT", ios : : in l ios : : binary) ;
fout.open("PHONBACK.DAT", ios : : out l ios : : binary) ;
while(!fin.eof( ))
{
fin.read((char*)&ph, sizeof(ph)) ;
if(ph.CheckCode("DEL") == 0)
fout.write((char*)&ph, sizeof(ph)) ;
}
fin.close( ) ;
fout.close( ) ;
}
147. Assuming that a text file names TEXTI.TXT already contains some text
written into it, write a function names vowelwords( ), that reads the file
TEXTI.TXT and creates a new file named TEXT2.TXT, which shall contain only
those words from the file TEXTI.TXT which don't start with an uppercase
vowel (i.e., with 'A', `E', 'I', '0', 'U'). For example, if the file TEXTI.TXT contains
Carry Umbrella and Overcoat When it Rains
then the file TEXT2.TXT shall contain
Carry When it Rains
Ans. #include<fstream.h>
void NewFile( )
{
ifstream fin("text1.txt", ios :: in) ;
ofstream fout("text2.txt", ios:: out) ;
char word[25] ;
while(!fin.eof( ))
{
fi n >> word ;
switch(word[0])
{
case 'A' :

case 'E ' :


case 'I ' :
case '0' :
case 'U' : continue ;
}
fout << word << ' ';
}
}

You might also like