0% found this document useful (0 votes)
28 views50 pages

C++ Paper Solution 2019

The document provides a comprehensive overview of various C++ concepts including unions, scope resolution operators, polymorphism, encapsulation, classes, arrays, inline functions, and data structures. It also discusses functions, the differences between pass by value and pass by reference, and the concept of inheritance along with its types such as single, multiple, multilevel, hierarchical, and hybrid inheritance. Additionally, it includes code examples to illustrate these concepts effectively.

Uploaded by

RamPrasad Saran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views50 pages

C++ Paper Solution 2019

The document provides a comprehensive overview of various C++ concepts including unions, scope resolution operators, polymorphism, encapsulation, classes, arrays, inline functions, and data structures. It also discusses functions, the differences between pass by value and pass by reference, and the concept of inheritance along with its types such as single, multiple, multilevel, hierarchical, and hybrid inheritance. Additionally, it includes code examples to illustrate these concepts effectively.

Uploaded by

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

C++ Paper Solution: 2019

Q1. a) Define Union in C++.


Ans: A union is a special class type that can hold only one of its non-static data
members at a time. list of access specifiers, member object and member function
declarations and definitions. A union can have member functions (including
constructors and destructors), but not virtual functions.

b) Define Scope Resolution Operator.


Ans: The :: (scope resolution) operator is used to get hidden names due to variable
scopes so that you can still use them. The scope resolution operator can be used as
both unary and binary. You can use the unary scope operator if a namespace scope
or global scope name is hidden by a particular declaration of an equivalent name
during a block or class.

c) What do you mean by polymorphism?


Ans: Polymorphism means multiple forms that allow you to use a single interface
for performing multiple actions in a program. Polymorphism helps reduce
complexity in programming by allowing you to perform common operations using
the same function name. The compiler selects the type of function that needs to be
called to perform the specific task.

d) What is Encapsulation?
Ans: In C++, the technique of binding the data and functions together in a single
unit is called encapsulation. Encapsulation helps secure the data and functions
from outside interference as data is accessible only to the member functions of the
object. These member functions provide an interface between the data of an object
and the program.

e) Define class.
Ans: A class is a collection of similar types of objects that share common attributes
and behavior. Objects are the variables of user-defined type called class. In an OOP
program, you create classes to develop an application. You can categorize the real
world into classes such as human being, automobiles, furniture, fruit and electrical
appliances. Each class has some properties and functions.

f) How will you declare 2-D array in C++?


Ans: data_type array_name[size1][size2]....[sizeN];
data_type: Type of data to be stored in the array. Here data_type is valid C/C++
data type
array_name: Name of the array
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 1
C++ Paper Solution: 2019

size1, size2,... ,sizeN: Sizes of the dimensions

g) What is inline function?


Ans: Inline functions are functions where the call is made to inline functions. The
actual code then gets placed in the calling program.

h) Define data structure.


Ans: Data structure is logical or mathematical organization of data; it
describes how to store the data and access data from memory. Actually in our
programming data stored in main memory(RAM) and To develop efficient software
or firmware we need to care about memory. To efficiently manage we required data
structure.

Q2. a) Define functions. Discuss the concepts of “pass by value” and “pass
by reference” with the help of program in C++.
Ans: A function is a subprogram that acts on data and often returns a value. A
program written with numerous functions is easier to maintain, update and debug
than one very long program. By programming in a modular (functional) fashion,
several programmers can work independently on separate functions which can be
assembled at a later date to create the entire project. Each function has its own
name. When that name is encountered in a program, the execution of the program
branches to the body of that function. When the function is finished, execution
returns to the area of the program code from which it was called, and the program
continues on to the next line of code.

Creating User-Defined Functions


Declare the function.
The declaration, called the FUNCTION PROTOTYPE, informs the compiler about
the functions to be used in a program, the argument they take and the type of value
they return.
Define the function.
The function definition tells the compiler what task the function will be performing.
The function prototype and the function definition must be same on the return type,
the name, and the parameters. The only difference between the function prototype
and the function header is a semicolon.
The function definition consists of the function header and its body. The header is
EXACTLY like the function prototype, EXCEPT that it contains NO terminating
semicolon.
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 2
C++ Paper Solution: 2019

//Prototyping, defining and calling a function


#include <iostream.h>
void starline(); // prototype the function
int main()
{
starline( ); // function call
cout<< "\t\tBjarne Stroustrup\n";
starline( ); // function call
return 0;
}
// function definition
void starline()
{
int count; // declaring a LOCAL variable
for(count = 1; count <=65; count++)
cout<< "*";
cout<<endl;
}
ARGUMENT TO A FUNCTION
Sometimes the calling function supplies some values to the called function. These
are known as parameters. The variables which supply the values to a calling
function called actual parameters. The variable which receive the value from
called statement are termed formal parameters.
Consider the following example that evaluates the area of a circle.
#include<iostream.h>
void area(float);
int main()
{
float radius;
cin>>radius;
area(radius);
return 0;
}
void area(float r)
{
cout<< ―the area of the circle is‖<<3.14*r*r<<‖\n‖;
}
Here radius is called actual parameter and r is called formal parameter.
RETURN TYPE OF A FUNCTION
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 3
C++ Paper Solution: 2019

