You are on page 1of 25

Course Code : BCS-031

Course Title : Programming in C++

Last Date of Submission : 15th October, 2019 (For July, 2019 Session)

15th April, 2020 (For January, 2020 Session)

Question 1

(a) Write advantages of Object Oriented Programming.


Also differentiate between Object Oriented Programming
approach and Structured Programming Approach.

Ans:

Advantages Of Object Oriented Programming

• As OOP is closer to the real world phenomena,


hence, it is easier to map real world problems
onto a solution in OOP.

• The objects in OOP have the state and behaviour that is similar to the real world objects.

• It is more suitable for large projects.

• Abstraction techniques are used to hide the unnecessary details and focus is only on the
relevant part of the problem and solution.

• Object oriented systems are easier to upgrade/modify.

Differentiate between Object Oriented Programming approach and Structured Programming


Approach

• OOP is closer to the phenomena in real world due to the use of objects whereas
structured programming is a bit away from the natural way of thinking of human beings.

• Under structured programming, the focus of a program is on procedures or functions


and the data is considered separately whereas in OOP, data and functions (behaviour)
both are in collective focus.

www.ignousolvedassignment.co.in
• In OOP, the basic units of manipulation are the objects whereas in case of structured
programming, functions are the basic units of manipulation.

In OOP, data is hidden within the objects and its manipulation can be strictly controlled
whereas in structure programming the data in the form of variables is exposed to unintended
manipulation too.

(b) Explain different data types available in C++ programming.

Data Types in C++

C++ offers the programmer a rich assortment of built-in as well as user defined data types.
Following table lists down seven basic C++ data types –

Type Keyword
Boolean bool
Character char
Integer int
Floating point float
Double floating point double
Valueless void

Several of the basic types can be modified using one or more of these type modifiers −
signed, unsigned, short, long

(c) Explain the use of followings in C++ programming with an example program for each

(a) if

(b) for

(c) switch

Ans:

(a) if
If statement is used when execution of statement is depend on condition. Syntax of the if
statement

www.ignousolvedassignment.co.in
if (condition)
{
statement(s);
}

Example :

#include <iostream.h>
int main()
{
int number;
cout<<"Enter a number: ";
cin>>number;
if (number < 0)
{
number = - number;
}
cout<<"The absolute value of number is “ <<
number;
return 0;
}

(b) for loop

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.

www.ignousolvedassignment.co.in
Example :

#include<iostream.h>
int main()
{
for (int i = 1; i <= 10; i++)
{
Cout << i <<endl;
}
return 0;
}

(c) switch statement


The 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;
}

Question 2 :

(a) What is constructor? Define the class Account with all the basic attributes of a saving bank
account. Define the default constructor, parameterised constructor in Account class. Define
member functions display_balance(),for displaying the balance of account and
cash_withdrawal( ) to withdraw some amount from account. Use appropriate access control
specifiers in this program.

Ans :

www.ignousolvedassignment.co.in
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.
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).

#include<iostream.h>
class Account
{
private:
int balance;

public:
/* Default Constructor */
Account()
{
balance = 0;
}
/* Parameterised Constructor */
Account(int amount)
{
balance = amount;
}
void cash_withdrawal(int amount)
{
balance = balance - amount;
}
void display_balance()
{
cout << "Balance = " << balance << endl;
}
};

void main()

www.ignousolvedassignment.co.in
{
Account ob1;
Account ob2(10000);
ob2. cash_withdraw (5000);
ob1.display_balance();
ob2.display_balance();
}

Output

Balance = 0

Balance = 5000

(b) Explain the following in detail, in context of C++


programming.

i. Access Specifiers ii. Virtual Function iii. Abstract Class

i. Access Specifiers

Access modifiers or Access Specifiers in a class are used


to set the accessibility of the class members. That is, it
sets some restrictions on the class members not to get
directly accessed by the outside functions.

There are 3 types of access modifiers available in C++

 public
 private
 protected

public - All the class members declared under public will be available to everyone. The data
members and member functions declared public can be accessed by other classes too. The
public members of a class can be accessed from anywhere in the program using the direct
member access operator (.) with the object of that class.

private - The class members declared as private can be accessed only by the functions inside
the class. They are not allowed to be accessed directly by any object or function outside the

www.ignousolvedassignment.co.in
class. Only the member functions or the friend functions are allowed to access the private data
members of a class.

protected - Protected access modifier is similar to that of private access modifiers, the
difference is that the class member declared as Protected are inaccessible outside the class but
they can be accessed by any subclass(derived class) of that class.

