Contents
Chapterwise Question Bank CBSE Class 12 Computer Science (C++) – Object Oriented Programming
Topic – 1
Concept of OOP
Exam Practice
Very Short Answer Type Questions [1 Mark]
Question 1:
How are the object’s behaviour and object’s characteristics represented in OOP?
Answer:
An object’s behaviours and object’s characteristics are represented in terms of member functions of a class and data members of a class.
Question 2:
Why function overloading is used?
Answer:
Function overloading plays very important role to implement polymorphism. It is also used to make the program run faster and reduces the number of comparison in a program.
Question 3:
When do you think function overloading be used?
Answer:
Function overloading is used when a function is required to perform for alternatives argument types and there is a definite way of optimising the function for the argument type. In such kind of case, function overloading should be used.
Question 4:
Is this possible to declare two functions with same name and same argument but different return type in C++?
Answer:
No, it is not possible to declare two functions with same name and same argument but different return type in C++, because the control will be confused at the time of calling which of these function will be executed first.
Question 5:
Which function is called during each function call in the program given below?
int sum(int); //Function[I] float sum(float); //Function[II] double sum(double); //Function[111] void main() int x=20; int a=sum(x); //Call 1 float b=sum(x); //Call 2 double c=sum(x); //Call 3 getch(); }
Answer:
Call 1, 2 and 3 will invoke only function [I] because controls with match only function [I] at each time. It is being called. And each time return value will be an integer that can be assigned to a higher data type easily.
Question 6:
How are abstraction and encapsulation interrelated?
Answer:
Encapsulation means binding of data members and member functions (which operates on the data) into a single unit and ensure that only important features get represented without representing background details, i.e. called abstraction. Encapsulation is a way to implement data abstraction. Therefore, both are interrelated.
Question 7:
Inheritance allows code reusability in OOP. Explain how?
Answer:
Inheritance allows us to add additional features to an existing class without modifying it. Thus, the class can be raised by inheriting it. We look for a class that can be reused in our program. If such a class exists, we simple use it or inherit it. Thus, inheritance allows code reusability.
Question 8:
In function overloading how is matching done?
Answer:
In function overloading, the matching is done on the basis of number of argument and types of argument. If two functions have same argument, then matching is done on the basis of sequence or type of arguments. There is no rule of matching on the basis of return type.
Question 9:
How an object differs from a program module?
Answer:
object is a real world entity that consists of both data and function and this integrated unit provides the necessary behaviour expected from the object. While a program module is a piece of code, which performs a particular function or set of functions.
Question 10:
Write declaration for two overloaded functions named bar(). They both return float type. The first takes one argument of type char and second takes two argument of type char. If this is impossible, explain why?
Answer:
Declaration of function is possible with overloading concept: float bar(char ch)
Question 11:
Why are the functions arguments called as “Signature”?
Answer:
The arguments differentiate functions with the same name. The name alone cannot identify a unique function. However, the name and its arguments (signature) will uniquely identify function. In real life, also we can see this happening. In a class, two students with same name can be identified by their signature.
Question 12:
Does the return type of a function also help in finding the best match in function overloading?
Answer:
No, compiler does not have any criteria to check function match using return type of a function. Two functions can have same name and return type in function overloading. If the signatures of two function are same but different return type, it is not allowed by the compiler.
Question 13:
To relate classes with real world, if book is a class then give example of its objects.
Answer:
If ‘book’ is a class then the objects of this class are Hindi, English, Social science, Computer science, etc.
Question 14:
Name the features by which classes acquire the properties of other classes.
Answer:
Inheritance is the feature by which classes acquire the properties of other classes.
Question 15:
How does a compiler decide as to which function should be invoked when there are many functions with the same name?
Answer:
The compiler differentiates between functions with same name by the number of arguments and the data type of arguments that are given with function declaration and the function call.
Short Answer Type Questions [2 Marks]
Question 16:
How does OOP overcome the shortcoming of traditional programming approach.
Answer:
An OOP overcome the shortcoming of traditional programming approach by implementing a real world problem into objects. An OOP provides an easy way to add new data and function while in traditional programming, it is very difficult to add new data and function.
For the security purpose, in OOP data cannot move easily from functions to functions. It can be kept public or private, so we can control the access of data but in POP, most function uses the global data for sharing, that can be accessed freely from function to function in the system that is the reason of security failed.
In traditional programming, the code reusability is not possible that is very important feature of a programming. While in OOP, through inheritance, the code reusability is possible.
Question 17:
With the multiple definition of single function name, what makes them significantly different?
Answer:
With the multiple definition of single function name, the function signature makes them significantly different. The function signature can be recognised by the list of argument. Either number of argument may be differ or types of argument may differ in function declaration. Another difference is that the sequence of argument type may differ. So in short, we can say that function’s signature makes them significantly different in making function with same name with multiple definition.
Question 18:
Why do you think function overloading must be a part of an OOP?
Answer:
A function overloading must be a part of an OOP because it is a feature that implements the polymorphism in object oriented programming, i.e. the ability of an object to behave differently in different circumstance can effectively be implemented in programming through overloading.
Also, with the function overloading, the programmer is relieved from the burden of choosing right function for a given set of values. This important responsibility is carried out by the compiler, when function is overloaded.
Question 19:
How does a class enforce data hiding, abstraction and encapsulation?
Answer:
A class binds data and its associated functions together under one unit, which enforcing encapsulation that means wrapping up data and associated functions together into single unit. Member of class can be group into three parts: public, private and protected. The private and protected functions remain hidden from outside world. Thus, through private and protected members a class enforce the data hiding. The public member can be used outside the world, that is important and necessary information, rest of the thing remain hidden which is nothing but abstraction. We can say that, an abstraction means representing only essential features wdthout expressing background details.
Question 20:
Write a program using overloaded function to compute the area of rectangle and area of triangle using hero’s formula.
Answer:
A program using overloaded function to compute the area of rectangle and area of triangle using hero’s formula.
#include<iostream.h> #include<conio.h> #includeCmath.h> double area(int x, int y); double area(int x, int y, int z); void main() { int A,B,a,b,c; double AREA; clrscr(); cout<<"Enter the side of rectangle"; cin>>A>>B; AREA=area(A,B); cout<<"\nArea of rectangle="<<AREA; cout<<"\nEnter the side of triangle"; cin>>a>>b>>c; AREA=area(a,b,c); cout<<”\nArea of triangle="<<AREA; getch(); } double area(int x ,int y) { return (x*y); } double area(int x, int y, int z) { float s=((x+y+z)/2); return(sqrt(s*(s-x)*(s-y)*(s-z))); }
Output
Enter the side of rectangle 10 20
Area of rectangle = 200
Enter the side of triangle 70 45 45
Area of triangle = 989.949494
Question 21:
How are large problems divided in object oriented programs? Give an example.
Answer:
In object oriented programming, large programs are divided into real world entity called object, which are consist of function and the data on which these functions have to be performed.
e.g. if a function has to be written to calculate the sum of two numbers then the entity will include the data, whose sum has to be calculated and also include the functions to calculate the sum and display the result.
Question 22:
How concrete class is differ from abstract class?
Answer:
Abstract Class and Concrete Class
An abstract class is one which cannot be used to create objects and is designed only to work as a base class. Only pointers or reference to this type of class can be declared.
On the other hand, the classes which are intended for the creation of objects or instances are called instance or concrete classes.
e.g. automobiles is an abstract class. Because, in real world there exists an instance of car, truck, etc., all these are child classes of class automobiles. But no instance of automobiles class can exist. So, automobiles is an abstract class and car and truck are concrete classes.
Question 23:
Why data encapsulation is so important in C++?
Answer:
Data encapsulation plays very important role in C++ because it ties data and function into a single unit so that data cannot move freely from one program to another and data cannot be accidently corrupted by the external world. It ensure that changes to the data and functions of an object can be made without affecting other objects. Objects are independent of each other. Therefore, each object can be studied properly for better understanding of the design, encapsulation links together the state and the behaviour of an object.
Question 24:
What will be the output of the following program?
int areadnt s) { return (s*s); } float area(int b.int h) { return (0.5*b*h); } void main() { cout<<area(5)<<endl; cout<<area(4,. 3)<<endl; cout<<area(6, area(3) )<<endl ; getch(); }
Answer:
Output
25
6
27
Long Answer Type Questions [4 Marks]
Question 25:
Write a program using three functions to calculate the volume of a cube, a cylinder and a rectangular box. The function names should be the same. HOTS
Answer:
#include<iostream.h> #include<conio.h> int volume(int a); double volume(float r.int h); int volume(int l.int b.int h); void main() { int a , l , b,h; float r; clrscr(); cout<<"Enter the side of cube cin>>a; cout<<"Enter the radius and height of cylinder ”; cin>>r>>h; cout<<"\nEnter the side of rectangular cube\n"; cin>>l>>b>>h; cout<<"Volume of cube="<<volume(a); cout<<"\nVolume of cylinder="<<volume(r,h); cout<<"\nVolume of rectangular cube="<<volume(l,b,h); getch(); } int volume(int a) { return(a*a*a); } double volume(float r.int h) { return(3.1461*r*r*h); } int volume(int l.int b,int h) { return(l*b*h); }
Output
Enter the side of cube 2
Enter the radius and height of cylinder 2 3
Enter the side of rectangular cube
3 4 5
Volume of cube = 8
Volume of cylinder = 62.922
Volume of rectangular cube = 60
Question 26:
What do you understand by function overloading? Give an example illustrating its use in a C++ program. All India 2011
or
What is function overloading? Write an example using C++ to illustrate the concept of function overloading. All India 2014
Answer:
Function overloading
Function overloading is the process of using the same name for two or more functions. Each redefinition of a function must use different type of parameters, sequence of parameters or number of parameters.
The number, type or sequence of parameters for a function is called the function signature. When we have multiple functions with the same name, the compiler identifies the function based on the parameters to the function. This is a very useful feature as illustrated in the following program. The function area() displays the area of different shapes.
Program 1. To show the use of function overloading.
#include<iostream.h> #include<conio.h> int area(int side) { return (side*side); } int area(int length, int breadth) { return (1ength*breadth); } float area(float radius) { return(3.14*radius*radius); } float area(int base, float height) { return (base*height/2); } float area(float base, int height) { return (base*height/2); } void main() { cout<<"for computing the area of a\n"; cout<<"square!side=5)"; cout<<area(5)<<endl ; cout<<"rectangle(1ength=5, breadth=10)"; cout<<area(5,10)<<endl; cout<<"circle (radius=5.5)"; cout<<area(5.5f)<<endl; cout<<"triangle(base=3, height = 5.4)"; cout<<area(3,5.4f)<<endl; cout<<"triangle (base = 4.5, height=6)"; cout<<area(4.5f,6)<<endl; getch(); }
e.g. this is very useful feature as illustrating in the following program. The function sroot( ) that returns the square root of its argument.
#include<iostream.h> #include<conio. h> #include<math.h> int sroot(int x); float sroot(float y); long int srootdong int x); double sroot(double x); void main() { int a; long int b; float c; double d; cout<<"\nEnter the integer value cin>>a; cout<<"\nSquare root="<<sroot(a); cout<<"\nEnter the long value cin>>b; cout<<"\nSquare root="<<sroot(b); cout<<"\nEnter the float value cin>>c; cout<<"\nSquare root="<<sroot(c); cout<<"\nEhter the double value cin>>d; cout<<"\nSquare root="<<sroot(d); getch(); . } int sroot(int x) { return(sqrt(x)); } float sroot(float y) { return(sqrt(y)); } long int srootdong int x) { return(sqrt(x)); } double sroot(double x) { return(sqrt(x)); }
Output
Enter the integer value 49
Square root = 7
Enter the long value 625
Square root = 25
Enter the float value 3452.34
Square root = 58.756618
Enter the double value 23456.789
Square root= 153.156094
Question 27:
What do you understand by polymorphism? Give an example, illustrating its use in a C++ program.
Answer:
Polymorphism means processing of data or messages in more than one form. It is the phenomenon, where different objects take different set of actions for the same message. It is implemented using function overloading and operator overloading.
e.g. the function area( ) will work differently for different shapes like circle, triangle, rectangle, etc. i.e. function area( ) exhibits polymorphic behaviour.
Delhi 2010
e.g.
#include<iostream. h> #includeCconio.h> #include<math.h> double area(int x); double area(int x,int y); double area(int x,int y.int z); void main() { int A,B,a,b,c,r; double AREA; clrscr(); cout<<"\nEnter the radius of circle cin >> r; AREA=area(r); cout<<"\nArea of circle="<<AREA; cout<<"\nEnter the side of rectangle "; cin>>A>>B; AREA=area(A,B); cout<<"\nArea of rectangle="<<AREA; cout<<”\nEnter the side of triangle cin>>a>>b>>c; AREA=area(a , b,c); cout<<"\nArea of tri angl e=''<<AREA; getch(); } double area(int x) { return ((22*x*x)/7); } double area(int x,int y) { return (x*y); } double areaCint x,int y,int z) { float s=((x+y+z)/2); return(sqrt(s*(s-x)*(s-y)*(s-z))); }
Output
Enter the radius of circle 2
Area of circle =12
Enter the side of rectangle 45 20
Area of rectangle = 900
Enter the side of triangle 70 60 50
Area of triangle = 1469.693846
Question 28:
Write the output of the following C++ code. Also, write the name of feature of object oriented programming used in the following program jointly illustrated by the functions [I] to [IV], Delhi 2011
#include<iostream.h> void Print() //Function[I] { for(int K=1; K<=60; K++) cout<<”-"; cout<<endl ; } void Print(int N) //Function[II] { for(K=1; K<=N; K++) cout<<"*"; cout<<endl ; } void Print(int A, int B) //Function[III] { for(K=1; K<=B; K++) cout<<A*K; cout<<endl ; } void Print(char T,int N) //Function[IV] { for(K=l; K<=N; K++) cout<<T; cout<<endl; } void main() { int U=9, V=4, W=3; char C='@'; Print(C,V); Print(U.W); }
Answer:
Output
@@@@
91827
In the above example, the function overloading concept is used from function [I] to [IV].
Question 29:
What are the advantages of OOP over the procedural-oriented programming?
Answer:
Topic – 2
Implementation of OOPs Concept in C++
Exam Practice
Short Answer Type Questions [2 Marks]
Question 1:
What is the significance of (::) scope resolution operator?
Answer:
Member functions can be defined within the class definition or separately using scope resolution operator(::). Scope resolution operator specifies that the scope of the function is restricted to the class_name.
#include<iostream.h> class Box { double length; double breadth; double height; public: double getVolume(void); }; double Box :: getVolume(void) { return length*breadth*height; }
Question 2:
What is the difference between a struct and a class in C++?
Answer:
The struct default access type is public. A struct should typically be used for grouping data. The class default access type is private and the default mode for inheritance is private.
A class should be used for grouping data and methods that operate on that data.
In short, the convention is to use struct when the purpose is to group data and use classes, when we require data abstraction and perhaps inheritance. In C++, structures and classes are passed by value, unless explicitly de-referenced. In other languages, classes and structures may have distinct semantics, i.e. objects (instances of classes) may be passed by reference and structures may be passed by value.
Technically, there are only two differences between classes and structures:
(i) classes are declared using the keyword ‘class’ while structures are declared using the keyword ‘struct’.
(ii) structures are entirely public, while classes are private by default.
Question 3:
Rewrite the following program after removing the syntactical errors (if any).
Underline each corrections. Delhi 2012
#include<iostream.h> class Product { long PId.Qty; public: void Purchase { cin>>PId>>Qty; } void sale() { cout<<setw(5)<<PId<<"0ld: ”<<Qty<<endl; cout<<”New:”<<--Qty<<endl; } }; void main() { Product P; Purchase(); P.Sale(); P.Sale(); }
Answer:
#include<iostream.h> # include<iomanip.h> class Product { long PId.Qty; public: void Purchase() { cin>>PId>>Qty; } void Sale() { cout<<setw(5)<<PId<<''0ld: "<<Qty<<endl; cout<<"New:"<<--Qty<<endl; } }; void main() { Product P; P. Purchase(); P.Sale(); P.Sale(); }
Question 4:
Rewrite the following program after removing the syntactical errors (if any).
Underline each correction. All India 2012
#include<iostream.h> class Item { long IId, Qty; public: void Purchase { cin>>IId>>Qty ; } void Sale() { cout<<setw(5)<<IId<<"old:"<<Qty<<endl; cout<<"New:"<<--Qty<<endl; } }; void main() { Item I; Purchase(); I .Sale(); I .Sale() }
Answer:
#include<iostream.h> #include<iomanip.h> class Item { long IId, Qty; public: void Purchase() { ci n>>IId>>Qty ; } void Sale() { cout<<setw(5)<<I Id<<"old: ”<<Qty<<endl; cout<<"New:”<<--Qty<<endl; } }; void main() { Item I; I.Purchase(): I .Sale(); I.Sale(): }
Question 5:
Rewrite the following C++ program code after removing the syntax error(s) (if any).
Underline each corrections. All India 2010
#include<iostream.h> class FLIGHT { long FlightCode; char Description(25); public; void AddInfo() { cin>>FlightCode; gets(Description); } void ShowInfo() { cout<<FlightCode<<":"; <<Description<<endl ; } }; void main() { Flight F; AddInfo.F(); ShowInfo.F();
Answer:
#include<iostream.h> //# is required before include #include<stdio.h> //for gets() function class FLIGHT { long FlightCode; char Description[25]: public: void AddInfo() { cin>>FlightCode; gets(Description); } void ShowInfo() { cout<<FlightCode<<”: "<<Description <<endl; } }; void main() FLIGHT F; F.AddInfo(): //syntax is object.member_function F. ShowInfo(); <<endl; }
Question 6:
Rewrite the following program after removing the syntactical errors (if any).
Underline each correction. Delhi 2009C
#include<iostrearn.h> class Transport { char Model[20]; char Name[20]; void Get() { gets(Model); gets(Name); { void Show() { cout<<Model<<endl; puts(Name); } }; void main() { Transport T; T.Get(); Show() }
Answer:
#include<iostream.h> #include<stdio.h> class Transport { char Model[20]; char Name[20]; public: void Get() { gets(Model); gets(Name); } void Show() { cout<<Model<<endl ; puts(Name); } }: void main() { Transport T; T.Get(); T.Show(): }
Question 7:
Rewrite the folio wing C++program code after removing the syntax error(s) (if any). Underline each correction.
# include<iostream.h> Class student { int roll No: char Name; Public void get Data(); { cout<<"RollNo = "<<rollNo; cout<<"Name = "<<Name; } void setdata(); { cin>>roll No; cin>>Name; } } void main() { Student SI; SI .getdata(): SI. setdata(); } }
Answer:
#include<iostream. h> class student /* class keyword should be small and first letter of class will be capital letter according to main ()*/ { int roll No; char Name[20]: // the string must have an array public: // public keyword will be small letter //and: should be written after public void getdata() { cout<<"Roll No="<<roll No: cout<<"Name=''<<Name; } void setdata() { cin>>roll No; cin>>Name; } }; void main() { student S1; SI.getdata(); Sl.setdata(); }
Question 8:
How are objects implemented in C++?
Answer:
Objects are implemented in C++ as follows:
(i) The properties/characteristics are implemented by the data members or member variables.
(ii) Behaviour of an object is determined by its member function or method.
(iii) To identify each object, unique name is given to each of the objects.
Question 9:
What do you understand by data encapsulation and data hiding? Also, give an example in C++ to illustrate both. All India 2010
Answer:
When member data and member function are binded into a single unit then the data is not accessible to the outside world and only those functions, which are wrapped in that class can access it.
These functions are referred to as member functions and also provide the interface between the object’s data and the program. This insulation of data from direct access by the program is called data hiding or information hiding. In other words, we can say that encapsulation is implemented through data hiding.
Note Encapsulation is implemented in C++ with the help of classes. Data hiding is implemented in C++ with the help of private and protected keywords.
Question 10:
What is the relationship between class and object? Illustrate with a suitable example. Delhi 2013 C
Answer:
A class cannot be assigned to memory until the object is created. An object is a class variable, i.e. class is a data type and object is a variable of class type. Without class, object instantiation is not possible. Hence, we can say that an object does not exist without class and a class has no value without object. So, they are related to each other,
e.g. A class Box is given as follows:
class Box { int height; int width; int length; public: double volume (int h , int w, int l) { height = h; width = w; length = l ; return (height * width * length); } };
The above class will not assigned memory until the object is instantiated.
The object instantiation is given below:
Box b1;
After the object instantiated it will take place in memory.
Question 11:
Write a class in C++ that will implement the concept of function overloading techniques to find the area of rectangle and circle.
Answer:
class Shape { double area; publlc: double area(int r) { area = 3.146*r*r; return(area); } double area(int 1, int w) { area = 1 * w; return (area); } }:
Question 12:
How does object occupy memory in C++?
Answer:
The member functions are created and placed in the memory space only once when they are defined as a part of a class specification. Since, all the objects belonging to that class use the same member functions, no separate space is allocated for member functions when the objects are created.
Space for member variables is allocated separately for each objects. Separate memory locations for the objects are essential, because the member variables will hold different data values for different objects.
This is shown in figure:
Question 13:
When object is used as function argument, then how call by value is differ from call by reference?
Answer:
Difference between call by value and call by reference, when object is used as a function argument are as follows:
Question 14:
What do you understand by an array of objects? Explain with a suitable example.
Answer:
An array of object is the collection of same type of object having the same properties and behaviours. An array of object can be defined in the same manner as, we define array for build in type.
If we want to define an array of object of student type, we use the following syntax:
classname ArrayofObjectName[size];
consider a class student
class student (int roll No; char name[10]; void setdata(); void getdata(); } student S[10];
Where, S is an array of objects.
Question 15:
Rewrite the following program after removing the syntactical error(s) (if any). Underline each correction. Delhi 2012C
#include<iostream.h> #include<stdio.h> class OFFER { int Offerld; char Description[80]; Void show { cout<<offerId<<”:"<<Descri pti on ; cout<<endl; } public void Enter { cin>>0fferld; gets>>Description; } }; void main() { Offer obj; obj . Enter(); obj .show(); }
Answer:
#includeCiostream.h> #include<stdio.h> class OFFER { int Offerld: char Description[80]; void show() { cout<<0fferId<<":”<<Description<<endl; } public: void Enter() { cin>>0fferId; gets(Description); } }; void main() { OFFER obj; obj . Enter(); //obi.show(): //show cannot be called because in //class declared as private {
Question 16:
Difference between members, which are presented within the private visibility mode with those which are presented within the public visibility mode.
or
Differentiate between public and private visibility modes in context of object oriented programming using a suitable example. Delhi 2011,2008
Answer:
A member declared as private remains hidden from outside world and it can only be accessed by the member function of the class.
A member declared as public is made available to the outside world, i.e. it can be accessed by any function, any expression in the program but only by using an object of the same class type.
Question 17:
What do you understand by a member function? How does a member function differ from an ordinary function?
Answer:
Member functions are functions defined within class that act on data members in the class. The use of member functions distinguishes a class from struct. Whereas, an ordinary function can be called in any function without an object, the member function can be called only by using its object.
The member function is a member of its own class but an ordinary function is not.
Question 18:
Rewrite the following C++ program code after
removing the syntax error(s) (if any). Underline each correction. All India 2010
include<iostream.h> class TRAIN { long int TrainNo; char Description[25]; public void Entry() { cin>>TrainNo; gets(Description); } void Display() { cout<<T rainNo<<":" <<Description<<endl; } }; void main() { TRAIN T; Entry .T(); Display.T(); }
Answer:
#include<iostream.h> //# sign will before include. #include<stdio.h> //should be include this for gets()function class TRAIN { long int TrainNo; char Description[25]; public: //: sign is required after public void Entry() { cin>>TrainNo; gets(Description); } void Display() { cout<<T rainNo<<":" <<Description<<endl ; } }; void main() { TRAIN T; T.Entry(); //object name.functionname(); T.Displav(): //object name.functionname(); }
Question 19:
Define a class RESTRA in C++ with following descriptions: All India 2012
Private members
• Food Code of type int
• Food of type string
• FType of type string
• Sticker of type string
• A member function GetStickerf) to assign the following values for Food Sticker as per the given FType:
FType Sticker
Vegetarian GREEN
Contains Egg YELLOW
Non-vegetarian RED
Public members
• A function GetFoodf) to allow user to enter values for Food Code, Food, FType and call function GetSticker() to assign Sticker.
• A function ShowFood() to allow user to view the content of all the data members.
Answer:
class RESTRA { int FoodCode; char Food[30], FType[20], Sticker[20]; void GetSticker() { if(strcmp( FTypeVegetari an" )=0) strcpy(Sticker,"GREEN"); else if(strcmp(FType, "Contains Egg")==0) strcpy(Sticker,"YELLOW"); else if(strcmp(FType, "Non - vegetarian" ).=0) strcpy(Sticker,"RED"); } public: void GetFood() { cout<<"Enter FoodCode, Food, Food Type"; cin>>FoodCode; gets(Food); gets(FType); GetSticker(); } void ShowFood() { cout<<"Entered values of FoodCode," ; cout<<"Food, Food Type, Sticker"; cout<<FoodCode<<endl<<Food<<endl <<FType<<endl; cout<<Sticker; } };
Question 20:
Define a class Candidate in C++ with following descriptions: Delhi 2011
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 the remarks as per the score obtained by a candidate. Score range and the respective remarks are shown as follow:
Public members
A function ENTER() to allow user to enter values for RNo, Name, Score and call function AssignRem() to assign grade.
A function DISPLAY,() to allow user to view the content of all data members.
Answer:
class Candidate { long RNo; char Name[40]; float Score; char Remarks[20]; void AssignRem() { if(Score>=50) strcpy(Remarks."Selected"); else strcpy(Remarks,"Not selected"); } public: void ENTER() cout<<"Enter the values for Rno,"; cout<<"Name,Score"; cin>>RNo; gets(Name); cin>>Score; AssignRem(); { void DISPLAY() { cout<<RNo<<endl<<Name<<endl<<Score<<endl<<Remarks; } };
Question 21:
Define a class Applicant in C++ with the following descriptions: All India 2011
Private members
• A data member ANo (Admission Number) of type long
• A data member Name of type string A data member Agg (Aggregate Marks) of type float * A data member Grade of type char A
• member function GradeMef) to find the grade as per the aggregate marks obtained by a student. Equivalent aggregate marks range and the respective grades are shown as follow:
Public members
• A function ENTER() to allow user to enter values for ANo, Name, Agg and call function GradeMe() to find the Grade.
• A function RESULT() to allow user to view the content of all data members.
Answer:
class Applicant { long ANo; char Name[40]; float Agg; char Grade; void GradeMe!) { if(Agg>=80) Grade = 'A'; else if(Agg<80 && Agg>=65) Grade = 'B'; else if(Agg<65 && Agg>=50) Grade = 'C'; else Grade = 'D'; } public: void ENTER() { cout<<"Enter the values for Ano,Name,Agg"; cin>>ANo; gets(Name); cin>>Agg; GradeMe(); } void Result() } cout<<"ANo,Name,Agg.Grade”; cout<<ANo<<''\n"<<Name<<"\n" <<Agg<<"\n"<<Grade; } };
Question 22:
Define a class ITEM in C++ with the following specification: Delhi 2010
Private members
• Code of type integer (Item Code)
• Iname of type string (Item Name)
• Price of type float (Price of each item)
• Qty of type integer (Quantity of item stock)
• Offer of type float (Offer percentage on the item)
• A member function Getofferf) to calculate offer percentage as follows:
Public members
• A function GetStockf) to allow user to enter values for Code, Iname, Price, Qty and call function Getofferf) to calculate offer.
• A function Showitemf) to allow user to view the content of all data member.
Answer:
class ITEM int Code; char Iname[20]; float Price; int Qty; float Offer; void Getoffer(); public: void GetStock() { cout<<"Enter the values of code, Item name, Price and Quantity”; cin>>Code; gets(Iname); cin>>Price>>Qty; Getoffer(); } void Showitem() } }; cout<<Code<<endl<<Iname<<endl <<Price<<endl<<Qty<<endl<<0ffer; } }; void ITEM Getoffer() { if(Qty <= 50) Offer = 0; else if(Qty <= 100) Offer = 5; else Offer = 10; }
Question 23:
Define a class STOCK in C++ with the following specification: All India 2010
Private members
• ICode of type integer (Item Code)
• Item of type string (Item Name)
• Price of type float(Price of each item)
• Qty of type integer(Quantity in stock)
• Discount of type float (Discount percentage on the item)
• A member function FindDisc() to calculate discount percentage as follows:
Public members
• A function Buy() to allow user to enter values for ICode, Item, Price, Qty and call function FindDisc() to calculate discount.
• A function ShowAll() to allow user to view the content of all data member.
Answer:
class STOCK { int I Code; char Item[20]; float Price; int Qty; float Discount; void FindDisc(); public: void Buy() { cout<<"Enter Item code,Item name, Price and Quantity”; cin>>ICode; gets(Item); cin>>Price>>Qty; FindDisc(): } void ShowAll() { cout<<ICode<<endl<<Item<<endl<<Price<<endl<<Qty<<endl<<Discount; } } ; void STOCK :: FindDisc() { if(Qty <= 50) Discount = 0; else if(Qty <= 100) Discount = 5; else Discount = 10; }
Question 24:
Define a class RESORT in C++ with the following specification: Delhi 2009
Private members
• Rno Data member to store room number
• Name Data member to store customer name
• Charges Data member to store per day charges
• Days Data member to store number of days of stay
• COMPUTE() Function to calculate and return amount as days
* charges and if the value of days
* charges is more than 11000, then as 1,02
*days*charges.
Public members
• Getinfo() Function to enter the content Rno, Name,Charges and Days
• Dispinfo() Function to display Rno, Name, Charges, Days and Amount
(amount to be displayed by calling function) COMPUTE()
Answer:
class RESORT { int Rno; char Name[30]; float Charges; int Days; float COMPUTE() { float temp = Days*Charges; if(temp > 11000) return(1.02 * temp); return temp; { public: void Getinfo() { cout<<”Enter the room number"; cin>>Rno; cout<<"Enter the customer name"; gets(Name); cout<<"Enter the room charges per day"; cin>>Charges; cout<<"Enter number of days stayed by customer"; cin>>Days; } void Dispinfo() { cout<<"Room number:"<<Rno<<endl ; cout<<"Customer name;"; puts(Name); cout<<"Charges per day:" <<Charges<<endl cout<<"Number of days stayed by customer"<<Days<<endl cout<<"Total charges of customer" <<COMPUTE() } };
Question 25:
Define a class HOTEL in C++ with the following specification: All India 2009
Private members
• Rno Data member to store room number
• Name Data member to store customer name
• Tariff Data member to store per day charges
• NOD Data member to store number of days of stay
• CALC() Function to calculate and return amount as NOD
*Tariff and if the value of days
* Tariff is more than 10000,
then as 1.05 days*Tariff.
Public members
• Checkin() Function to enter the content Rno, Name, Tariff and NOD
• Checkout() Function to display Rno, Name, Tariff,
NOD and Amount (amount to be displayed by calling function) CALC()
Answer:
class HOTEL { int Rno,NOD; char Name[30]; float Tariff; float CALC() { float temp = NOD*Tariff; if(temp > 10000) return(1.05*temp); } cout<<"Enter the room number"; cin>>Rno; cout<<"Enter the customer name"; gets(Name); cout<<”Enter the room charges per day"; cin>>Tariff; cout<<"Enter number of days stayed by customer."; cin>>NOD; } void Checkout() { cout<<"Room number"<<Rno<<endl ; cout<<"Customer name"; puts(Name); cout<<"Charges per day:"<<Tariff<<endl ; cout<<"Number of days stayed by customer:"<<N0D<<endl; cout<<"Total charges of customer:"<<CALC(); } };
Question 26:
Define a class named FIOUSING in C++ with the following descriptions:
Private members
• REG_NO lnteger(Ranges 10-1000)
• NAME Array of characters(String)
• TYPE Character
• COST Float
Public members
• Read_Data() Function to read an object of HOUSING type
• Display() Function to display the details of an object
• Draw_Nos() Function to choose and display the details of 2 houses
selected randomly from an array of 10 objects of type HOUSING.
Use random function to generate the registration number
to match with REG_NO from the array.
Answer:
Assume that name of array of type HOUSING storing 10 objects is Arr.
class HOUSING { int REG_N0; char NAME[31]; char TYPE; float COST; public: void Read_Data() { cout<<"\nEnter the house number:"; cin>>REG_N0; cout<<"\nEnter the house name:"; gets(NAME); cout<<"\nEnter the house type:"; cin > >TY P E; cout<<"\nEnter the house cost:"; cin>>C0ST; } void Display() { cout<<"\nThe number of the house" <<REG_N0; cout<<"\nThe name of the house” <<NAME; cout<<"\nThe type of the house" <<TYPE; cout<<"\nThe cost of the house" <<C0ST; } void Draw_*Nos(H0USING *Arr); }; void HOUSING :: Draw_Nos(H0USING Arr[10]) { int nol,no2,i ; randomise(); nol=random(991)+10; // Generate a random number // between 10-1000 no2=random(991)+10; for(i=0;i<10;i++) { if((ArrCi].REG_N0 == nol)|| (Arr[i].REG_N0 == no2)) Arr[i].Display(); } }
Question 27:
Define a class BOOK in C++ with folio wing description:
Private members
• BOOK_NO Integer type
• BOOKJITLE 20 characters
• PRICE float (price per copy)
• TOTAL_COST() A function to calculate the total
cost for N number of copies, where N is
passed to the function as argument
Public members
• INPUT() Function to read BOOK_ NO, BOOK_TITLE, PRICE
• PURCHASE() Function to ask the user to input the number
of copies to be purchased. It invokes TOTAL_COST() and
prints the total cost to be paid by the user.
Answer:
class BOOK { int B00K_N0; char B00K_TITLE[20]; float PRICE; float T0TAL_C0ST(int N) { float TOTAL; TOTAL=N * PRICE; return TOTAL; } public: void INPUT() } cout<<"Enter book no:"; cin>>B00K_N0; cout<<"Enter book title:"; gets(BOOK_TITLE); cout<<"Enter price;"; cin>>PRICE; } void PURCHASE() { int n; float TOT; cout<<"Enter purchased copies:"; cin>>n; TOT = T0TAL_C0ST(n); cout<<"Total amount is"<<T0T; } };
Question 28:
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 initialise data members
(ii) To deposit money
(iii) To withdraw money after checking the balance (minimum balance is Rs. 1000)
(iv) To display the data members.
Answer:
class Bank { char name[15]; int acc_no; char acc_type; float bal_amount; public: void readData() { cout<<"\nEnter the name:"; gets(name); cout<<"\nEnter the account number:"; cin>>acc_no; cout<<"\nEnter the account type:"; cin>>acc_type; cout<<"\nEnter the balance amount"; cin>>bal_amount; { void deposit() { float deposit; cout<<"\nEnter your account number;"; cin>>acc_no; cout<<"\nEnter the amount to deposit:"; cin>>deposit; bal_amount = bal_amount + deposit; } void withdraw() { float w_amount; cout<<"\nEnter your account number:"; cin>>acc_no; cout<<"\nEnter amount to withdraw"; cin>>w_amount; if ((bal_amount - w_amount)<1000) cout<<"\nWithdraw is not possible"; else { bal_amount = bal_amount - w_amount; cout<<"\nThe balance is"; cout<<bal_amount; } } void display() { cout<<"\nName of depositor:"<<name; cout<<"\nAccount number:"<<acc_no; cout<<"\nAccount type:"<<acc_type; cout<<"\nThe balance amount is:"; cout<<bal_amount; } }b[10];
Question 29:
Define a class WORKER with the following specification:
Private members
• wno int
• wname 25 characters
• hrwrk,wgrate float (hours worked and wage rate per hour)
• totwage float(hrwrk*wgrate)
• calcwg() A function to find hrwrk*wgrate with float return type
Public members
• ln_data() A function to accept values for wno,
wname, hrwrk, wgrate and invoke
calcwg() to calculate totwage.
• Out__data() A function to display all the data
members on the screen you should
give definitions of functions.
Answer:
class WORKER { int wno; char wname[25]; float hrwrk,wgrate; float totwage; float calcwg() { return(hrwrk*wgrate); } public; void In_data() { cout<<"\nEnter worker number"; cout<<"\nName,hours worked & wage rate"; cin>>wno; gets(wname); void Out_data() cout<<"\nThe worker number:”<<wno; cout<<"\nName of the worker:" <<wname; cout<<"\nNumber of hours worked cout<<hrwrk; cout<<"\nWage rate of the worker:"; cout<<wgrate; cout<<"\nTotal wages of the worker:"; cout<<totwage; cin>>hrwrk>>wgrate; totwage = calcwg(); } };
Question 30:
Define a class STUDENT with the following specifications:
Private members
• Admno integer
• Sname 20 character
• English float
• Math float
• Science float
• Total float
• Ctotal() A function to calculate English + Math +
Science with float return type
Public members
• Takedata() Function to accept values for
Admno, Sname, English, Math, Science and
invoke Ctotal() to calculate total
• Showdata() Function to display all the data members on the screen.
Answer:
class STUDENT { int Admno; char Sname[20]; float English,Math,Science,Total; float Ctotal() { return(English+Math+Science); } public: void Takedata() { cout<<"\nEnter the admission number:"; cout<<"\nName of the student:"; cin>>Admno; gets(Sname); cout<<"\nEnter marks of E, M & S:"; cin>>English>>Math>>Science; Total=Ctotal(); } void Showdata() { cout<<"\nAdmission number of the student:"; cout<<Admno; cout<<"\n The Name of the student:"; cout<<Sname; cout<<"\nMarks are E, M & S..."; cout<<English<<"\t”<<Math<<"\t"; cout<<Science<<"\n"; cout<<"\nTotal marks of student:"; cout<<\nTotal; } };
Question 31:
Define a class EMPLOYEE with the following specifications:
Private members
• empno integer
• ename 20 characters
• basic, hra, da float
• netpay float
• calculate() A function to calculate basic + hra +
da with float return type.
Public members
• havedata() Function to accept values for empno,
sname, basic, hra, da and invoke
calculate() to calculate netpay
• display() Function to display all the data
members on the screen.
Answer:
class EMPLOYEE //class and function of EMPLOYEE class { int empno; char ename[20]; float basic,hra,da,netpay; float calculate() { return (basic+hra+da); } public: void havedata() { cout<<"\nEnter the employee number and name:”; cin>>empno; gets(ename); cout<<”\nEnter basic,hra ,da"; cin>>basic>>hra>>da; netpay = calculate(); } void display() { cout<<"\nThe employee number of the employee"<<empno; cout<<"\nThe name of the employee"<<ename; cout<<"\nbasic, hra and da are...”; cout<<basic<<”\t"<<hra<<"\t” <<da<<”\n"; cout<<"\nTotal pay of the employee”<<netpay; } };
Question 32:
Define a class Seminar with the following specification:
Private members
• SeminarlD long
• Topic string of 20 characters
• VenueLocation string of 20 characters
• Fee float
• CalcFee() function to calculate Fee depending in VenueLocation
Public members
• Register() function to accept values for SeminarlD, Topic,
VenueLocation and call CalcFee() to calculate Fee.
• ViewSeminar() function to display
all the datamembers on the screen. Delhi 2013C
Answer:
class Seminar { long Seminarld; char Topic[20], VenueLocation[20]; float Fee; void CalcFee() { if(strcmp(VenueLocation, "Outdoor”)==0) Fee=5000; else if(strcmp(VenueLocation, "Indoor Non-Ac")==0) Fee=6500; else if(strcmp(VenueLocation, "Indoor Ac")==0) Fee=7500; } public: void Register( ) { cout<<"Enter Seminar Id"; cin>>Seminarld; cout<<"Enter Topic"; getsdopi c); cout<<"Enter Venue Location"; gets(VenueLocation); CalcFee( ); } void ViewSeminar( ) { cout<<"Seminar Id:"<<SeminarId<<endl; cout<<"Topic”:<<Topic<<endl ; cout<<"VenueLocation:" <<VenueLocati'on<<endl ; cout<<"Fee is:"<<Fee; } }:
Question 33:
Define a class Directory in C++ with following specifications:
Public members
• Docunames An array of strings of size[10][25]
to represent all the names of documents inside directory
• Occupied long to represent total number of bytes used In directory.
• Freespace long to represent total number of bytes free in my directory
Public members
• Newdocumentry A function to accept values of Docunames,
Freespace and Occupied by user.
• Retfreespace() A function that returns the
value of total kilobytes available.
• Showfiles() A function that displays the names of all
documents in directory. Delhi 2003
Answer:
class Directory { char Docunames[10][25]; long Freespace; long Occupied; public: void Newdocumentry(); long Retfreespace(); void Showfiles(); }; void Directory :: Newdocumentry() { cout<<"Enter any 10 file names:"; for(int i=0;i<=9;i++) { cout<<"Enter the"<<i+l<<"file name:"; gets(Docunames[i]); } cout<<"Enter the Available Spacedn Kilobytes):”; cin>>Freespace; cout<<”Enter the Used Space (In Kilobytes):”; cin>>0ccupied; } long Directory :: Retfreespace() { return Freespace*1023; } void Directory::Showfiles() { cout<<"\nThe names of the files in myfolder object..."; for(i=0;i<=9;i++) { puts(Docunames[i]); cout<<endl; } }
Question 34:
Define a class with complete function definitions COMPETITION in C++ with following specifications:
Private members
• event_no integer
• description char (30)
• score integer
• qualified char
Public members
• Input () To take input for event_no, description and score.
• Award () To award qualified as ‘y’ if score is more than the cut off
score passed as int to the function else award ‘N’.
• show () To display all details.
Answer:
class COMPETITION { int event_no; char description[30]; int score; char qualified; public: void Input() { cout<<"Enter event no:"; cin>>event_no; cout<<"Enter description:"; cin>>description; cout<<"Enter score:"; cin>>score; } void Award(int cut_off) { if (score > cut_off) qualified = 'Y' ; else qualified = 'N'; } void show() { cout<<event_no<<"\t”<<description <<"\t"<<score «"\t"<<qualified;. } };
Question 35:
Define a class Flight in C++ with the following specification:
Private members
• A Data Member FlightNumber of type integer
• A Data Member Destination of type string
• A Data Member Distance of float type
• A Data Member Fuel of type float
• A Member Function CalFuelf) to calculate the value of fuel as per the following criteria:
Public members
• A function Feed_lnfo() to allow user to enter values for Flight Number, Destination, Distance and Call Function calfuel() to calculate the quantity of fuel.
• A function Show_Fuel() to allow user to view the content of all the data members.
Answer:
class Flight { int FlightNumber; char Destination[20]; float Distance; float Fuel; void Cal Fuel () { if(Distance <= 1000) Fuel = 500 ; else if(Distance > 1000 && Distance <= 2000) Fuel = 1100; else Fuel = 2200; } public: void Feed_Info() { cout<<"Enter the value of Flight Number cin>>FlightNumber; cout<<"Enter Destination"; cin>>Destination ; cout<<"Enter the Distance"; cin>>Distance; Cal Fuel (); } void Show_Fuel() { cout<<"Flight Number = "<<F1ightNumber; cout<<"\nDestination = "<<Destination ; cout<<”\n Distance = "<<Distance; cout<<"\nFuel = "<<Fuel; } };
Computer ScienceChapterwise Question Bank for Computer ScienceNCERT Solutions