// Example program
#include <iostream.h>
int timesTwo(int num); // function prototype
int main()
{
int number, response;
cout<<"Please enter a number:";
cin>>number;
response = timesTwo(number); //function call
cout<< "The answer is "<<response;
return 0;
}
//timesTwo function
int timesTwo (int num)
{
int answer; //local variable
answer = 2 * num;
return (answer);
}
CALLING OF FUNCTION
The function can be called using either of the following methods:
i) Call by value
ii) Call by reference
CALL BY VALUE
In call by value method, the called function creates its own copies of original values
sent to it. Any changes, that are made, occur on the function‘s copy of values and
are not reflected back to the calling function.
CALL BY REFERENCE
In call be reference method, the called function accesses and works with the original
values using their references. Any changes, that occur, take place on the original
values are reflected back to the calling code.
Consider the following program which will swap the value of two variables.
using call by reference using call by value
#include<iostream.h>
void swap(int &, int &);
int main()
{
int a=10,b=20;
swap(a,b);
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 4
C++ Paper Solution: 2019

cout<<a<<" "<<b;
return 0;
}
void swap(int &c, int &d)
{
int t;
t=c;
c=d;
d=t;
}
#include<iostream.h>
void swap(int , int );
int main()
{
int a=10,b=20;
swap(a,b);
cout<<a<<" "<< b;
return 0;
}
void swap(int c, int d)
{
int t;
t=c;
c=d;
d=t;
}
output:
20 10
output:
10 20
Function With Default Arguments
C++ allows to call a function without specifying all its arguments. In such cases, the
function assigns a default value to a parameter which does not have a matching
arguments in the function call. Default values are specified when the function is
declared. The complier knows from the prototype how many arguments a function
uses for calling.
Example : float result(int marks1, int marks2, int marks3=75);a subsequent
function call

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 5


C++ Paper Solution: 2019

average = result(60,70);passes the value 60 to marks1, 70 to marks2 and lets the


function use default value of 75 for marks3.
The function callaverage = result(60,70,80);passes the value 80 to marks3.

b) What is Inheritance? What are different types of inheritance available


in C++?
Ans: One of the most important concepts in object-oriented programming is that of
inheritance. Inheritance allows us to define a class in terms of another class, which
makes it easier to create and maintain an application. This also provides an
opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and
member functions, the programmer can designate that the new class should inherit
the members of an existing class. This existing class is called the base class, and
the new class is referred to as the derived class.

Sub Class: The class that inherits properties from another class is called Sub class
or Derived Class.
Super Class: The class whose properties are inherited by sub class is called Base
Class or Super class.

Why and when to use inheritance?


Consider a group of vehicles. We need to create classes for Bus, Car and Truck. The
methods fuelAmount(), capacity(), applyBrakes() will be same for all of the three
classes. If we create these classes avoiding inheritance then we have to write all of
these functions in each of the three classes as shown in below figure:

We can clearly see that above process results in duplication of same code 3 times.
This increases the chances of error and data redundancy. To avoid this type of
situation, inheritance is used. If we create a class Vehicle and write these three

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 6


C++ Paper Solution: 2019

functions in it and inherit the rest of the classes from the vehicle class, then we can
simply avoid the duplication of data and increase re-usability. Look at the below
diagram in which the three classes are inherited from vehicle class:

Using inheritance, we have to write the functions only one time instead of three
times as we have inherited rest of the three classes from base class(Vehicle).
Implementing inheritance in C++: For creating a sub-class which is inherited
from the base class we have to follow the below syntax.
Syntax:
class subclass_name : access_mode base_class_name
{
//body of subclass
};
Here, subclass_name is the name of the sub class, access_mode is the mode in
which you want to inherit this sub class for example: public, private etc.
and base_class_name is the name of the base class from which you want to inherit
the sub class.
Note: A derived class doesn‘t inherit access to private data members. However, it
does inherit a full parent object, which contains any private members which that
class declares.
//Base class
class Parent
{
public:
int id_p;
};

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 7


C++ Paper Solution: 2019

// Sub class inheriting from Base Class(Parent)


class Child : public Parent
{
public:
int id_c;
};

//main function
int main()
{

Child obj1;

// An object of class child has all data members


// and member functions of class parent
obj1.id_c = 7;
obj1.id_p = 91;
cout << "Child id is " << obj1.id_c << endl;
cout << "Parent id is " << obj1.id_p << endl;

return 0;
}
Output:

Child id is 7
Parent id is 91
In the above program the ‗Child‘ class is publicly inherited from the ‗Parent‘ class so
the public data members of the class ‗Parent‘ will also be inherited by the class
‗Child‘.

Modes of Inheritance
1. Public mode: If we derive a sub class from a public base class. Then the
public member of the base class will become public in the derived class and
protected members of the base class will become protected in derived class.
2. Protected mode: If we derive a sub class from a Protected base class. Then
both public member and protected members of the base class will become
protected in derived class.
3. Private mode: If we derive a sub class from a Private base class. Then both
public member and protected members of the base class will become Private in
derived class.
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 8
C++ Paper Solution: 2019

Note : The private members in the base class cannot be directly accessed in the
derived class, while protected members can be directly accessed. For example,
Classes B, C and D all contain the variables x, y and z in below example. It is just
question of access.

class A
{
public:
int x;
protected:
int y;
private:
int z;
};

class B : public A
{
// x is public
// y is protected
// z is not accessible from B
};

class C : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};

class D : private A // 'private' is default for classes


{
// x is private
// y is private
// z is not accessible from D
};

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 9


C++ Paper Solution: 2019

The below table summarizes the above three modes and shows the access specifier
of the members of base class in the sub class when derived in public, protected and
private modes:

Types of Inheritance in C++


1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Hybrid (virtual ) inheritance

1. Single Inheritance: In single inheritance, a class is allowed to inherit from only


one class. i.e. one sub class is inherited by one base class only.

Syntax:
class subclass_name : access_mode base_class
{
//body of subclass
};

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 10


C++ Paper Solution: 2019

class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};

// sub class derived from two base classes


class Car: public Vehicle{

};

// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
Output:
This is a vehicle

2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class


can inherit from more than one classes. i.e one sub class is inherited from more
than one base classes.

.
Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2,
....

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 11


C++ Paper Solution: 2019

{
//body of subclass
};
Here, the number of base classes will be separated by a comma (‗, ‗) and access mode
for every base class must be specified.
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};