ii.

Virtual Function

Consider the following simple program as an example of runtime polymorphism. The main thing
to note about the program is that the derived class’s function is called using a base class
pointer. The idea is that virtual functions are called according to the type of the object instance
pointed to or referenced, not according to the type of the pointer or reference.
In other words, virtual functions are resolved late, at runtime.
#include<iostream>
using namespace std;

class Base
{
public:
virtual void show() { cout<<" In Base \n"; }
};

class Derived: public Base


{
public:
void show() { cout<<"In Derived \n"; }
};

int main(void)
{
Base *bp = new Derived;
bp->show(); // RUN-TIME POLYMORPHISM
return 0;
}

www.ignousolvedassignment.co.in
iii. Abstract Class

Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract classes
are used to provide an Interface for its sub classes. Classes inheriting an Abstract Class must
provide definition to the pure virtual function, otherwise they will also become abstract class.

Characteristics of Abstract Class -

 Abstract class cannot be instantiated, but pointers and refrences of Abstract class type
can be created.
 Abstract class can have normal functions and variables along with a pure virtual
function.
 Classes inheriting an Abstract Class must implement all pure virtual functions, or else
they will become Abstract too.

Example -

#include<iostream.h>
class Base
{
public:
virtual void show() = 0;
};

class Derived : public Base


{
public:
virtual void show()
{
cout << "Derived Class";
}
};

void main()
{
Base *ob1;
Derived ob2;
ob1=&ob2;

www.ignousolvedassignment.co.in
ob1->show();
}

Q3.

(a) What is inheritance? Explain different types of inheritance supported by C++ with the help
of example programs.

Inheritance in C++ is a mechanism in which one object acquires all the properties and behaviors
of a parent object.

The idea behind inheritance in C++ is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.

Subclass is a class which inherits the other class. It is also called a derived class, extended class,
or child class.

Superclass is the class from where a subclass inherits the features. It is also called a base class
or a parent class.

Different types of Inheritance -

 Single Inheritance - A derived class with only one base class is called single inheritance.

 Multilevel Inheritance - A derived class with one base class and that base class is a
derived class of another is called multilevel inheritance.

www.ignousolvedassignment.co.in
 Multiple Inheritance - A derived class with multiple base class is called multiple
inheritance.

 Heirarchical Inheritance - Multiple derived classes with same base class is called
hierarchical inheritance.

www.ignousolvedassignment.co.in
 Hybrid Inheritance - Combination of multiple and hierarchical inheritance is called
hybrid inheritance.

 Multipath Inheritance - A derived class with two base classes and these two base
classes have one common base class is called multipath inheritance.

www.ignousolvedassignment.co.in
Constructor calling in Multilevel Inheritance -

#include<iostream.h>
class A
{
public:
A() { cout << "A's constructor called" << endl; }
};
class B : public A
{
public:
B() { cout << "B's constructor called" << endl; }
};
class C : public B
{
public:
C() { cout << "C's constructor called" << endl; }
};
void main()
{
C ob1;
}

Output

A's constructor called

B's constructor called

C's constructor called

(b) Write a C++ program to overload ‘+’ operator to find the sum of length of two given strings.
(Note: if S1 and S2 are two strings then S1+S2 should give the sum of lengths of S1 and S2).

#include<iostream>
using namespace std;
#include<string.h>

class String
{

www.ignousolvedassignment.co.in
char str[80];
public :
String(char s[])
{
strcpy(str,s);
}

void operator+(String s)
{
cout << "Total Length :"<< strlen(str)+strlen(s.str);
}
};

int main()
{
String s1("IGNOU");
String s2("University");
s1+s2;
return 0;
}

Q4.

(a) What is stream manipulator? Explain use of setw( ) and setprecision( ) as stream
manipulator. (4)

STREAM MANIPULATORS

 A stream manipulator is a symbol or function that is used by placing it on the


right side of the insertion operator << .
o A plain manipulator is just a symbol, like a variable:

cout << endl; // endl is a stream manipulator

o A parameterized stream manipulator looks like a function call -- it has one or


more parameters:

www.ignousolvedassignment.co.in
cout << setw(10);// setw() is a parameterized manipulator

o To use parameterized stream manipulators, you need to include


the <iomanip> library
o #include <iomanip>

 Many of the stream manipulators are just alternate ways of doing tasks
