C++ Paper Solution 2019
C++ Paper Solution 2019
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.
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.
// 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
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.
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
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;
};
//main function
int main()
{
Child obj1;
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
};
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:
Syntax:
class subclass_name : access_mode base_class
{
//body of subclass
};
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
};
// 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
.
Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2,
....
{
//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;
}
};
};
// 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
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;
}
};
// 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;
}
};
};
};
// 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
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
//base class
class Fare
{
public:
Fare()
{
cout<<"Fare of Vehicle\n";
}
};
};
};
// 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
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.
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.
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.
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.
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.
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.
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.
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.
#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
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.
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
Below we have a simple C++ program implementing stack data structure while
following the object oriented programming concepts.
class Stack
{
int top;
public:
// 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.
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 −
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.
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;
}
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()
{
// 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);
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
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];
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.
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;
}
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)
{
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;
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.
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.
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
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);
}
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
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.
while (condition)
{
Statement 1;
If (condition)
continue;
statement;
}
The continue statement skips rest of the loop body and starts a new iteration.