// second base class


class FourWheeler {
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle" << endl;
}
};

// sub class derived from two base classes


class Car: public Vehicle, public FourWheeler {

};

// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
Output:
This is a Vehicle
This is a 4 wheeler Vehicle

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 12


C++ Paper Solution: 2019

3. Multilevel Inheritance: In this type of inheritance, a derived class is created


from another derived class.

class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
class fourWheeler: public Vehicle
{ public:
fourWheeler()
{
cout<<"Objects with 4 wheels are vehicles"<<endl;
}
};
// sub class derived from two base classes
class Car: public fourWheeler{
public:
car()
{
cout<<"Car has 4 Wheels"<<endl;
}
};

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 13


C++ Paper Solution: 2019

// main function
int main()
{
//creating object of sub class will
//invoke the constructor of base classes
Car obj;
return 0;
}
Output:
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels

4. Hierarchical Inheritance: In this type of inheritance, more than one sub class
is inherited from a single base class. i.e. more than one derived class is created from
a single base class.

class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};

// first sub class


class Car: public Vehicle
{

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 14


C++ Paper Solution: 2019

};

// second sub class


class Bus: public Vehicle
{

};

// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base class
Car obj1;
Bus obj2;
return 0;
}
Output:
This is a Vehicle
This is a Vehicle

5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by


combining more than one type of inheritance. For example: Combining Hierarchical
inheritance and Multiple Inheritance.

Below image shows the combination of hierarchical and multiple inheritance:

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 15


C++ Paper Solution: 2019

class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};

//base class
class Fare
{
public:
Fare()
{
cout<<"Fare of Vehicle\n";
}
};

// first sub class


class Car: public Vehicle
{

};

// second sub class


class Bus: public Vehicle, public Fare
{

};

// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base class
Bus obj2;
return 0;
}
Output:
This is a Vehicle
Fare of Vehicle

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 16


C++ Paper Solution: 2019

Q3. a) How function overloading is possible in C++? Discuss with C++


program.
Ans: C++ allows you to specify more than one definition for a function name or an
operator in the same scope, which is called function overloading and operator
overloading respectively. An overloaded declaration is a declaration that had been
declared with the same name as a previously declared declaration in the same
scope, except that both declarations have different arguments and obviously
different definition (implementation).
When you call an overloaded function or operator, the compiler determines the
most appropriate definition to use by comparing the argument types you used to call
the function or operator with the parameter types specified in the definitions. The
process of selecting the most appropriate overloaded function or operator is called
overload resolution.
You can have multiple definitions for the same function name in the same scope.
The definition of the function must differ from each other by the types and/or the
number of arguments in the argument list. You can not overload function
declarations that differ only by return type.
Following is the example where same function print() is being used to print
different data types:
#include <iostream>
class printData
{
public:
void print(int i)
{
cout << "Printing int: " << i << endl;
}
void print(double f)
{
cout << "Printing float: " << f << endl;
}
void print(char* c)
{
cout << "Printing character: " << c << endl;
}
};
int main(void)
{
printData pd;
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 17
C++ Paper Solution: 2019

// Call print to print integer


pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
return 0;
}

b) What are the characteristics of OOP’s approach?


Ans: The basic concepts of OOP revolve around several key terms. These key terms
are:
1) Object
2) Class
3) Encapsulation
4) Abstraction
5) Inheritance
6) Polymorphism
7) Dynamic Binding
8) Reusability
9) Message Passing
10) Operator Overloading

1. Object
An object is a real-world run-time entity in OOP that has some attributes and
behavior such as person, place and vehicle. It represents user-defined data types
such as vectors, angles and programming constructs. An object contains data
variables and functions to store and manipulate the data. For example, a student
object consists of data variables such as name, rollno and marks, and functions such
as get_data(), calculate_percentage and display_data. The get_data() function reads
the data, the calculate_percentage function calculates the percentage and the
display_data function displays the student data. The functions associated with an
object are called its member functions. In an object, the data variables can only be
accessed by its member functions. Figure shows the data and member functions
associated with the student object.

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 18


C++ Paper Solution: 2019

Figure: student object


2. Class
A class is a collection of similar types of objects that share common attributes and
behavior. Objects are the variables of user-defined type called class. In an OOP
program, you create classes to develop an application. You can categorize the real
world into classes such as human being, automobiles, furniture, fruit and electrical
appliances. Each class has some properties and functions. For example, the human
being class has the properties such as height, weight, colour of eyes and colour of
hair. The functions of human being class are walking, talking, sleeping, breathing,
etc. You can take a class, Car, having properties such as model, colour and capacity.
The functions that the Car class performs are speed, average, start and stop.
In technical terms, a class consists of member variables or properties and member
functions. A class is also called abstract data type because it is only a template or
design to be used by the objects of the class. Figure shows the class, Car.

Figure: Class Structure

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 19


C++ Paper Solution: 2019

The Car class is divided into two parts—member variables or properties and
member functions. Model, colour and capacity are the properties and speed and
average are the member functions of the Car class.

3. Encapsulation
In C++, the technique of binding the data and functions together in a single unit is
called encapsulation. Encapsulation helps secure the data and functions from
outside interference as data is accessible only to the member functions of the object.
These member functions provide an interface between the data of an object and the
program. Encapsulation is also called data hiding because it protects data from
direct access. To implement this technique, the data variables and methods are
defined as private or public. The private data is accessible only to the member
functions of the class and the public data represents the information that can be
accessible to the external users of the class.
4. Abstraction
Abstraction means representing the essential features without mentioning the
background details. In C++, objects use the concept of abstraction which helps
represent only the important details related to an entity. Data can be accessed only
by the member functions of a class. Member functions of an object act as an
abstraction medium that is used to provide an interface between data and a
program.