performed by member functions. A nice benefit is that cascading can be used,
intermixing manipulators and other output statements that use the insertion operator
 cout << setw(10) << "Hello" << endl;
 setprecision() is a parameterized stream manipulator that performs the same
task as the member function precision()
 cout.precision(2); // sets decimal precision to 2 significant digits
 cout << setprecision(2); // does the same thing!
 setw() is a parameterized stream manipulator that performs the same task as
the member function width()
 cout.width(10); // sets field width to 10 for next output
 cout << setw(10); // does the same thing!

(b) Write a C++ program to read the contents of a file and display it on console. (5)

#include<fstream>
#include<iostream>
using namespace std;

int main()
{
ifstream fin;
fin.open("out.txt");

char ch;

while(!fin.eof())
{
fin.get(ch);
cout << ch;
}

www.ignousolvedassignment.co.in
fin.close();
return 0;
}

(c) What is an exception? Explain advantages of exceptions handling .Write a program in C++ to
perform simple arithmetic operations with proper exceptions handling.

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.
#include <iostream>
using namespace std;

double division(int a, int b) {


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

int main () {

www.ignousolvedassignment.co.in
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;
}

Q5.

(a) What is template? Write appropriate statements to create a template class for Stack
data structure in C++.

Templates are powerful features of C++ which allows you to write generic programs. In simple
terms, you can create a single function or a class to work with different data types using
templates.

Templates are often used in larger codebase for the purpose of code reusability and flexibility
of the programs.

The concept of templates can be used in two different ways:

 Function Templates
 Class Templates

www.ignousolvedassignment.co.in
FUNCTION TEMPLATES

A function template works in a similar to a normal function, with one key difference.

A single function template can work with different data types at once but, a single normal
function can only work with one set of data types.

Normally, if you need to perform identical operations on two or more types of data, you use
function overloading to create two functions with the required function declaration.

However, a better approach would be to use function templates because you can perform the
same task writing less and maintainable code.

A function template starts with the keyword template followed by template parameter/s
inside < > which is followed by function declaration.

template <class T>


T someFunction(T arg)
{
... .. ...
}

In the above code, T is a template argument that accepts


different data types (int, float), and class is a keyword.

CLASS TEMPLATES

Like function templates, you can also create class


templates for generic class operations.

Sometimes, you need a class implementation that is


same for all classes, only the data types used are
different.

Normally, you would need to create a different class for each data type OR create different
member variables and functions within a single class.

This will unnecessarily bloat your code base and will be hard to maintain, as a change is one
class/function should be performed on all classes/functions.

www.ignousolvedassignment.co.in
However, class templates make it easy to reuse the same code for all data types.

Declaring a class template

template <class T>

class className

... .. ...

public:

T var;

T someOperation(T arg);

... .. ...

};

In the above declaration, T is the template argument which is a placeholder for the data type
used.
Inside the class body, a member variable var and a member function someOperation() are both
of type T.

C++ Program for to implement stack operation using template function.

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
template<class T>
class Stack
{
T s[10];
int top,n;
public:
Stack()

www.ignousolvedassignment.co.in
{
top=-1;
cout<<"\n\tEnter the Stack Size : ";
cin>>n;
}
void push(T elt)
{
if(top<n-1)
s[++top]=elt;
else
cout<<"\n\tstack is full.Can't insert "<<elt<<endl;
}
void pop()
{
if(top<0)
cout<<"\n\tstack is empty.\n";
else
cout<<"\n\tPoped elt : "<<s[top--];
}
void stk_operation();
};
template<class T>
void Stack<T> :: stk_operation()
{
int choice=1,i;
T elt;
while(choice>0 && choice<3)
{
cout<<"\n\n\t1.PUSH\t2.POP\tAny Key To Exit\n\tChoice : ";
cin>>choice;
switch(choice)
{
case 1 : //push
cout<<"\n\tEnter the Elt to push : ";
cin>>elt;

www.ignousolvedassignment.co.in
push(elt);
cout<<"\n\t\tstack content :\n\n\t";
for(i=0;i<=top;i++)
cout<<s[i]<<"\t";
break;
case 2 : //pop
pop();
cout<<"\n\t\tstack content :\n\n\t";
for(i=0;i<=top;i++)
cout<<s[i]<<"\t";
break;
}
}
}
void main()
{
clrscr();
cout<<"\n\t\tSTACK OPERATION USING TEMPLATE\n\n";
cout<<"\n\t INT\n";
Stack<int> stk1;
cout<<"\n\t FLOAT\n";
Stack<float> stk2;
int ch;
while(1)
{
cout<<"\n\t\t\tSTACK OPERATION \n\n";
cout<<"\t1.INT STACK\t2.FLOAT STK\tAny Key To Exit\n\tChoice : ";
cin>>ch;
switch(ch)
{
case 1 : //perform stk operation on int stk
stk1.stk_operation();
break;
case 2 : //float
stk2.stk_operation();

www.ignousolvedassignment.co.in
break;
default : exit(0);
}
}
}

