C++ Final CS1
C++ Final CS1
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.
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.
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+ +.
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
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.
}
}
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
#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
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
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
;
;
{
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
{
Public Members
Rent
1000
Van
800
SUV
2500
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.
:
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.
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
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
1
2
3
64.
65.
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( ) ;
}
Private Members
adno
name
marks
average
getavg()
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.
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.
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.
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.
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( )
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.
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
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
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.
TiLeP550
AiLJP430
Striker > 10
Next @50
Last @40
Reset To 0
86.
Ans.
4 # 6 # 10#
12@18@30@36@
87.
#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.
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 ;
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.
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
{
{
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.
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.
}
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( )
};
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( ) ; }