5. Inheritance
Inheritance is the process of defining new classes by extending the properties of
other classes. The class that acquires the properties of other class is called derived
class and the class from which the properties are inherited is called base class. The
derived class shares the properties of the base class and also adds its own
characteristics to create additional features. The derived class needs to define only
those properties which are unique to it. Inheritance supports the concept of
classification. For example, a car is a part of the four-wheeler class that, in turn, is
a part of the vehicle class. It means a car has the properties of both four-wheeler
and vehicle classes. It also means that a car is a subclass of the four-wheeler class
that, in turn, is the subclass of the vehicle class. The vehicle class is the super class
of all the classes. Figure shows the concept of inheritance in OOP.

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 20


C++ Paper Solution: 2019

Figure Inheritance in OOP

For example, there are three base classes and from these base classes, three classes
are derived. Each derived class contains its own unique features and the features of
a base class also. Inheritance provides the concept of reusability which means using
the existing classes to derive new classes. Using inheritance, you can add additional
properties to an existing class without modifying it.

6. Polymorphism
Polymorphism means multiple forms that allow you to use a single interface for
performing multiple actions in a program. Polymorphism helps reduce complexity in
programming by allowing you to perform common operations using the same
function name. The compiler selects the type of function that needs to be called to
perform the specific task. For example, in a shape class, polymorphism enables the
programmer to define different area methods for any geometrical shape such as
circle, rectangle or triangle. The method name, Area 0 is same but the parameters
passed in the Area 0 method are different for different shapes. Polymorphism is
widely used to implement inheritance. Figure shows an example of polymorphism.

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 21


C++ Paper Solution: 2019

Figure: The Polymorphic Function

7. Dynamic Binding
Binding is the process of linking a function call to execute code. It means when a
function is called in a program, the code is attached with it during binding. Binding
is of two types—static binding and dynamic binding. Static binding means the code
to be executed in response to a function call is known at the compilation time of the
code. It means the function call is bound to its code when the program is being
compiled. Dynamic binding resolves the code associated with a given function call at
run-time. OOP supports dynamic binding. This means that OOP has the facility to
link the function call to its code at run time using virtual functions.

8. Reusability
Object-oriented programming allows reusability of a code. If you have designed a
class, any programmer can also use it in his program. You can add a new feature to
an existing class in order to make a derived class using inheritance. Figure shows
how you can implement reusability.

Figure Implementing Reusability

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 22


C++ Paper Solution: 2019

9. Message Passing
In the object-oriented programming, a program consists of objects that communicate
with each other. You create classes that consist of properties and functions. Then,
you create objects based on class definition and establish communication among
objects. The message that the objects pass among themselves is a request for
execution of a procedure. The message passing involves three things—name of the
object, name of the function and information to be sent. An object can send and
receive message until it is destroyed.

10. Operator Overloading


Operator overloading refers to a mechanism that you use to redefine operators for
different objects by using the operator keyword. You can use operator overloading to
modify the built-in operators to develop user-defined operators.

Q4. a) What do you mean by file handling. Write a C++ program to copy
contents of one file to another.
Ans: File Stream
So far, we have been using the iostream standard library, which
provides cin and cout methods for reading from standard input and writing to
standard output respectively.
This tutorial will teach you how to read and write from a file. This requires another
standard C++ library called fstream, which defines three new data types –
Sr.No Data Type & Description
1 ofstream
This data type represents the output file stream and is used to create files
and to write information to files.
2 ifstream
This data type represents the input file stream and is used to read
information from files.
3 fstream
This data type represents the file stream generally, and has the capabilities
of both ofstream and ifstream which means it can create files, write
information to files, and read information from files.

To perform file processing in C++, header files <iostream> and <fstream> must be
included in your C++ source file.

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 23


C++ Paper Solution: 2019

Opening a File
A file must be opened before you can read from it or write to it.
Either ofstream or fstream object may be used to open a file for writing. And
ifstream object is used to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream,
ifstream, and ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and
the second argument of the open() member function defines the mode in which the
file should be opened.
Sr.No Mode Flag & Description
1 ios::app
Append mode. All output to that file to be appended to the end.
2 ios::ate
Open a file for output and move the read/write control to the end of the file.
3 ios::in
Open a file for reading.
4 ios::out
Open a file for writing.
5 ios::trunc
If the file already exists, its contents will be truncated before opening the
file.
You can combine two or more of these values by ORing them together. For example
if you want to open a file in write mode and want to truncate it in case that already
exists, following will be the syntax −
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows

fstream afile;
afile.open("file.dat", ios::out | ios::in );

Closing a File
When a C++ program terminates it automatically flushes all the streams, release
all the allocated memory and close all the opened files. But it is always a good
practice that a programmer should close all the opened files before program
termination.

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 24


C++ Paper Solution: 2019

Following is the standard syntax for close() function, which is a member of fstream,
ifstream, and ofstream objects.
void close();

Writing to a File
While doing C++ programming, you write information to a file from your program
using the stream insertion operator (<<) just as you use that operator to output
information to the screen. The only difference is that you use
an ofstream or fstream object instead of the cout object.

Reading from a File


You read information from a file into your program using the stream extraction
operator (>>) just as you use that operator to input information from the keyboard.
The only difference is that you use an ifstream or fstream object instead of
the cin object.

Read and Write Example


Following is the C++ program which opens a file in reading and writing mode. After
writing information entered by the user to a file named afile.dat, the program reads
information from the file and outputs it onto the screen −

#include <fstream.h>
#include <iostream.h>
int main ()
{
char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
// again write inputted data into the file.
outfile << data << endl;
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 25
C++ Paper Solution: 2019

// close the opened file.


outfile.close();
// open a file in read mode.
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
// write the data at the screen.
cout << data << endl;
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
// close the opened file.
infile.close();
return 0;
}

b) What is stack? Write the insertion and deletion algorithm in stack.