(b) What is polymorphism? Explain different types of polymorphism with examples.

Polymorphism is a significant feature of Object Oriented Principles. The


word POLYMORPHISM came from two Greek words ‘POLY‘ and ‘MORPHS‘.
Here POLY means many and MORPHS means forms.

Polymorphism represents the ability of an object to assume different forms. And it enables the
programmers to create/write programs that are easier to understand and reuse.

Polymorphism provides flexibility to the programmer to write programs that uses single
method for different operations depending on the requirement.

In C++ we can define a single abstract class to represent


multiple concrete classes. So by accepting the abstract
class type a method can behave differently for different
inputs.

TYPES OF POLYMORPHISM

C++ supports two types of polymorphism that are,

 compile-time polymorphism and


 run-time polymorphism.

COMPILE-TIME POLYMORPHISM:

The type of polymorphism that is implemented when the compiler compiles a program is called
compile-time polymorphism. C++ supports compile-time polymorphism through method
overloading. This type of polymorphism is also called as static polymorphism or early binding.

Polymorphism occurs in method overloading because method overloading allows access to


different methods through the same interface.

www.ignousolvedassignment.co.in
In function overloading, two or more methods in a class can use the same name as long as their
parameter declarations are different.

When the compiler encounters a call to an overloaded method, it identifies the correct version
of the overloaded function to be executed by comparing the type and number of arguments.

RUN-TIME POLYMORPHISM:

The type of polymorphism that is implemented dynamically when a program being executed is
called run-time polymorphism. C++ supports run-time polymorphism by dynamically
dispatching methods at run time through method overriding.

For this type of polymorphism, method invocations are resolved at run time and not at the
compile time.

The run-time polymorphism is also called dynamic polymorphism or late binding.

(6) (c) Write C++ program to demonstrate implementation of friend function. Also explain
advantages of friend function.

FRIEND FUNCTION IN C++

If a function is defined as a friend function then, the


private and protected data of a class can be accessed using
the function.
The complier knows a given function is a friend function by
the use of the keyword friend.
For accessing the data, the declaration of a friend function
should be made inside the body of the class (can be
anywhere inside class either in private or public section) starting with keyword friend.

DECLARATION OF FRIEND FUNCTION IN C++

class class_name
{
... .. ...

www.ignousolvedassignment.co.in
friend return_type function_name(argument/s);
... .. ...
}

Now, you can define the friend function as a normal function to access the data of the class.
No friend keyword is used in the definition.

class className
{
... .. ...
friend return_type functionName(argument/s);
... .. ...
}

return_type functionName(argument/s)
{
... .. ...
// Private and protected data of className can be accessed from
// this function because it is a friend function of className.
... .. ...
}

EXAMPLE : WORKING OF FRIEND FUNCTION


1. /* C++ program to demonstrate the working of friend function.*/
2. #include <iostream>
3. using namespace std;
4.
5. class Distance
6. {
7. private:
8. int meter;
9. public:
10. Distance(): meter(0) { }
11. //friend function

www.ignousolvedassignment.co.in
12. friend int addFive(Distance);
13. };
14.
15. // friend function definition
16. int addFive(Distance d)
17. {
18. //accessing private data from non-member function
19. d.meter += 5;
20. return d.meter;
21. }
22.
23. int main()
24. {
25. Distance D;
26. cout<<"Distance: "<< addFive(D);
27. return 0;
28. }
Output

Distance: 5

Here, friend function addFive() is declared inside Distance class. So, the private data metercan
be accessed from this function.

Disclaimer/Note:

These are just the sample of the answers/solutions to some of the questions
given in the Assignments. These sample answers are submitted by students /
private tutors. These sample answers may be seen as the Guide/Help for the
reference to prepare the answers of the questions given the assignment. Student
should read and refer the official study material provided by the university.
http://www.ignousolvedassignment.co.in

www.ignousolvedassignment.co.in
www.ignousolvedassignment.co.in

DRM Software Review

You might also like