Ans: Stack is a linear data structure which follows a particular order in which the
operations are performed. The order may be LIFO(Last In First Out) or FILO(First
In Last Out).

There are many real-life examples of a stack. Consider an example of plates stacked
over one another in the canteen. The plate which is at the top is the first one to be
removed, i.e. the plate which has been placed at the bottommost position remains in
the stack for the longest period of time. So, it can be simply seen to follow
LIFO(Last In First Out)/FILO(First In Last Out) order.

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 26


C++ Paper Solution: 2019

Mainly the following three basic operations are performed in the stack:
 Push: Adds an item in the stack. If the stack is full, then it is said to be an
Overflow condition.
 Pop: Removes an item from the stack. The items are popped in the reversed
order in which they are pushed. If the stack is empty, then it is said to be an
Underflow condition.
 Peek or Top: Returns top element of stack.
 isEmpty: Returns true if stack is empty, else false.

Applications of stack:
 Balancing of symbols
 Infix to Postfix /Prefix conversion
 Redo-undo features at many places like editors, photoshop.
 Forward and backward feature in web browsers
 Used in many algorithms like Tower of Hanoi, tree traversals, stock span
problem, histogram problem.
 Other applications can be Backtracking, Knight tour problem, rat in a
maze, N queen problem and sudoku solver
 In Graph Algorithms like Topological Sorting and Strongly Connected
Components

Implementation of Stack Data Structure


Stack can be easily implemented using an Array or a Linked List. Arrays are quick,
but are limited in size and Linked List requires overhead to allocate, link, unlink,
and deallocate, but is not limited in size. Here we will implement Stack using array.

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 27


C++ Paper Solution: 2019

Algorithm for PUSH operation

1. Check if the stack is full or not.


2. If the stack is full, then print error of overflow and exit the program.
3. If the stack is not full, then increment the top and add the element.

Algorithm for POP operation

1. Check if the stack is empty or not.


2. If the stack is empty, then print error of underflow and exit the program.
3. If the stack is not empty, then print the element at the top and decrement the
top.

Below we have a simple C++ program implementing stack data structure while
following the object oriented programming concepts.
class Stack
{
int top;
public:

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 28


C++ Paper Solution: 2019

int a[10]; //Maximum size of Stack


Stack()
{
top = -1;
}

// declaring all the function


void push(int x);
int pop();
void isEmpty();
};

// function to insert data into stack


void Stack::push(int x)
{
if(top >= 10)
{
cout << "Stack Overflow \n";
}
else
{
a[++top] = x;
cout << "Element Inserted \n";
}
}

// function to remove data from the top of the stack


int Stack::pop()
{
if(top < 0)
{
cout << "Stack Underflow \n";
return 0;
}
else
{
int d = a[top--];
return d;
}
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 29
C++ Paper Solution: 2019

// function to check if stack is empty


void Stack::isEmpty()
{
if(top < 0)
{
cout << "Stack is empty \n";
}
else
{
cout << "Stack is not empty \n";
}
}

// main function
int main() {

Stack s1;
s1.push(10);
s1.push(100);
/*
preform whatever operation you want on the stack
*/
}

Q5. a) Define exception handling. Explain the use of try, catch and throw
for exception handling in C++.
Ans: An exception is a problem that arises during the execution of a program. A
C++ exception is a response to an exceptional circumstance that arises while a
program is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another.
C++ exception handling is built upon three keywords: try, catch, and throw.
 throw − A program throws an exception when a problem shows up. This is
done using a throw keyword.
 catch − A program catches an exception with an exception handler at the
place in a program where you want to handle the problem.
The catch keyword indicates the catching of an exception.

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 30


C++ Paper Solution: 2019

 try − A try block identifies a block of code for which particular exceptions
will be activated. It's followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a
combination of the try and catch keywords. A try/catch block is placed around the
code that might generate an exception. Code within a try/catch block is referred to
as protected code, and the syntax for using try/catch as follows −
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
You can list down multiple catch statements to catch different type of exceptions in
case your try block raises more than one exception in different situations.

Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throw statement.
The operand of the throw statement determines a type for the exception and can be
any expression and the type of the result of the expression determines the type of
exception thrown.
Following is an example of throwing an exception when dividing by zero condition
occurs −

double division(int a, int b) {


if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}

Catching Exceptions
The catch block following the try block catches any exception. You can specify what
type of exception you want to catch and this is determined by the exception
declaration that appears in parentheses following the keyword catch.

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 31


C++ Paper Solution: 2019

try {
// protected code
} catch( ExceptionName e ) {
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type. If you want to specify
that a catch block should handle any type of exception that is thrown in a try block,
you must put an ellipsis, ..., between the parentheses enclosing the exception
declaration as follows −
try {
// protected code
} catch(...) {
// code to handle any exception
}
The following is an example, which throws a division by zero exception and we catch
it in catch block.
double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}

int main () {
int x = 50;
int y = 0;
double z = 0;

try {
z = division(x, y);
cout << z << endl;
} catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 32


C++ Paper Solution: 2019

b) Define Constructor. How will you overload a constructor? Explain with


example.
Ans: What is constructor?
A constructor is a member function of a class which initializes objects of a class. In
C++, Constructor is automatically called when object (instance of class) create. It is
special member function of the class.
How constructors are different from a normal member function?
A constructor is different from normal functions in following ways:
 Constructor has same name as the class itself
 Constructors don‘t have return type
 A constructor is automatically called when an object is created.
 If we do not specify a constructor, C++ compiler generates a default
constructor for us (expects no parameters and has an empty body).

Types of Constructors
1. Default Constructor: Default constructor is the constructor which doesn‘t
take any argument. It has no parameters.

class construct {
public:
int a, b;

// Default Constructor
construct()
{
a = 10;
b = 20;
}
};

int main()

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 33


C++ Paper Solution: 2019

{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: " << c.a << endl
<< "b: " << c.b;
return 1;
}
Output:
a: 10
b: 20
Note: Even if we do not define any constructor explicitly, the compiler will
automatically provide a default constructor implicitly.
2. Parameterized Constructors: It is possible to pass arguments to constructors.
Typically, these arguments help initialize an object when it is created. To create
a parameterized constructor, simply add parameters to it the way you would to
any other function. When you define the constructor‘s body, use the parameters
to initialize the object.

class Point {
private:
int x, y;

public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}

int getX()
{
return x;
}
int getY()
{
return y;
}
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 34
C++ Paper Solution: 2019

};

int main()
{
// Constructor called
Point p1(10, 15);

// Access values assigned by constructor


cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();

return 0;
}
1. Output:
p1.x = 10, p1.y = 15
When an object is declared in a parameterized constructor, the initial values
have to be passed as arguments to the constructor function. The normal way of
object declaration may not work. The constructors can be called explicitly or
implicitly.
Example e = Example(0, 50); // Explicit call

Example e(0, 50); // Implicit call

Uses of Parameterized constructor:


1. It is used to initialize the various data elements of different objects
with different values when they are created.
2. It is used to overload constructors.
Can we have more than one constructors in a class?
Yes, It is called Constructor Overloading.

3. Copy Constructor: A copy constructor is a member function which initializes


an object using another object of the same class. Detailed article on Copy
Constructor.
Whenever we define one or more non-default constructors( with parameters ) for
a class, a default constructor( without parameters ) should also be explicitly
defined as the compiler will not provide a default constructor in this case.
However, it is not necessary but it‘s considered to be the best practice to always
define a default constructor.

class point {
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 35
C++ Paper Solution: 2019

private:
double x, y;

public:
// Non-default Constructor & default Constructor
point (double px, double py) {
x = px, y = py;
}
};

int main(void) {
// Define an array of size 10 & of type point
// This line will cause error
point a[10];

// Remove above line and program will compile without error


point b = point(5, 6);
}

Q6 a) Differentiate between C and C++.


Ans: C++ is an extension of C and provides enhancements that C language does not
support. Following points help compare C and C++:

1) C++ allows you to use Standard Library as well as the Standard Template
Library containing various templates such as sort routine that you use to create
real-world programs whereas C uses only Standard Library.

2) C++ provides memory management operator such as new and delete to allocate
memory to the programs dynamically whereas C uses malloc and free memory
management operators to allocate memory while writing a program.

3) C++ allows you to use stream operators such as cin and cout stored in the
iostream class to perform tasks such as converting the entire input data in user
readable form from machine code and vice versa whereas C doesn't provide any
stream operator. C reads only a character from the entire stream of data.

4) C++ allows you to declare variables anywhere in the program whereas C allows
you to declare a variable only at the beginning of a function.
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 36
C++ Paper Solution: 2019

5) C++ allows you to use the bool keyword to refer to booleans whereas C uses 0 and
1 for specifying false and true values of booleans.

6) C++ assigns .cpp extensions to the programs created in C++ whereas C programs
are identified with .c extension.

7) C++ uses simpler language to write programs than C leading to lesser number of
errors in the program.

8) C++ allows you to define a class that includes objects sharing a common
behaviour whereas C does not allow you to define a class.

9) C++ allows you to use \\ and /* */ symbol to define a comment whereas C allows
you to use only /* */ symbol to define a comment.

b) Write note on data hiding.


Ans: It means that data is concealed (masked) within a class so that it cannot be
accessed by functions outside the class even by mistake.
The mechanism used to hide data is to put it in a class & make it private.
The body of the class has two keywords namely :
(i) private
(ii) public
In C++, the keywords private and public are called access specifiers. The data
hiding concept in C++ is achieved by using the keyword private.
Private data and functions can only be accessed from within the class itself. Public
data and functions are accessible outside the class also.
Data hiding not mean the security technique used for protecting computer
databases.
The security measure is used to protect unauthorized users from performing any
operation (read/write or modify) on the data.
The data declared under Private section are hidden and safe from accidental
manipulation. Though the user can use the private data but not by accident.
The principle of data hiding helps the programmer to build secure program that
can not be invaded by code in other parts of a programs.
Data and encapsulation is the most striking feature of a class. The data is not
accessible to the outside world, and only those functions which are wrapped in the
class can access it.
These functions provide the interface between the object‘s data and the program.
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 37
C++ Paper Solution: 2019

This insulation of the data from direct access by the program is called data
hiding or information hiding.
class MyRank{
int a;
public: void read(); //default accessibility is private
void print();
};
void MyRank :: read() {
cout<<"Enter any Integer value"<<endl;
cin>>a; }
void MyRank :: print(){
cout<<"The value is "<<a<<endl; }
int main(){
MyRank k;
k.read();
k.print();
return 0;
}

Q7 a) Write an algorithm to perform basic operation in linked list.


Ans: Linear Linked list is the default linked list and a linear data structure in
which data is not stored in contiguous memory locations but each data node is
connected to the next data node via a pointer, hence forming a chain.
The element in such a linked list can be inserted in 2 ways:
 Insertion at beginning of the list.
 Insertion at the end of the list.
Hence while writing the code for Linked List we will include methods to insert or
add new data elements to the linked list, both, at the beginning of the list and at the
end of the list.
We will also be adding some other useful methods like:
 Checking whether Linked List is empty or not.
 Searching any data element in the Linked List
 Deleting a particular Node(data element) from the List
Before learning how we insert data and create a linked list, we must understand
the components forming a linked list, and the main component is the Node.

What is a Node?
A Node in a linked list holds the data value and the pointer which points to the
location of the next node in the linked list.
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 38
C++ Paper Solution: 2019

In the picture above we have a linked list, containing 4 nodes, each node has some
data(A, B, C and D) and a pointer which stores the location of the next node.
You must be wondering why we need to store the location of the next node.
Well, because the memory locations allocated to these nodes are not contiguous
hence each node should know where the next node is stored.
As the node is a combination of multiple information, hence we will be defining a
class for Node which will have a variable to store data and another variable to store
the pointer. In C language, we create a structure using the struct keyword.
class Node
{
public:
// our linked list will only hold int data
int data;
//pointer to the next node
node* next;

// default constructor
Node()
{
data = 0;
next = NULL;
}

// parameterised constructor
Node(int x)
{

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 39


C++ Paper Solution: 2019

data = x;
next = NULL;
}
}
We can also make the Node class properties data and next as private, in that case
we will need to add the getter and setter methods to access them. You can add the
getter and setter functions to the Node class like this:

class Node
{
// our linked list will only hold int data
int data;
//pointer to the next node
node* next;

// default constructor same as above

// parameterised constructor same as above

/* getters and setters */


// get the value of data
int getData()
{
return data;
}

// to set the value for data


void setData(int x)
{
this.data = x;
}
// get the value of next pointer
node* getNext()
{
return next;
}
// to set the value for pointer
void setNext(node *n)
{
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 40
C++ Paper Solution: 2019

this.next = n;
}
}
The Node class basically creates a node for the data to be included into the Linked
List. Once the object for the class Node is created, we use various functions to fit in
that node into the Linked List.

Linked List class


As we are following the complete OOPS methodology, hence we will create a
separate class for Linked List, which will have all the methods like insertion,
search, deletion etc. Also, the linked list class will have a pointer called head to
store the location of the first node which will be added to the linked list.
class LinkedList
{
public:
node *head;
//declaring the functions

//function to add Node at front


int addAtFront(node *n);
//function to check whether Linked list is empty
int isEmpty();
//function to add Node at the End of list
int addAtEnd(node *n);
//function to search a value
node* search(int k);
//function to delete any Node
node* deleteNode(int x);

LinkedList()
{
head = NULL;
}
}
Insertion at the Beginning
Steps to insert a Node at beginning :
1. The first Node is the Head for any Linked List.
2. When a new Linked List is instantiated, it just has the Head, which is Null.
3. Else, the Head holds the pointer to the first Node of the List.
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 41
C++ Paper Solution: 2019

4. When we want to add any Node at the front, we must make the head point to
it.
5. And the Next pointer of the newly added Node, must point to the previous
Head, whether it be NULL(in case of new List) or the pointer to the first
Node of the List.
6. The previous Head Node is now the second Node of Linked List, because the
new Node is added at the front.

int LinkedList :: addAtFront(node *n) {


int i = 0;
//making the next of the new Node point to Head
n->next = head;
//making the new Node as Head
head = n;
i++;
//returning the position where Node is added
return i;
}

Inserting at the End


Steps to insert a Node at the end :
1. If the Linked List is empty then we simply, add the new Node as the Head of
the Linked List.
2. If the Linked List is not empty then we find the last node, and make it' next
to the new Node, hence making the new node the last Node.

int LinkedList :: addAtEnd(node *n) {


//If list is empty
if(head == NULL) {
//making the new Node as Head
head = n;
//making the next pointe of the new Node as Null
n->next = NULL;
}
else {
//getting the last node
node *n2 = getLastNode();
n2->next = n;
}
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 42
C++ Paper Solution: 2019

node* LinkedList :: getLastNode() {


//creating a pointer pointing to Head
node* ptr = head;
//Iterating over the list till the node whose Next pointer points to null
//Return that node, because that will be the last node.
while(ptr->next!=NULL) {
//if Next is not Null, take the pointer one step forward
ptr = ptr->next;
}
return ptr;
}

Searching for an Element in the List


In searhing we do not have to do much, we just need to traverse like we did while
getting the last node, in this case we will also compare the data of the Node. If we
get the Node with the same data, we will return it, otherwise we will make our
pointer point the next Node, and so on.

node* LinkedList :: search(int x) {


node *ptr = head;
while(ptr != NULL && ptr->data != x) {
//until we reach the end or we find a Node with data x, we keep moving
ptr = ptr->next;
}
return ptr;
}

Deleting a Node from the List


Deleting a node can be done in many ways, like we first search the Node
with data which we want to delete and then we delete it. In our approach, we will
define a method which will take the data to be deleted as argument, will use the
search method to locate it and will then remove the Node from the List.
To remove any Node from the list, we need to do the following :
 If the Node to be deleted is the first node, then simply set the Next pointer of
the Head to point to the next element from the Node to be deleted.
 If the Node is in the middle somewhere, then find the Node before it, and
make the Node before it point to the Node next to it.
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 43
C++ Paper Solution: 2019

node* LinkedList :: deleteNode(int x) {


//searching the Node with data x
node *n = search(x);
node *ptr = head;
if(ptr == n) {
ptr->next = n->next;
return n;
}
else {
while(ptr->next != n) {
ptr = ptr->next;
}
ptr->next = n->next;
return n;
}
}
Checking whether the List is empty or not
We just need to check whether the Head of the List is NULL or not.

int LinkedList :: isEmpty() {


if(head == NULL) {
return 1;
}
else { return 0; }
}

Now you know a lot about how to handle List, how to traverse it, how to search an
element. You can yourself try to write new methods around the List.
If you are still figuring out, how to call all these methods, then below is how
your main() method will look like. As we have followed OOP standards, we will
create the objects of LinkedList class to initialize our List and then we will create
objects of Node class whenever we want to add any new node to the List.
int main() {
LinkedList L;
//We will ask value from user, read the value and add the value to our Node
int x;
cout << "Please enter an integer value : ";
cin >> x;
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 44
C++ Paper Solution: 2019

Node *n1;
//Creating a new node with data as x
n1 = new Node(x);
//Adding the node to the list
L.addAtFront(n1);
}
Similarly you can call any of the functions of the LinkedList class, add as many
Nodes you want to your List.

b) What do you mean by control flow statements? Explain any two with
example.
Ans: Statements
Statements are the instructions given to the computer to perform any kind of
action. Action may be in the form of data movement, decision making etc.
Statements form the smallest executable unit within a C++ program. Statements
are always terminated by semicolon.

Compound Statement
A compound statement is a grouping of statements in which each individual
statement ends with a semi-colon. The group of statements is called block.
Compound statements are enclosed between the pair of braces ({}.). The opening
brace ({) signifies the beginning and closing brace (}) signifies the end of the block.

Null Statement
Writing only a semicolon indicates a null statement. Thus ';' is a null or empty
statement. This is quite useful when the syntax of the language needs to specify a
statement but the logic of the program does not need any statement. This statement
is generally used in for and while looping statements.

Conditional Statements
Sometimes the program needs to be executed depending upon a particular
condition. C++ provides the following statements for implementing the selection
control structure.
 if statement
 if else statement
 nested if statement
 switch statement

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 45


C++ Paper Solution: 2019

if statement:
syntax of the if statement
if (condition)
{
statement(s);
}
From the flowchart it is clear that if the if condition is true, statement is executed;
otherwise it is skipped. The statement may either be a single or compound
statement.

if else statement:
syntax of the if - else statement
if (condition)
statement1;
else
statement2;
From the above flowchart it is clear that the given condition is evaluated first. If the
condition is true, statement1 is executed. If the condition is false, statement2 is
executed. It should be kept in mind that statement and statement2 can be single or
compound statement.

Nested if statement
The if block may be nested in another if or else block. This is called nesting of if or
else block.
syntax of the nested if statement
if(condition 1)
{
if(condition 2)
{
statement(s);
}

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 46


C++ Paper Solution: 2019

if(condition 1)
statement 1;
else if (condition 2)
statement2;
else
statement3;

Example:
if(percentage>=60)
cout<<"Ist division";
else if(percentage>=50)
cout<<"IInd division";
else if(percentage>=40)
cout<<"IIIrd division";
else
cout<<"Fail" ;

switch statement:
The if and if-else statements permit two way branching whereas switch statement
permits multiple branching. The syntax of switch statement is:
switch (var / expression)
{
case constant1 : statement 1;
break;
case constant2 : statement2;
break;
.
.
default: statement3;
break;
}
The execution of switch statement begins with the evaluation of expression. If the
value of expression matches with the constant then the statements following this
statement execute sequentially till it executes break. The break statement transfers
control to the end of the switch statement. If the value of expression does not match
with any constant, the statement with default is executed.
Some important points about switch statement-
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 47
C++ Paper Solution: 2019

The expression of switch statement must be of type integer or character type.


-The default case need not to be used at last case. It can be placed at any place.
-The case values need not to be in specific order.

Looping statement
It is also called a Repetitive control structure. Sometimes we require a set of
statements to be executed a number of times by changing the value of one or more
variables each time to obtain a different result. This type of program execution is
called looping. C++ provides the following construct
1. while loop
2. do-while loop
3. for loop

1. While loop:
Syntax of while loop
while(condition)
{
statement(s);
}
The flow diagram indicates that a condition is first evaluated. If the condition is
true, the loop body is executed and the condition is re-evaluated. Hence, the loop
body is executed repeatedly as long as the condition remains true. As soon as the
condition becomes false, it comes out of the loop and goes to the statement next to
the ‗while‘ loop.

2. do-while loop:
Syntax of do-while loop
do
{
statements;
} while (condition);
Note : That the loop body is always executed at least once. One important
difference between the while loop and the do-while loop the relative ordering of the
conditional test and loop body execution. In the while loop, the loop repetition test is
performed before each execution the loop body; the loop body is not executed at all if
the initial test fail. In the do-while loop, the loop termination test is Performed after
each execution of the loop body. hence, the loop body is always executed least once.

3. for loop:
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 48
C++ Paper Solution: 2019

It is a count controlled loop in the sense that the program knows in advance how
many times the loop is to be executed.

syntax of for loop :


for (initialization; decision; increment/decrement)
{
statement(s);
}
The flow diagram indicates that in for loop three operations take place:
 Initialization of loop control variable
 Testing of loop control variable
 Update the loop control variable either by incrementing or
decrementing.
Operation (i) is used to initialize the value. On the other hand, operation (ii) is used
to test whether the condition is true or false. If the condition is true, the program
executes the body of the loop and then the value of loop control variable is updated.
Again it checks the condition and so on. If the condition is false, it gets out of the
loop.
Jump Statements
The jump statements unconditionally transfer program control within a function.
1. goto statement
2. break statement
3. continue statement
4. exit

1. The goto statement


goto allows to make jump to another point in the program.goto pqr;
pqr:pqr is known as label. It is a user defined identifier. After the execution of goto
statement, the control transfers to the line after label pqr.

2. The break statement


The break statement, when executed in a switch structure, provides an immediate
exit from the switch structure. Similarly, you can use the break statement in any of
the loop. When the break statement executes in a loop, it immediately exits from
the loop.

3. The continue statement


The continue statement is used in loops and causes a program to skip the rest of the
body of the loop.
PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 49
C++ Paper Solution: 2019

while (condition)
{
Statement 1;
If (condition)
continue;
statement;
}
The continue statement skips rest of the loop body and starts a new iteration.

4. The exit ( ) function


The execution of a program can be stopped at any point with exit ( ) and a status
code can be informed to the calling program. The general format is
exit (code) ;
where code is an integer value. The code has a value 0 for correct execution. The
value of the code varies depending upon the operating system.

PREPARED BY: SUMIT PUROHIT, ASST PROFESSOR, AISHWARYA COLLEGE Page 50

You might also like