BCS 031 Solved Assignment
BCS 031 Solved Assignment
(a) What is Object Oriented Programming (OOP) approach? Explain advantages of OOP.
ans- OOP stands for Object-Oriented Programming. As you can guess from it’s name it breaks
the program on the basis of the objects in it. It mainly works on Class, Object, Polymorphism,
Abstraction, Encapsulation and Inheritance. Its aim is to bind together the data and functions to
operate on them.
Some of the well-known object-oriented languages are Objective C, Perl, Javascript, Python,
Modula, Ada, Simula, C++, Smalltalk and some Common Lisp Object Standard. Here we are
discussing its benefits on C++.
Benefits of OOP
We can build the programs from standard working modules that communicate with one
another, rather than having to start writing the code from scratch which leads to saving of
development time and higher productivity,
OOP language allows to break the program into the bit-sized problems that can be solved easily
(one object at a time).
The new technology promises greater programmer productivity, better quality of software and
lesser maintenance cost.
1
The principle of data hiding helps the programmer to build secure programs which cannot be
invaded by the code in other parts of the program.
By using inheritance, we can eliminate redundant code and extend the use of existing classes.
Message passing techniques is used for communication between objects which makes the
interface descriptions with external systems much simpler.
While it is possible to incorporate all these features in an OOP, their importance depends upon
the type of project and preference of the programmer. These technology is still developing and
current products may be superseded quickly.
Disadvantages of OOP
The length of the programmes developed using OOP language is much larger than the
procedural approach. Since the programme becomes larger in size, it requires more time to be
executed that leads to slower execution of the programme.
We can not apply OOP everywhere as it is not a universal language. It is applied only when it is
required. It is not suitable for all types of problems.
Programmers need to have brilliant designing skill and programming skill along withproper
planning because using OOP is little bit tricky.
OOPs take time to get used to it. The thought process involved in object-oriented programming
may not be natural for some people.
Everything is treated as object in OOP so before applying it we need to have excellent thinking
in terms of objects.
ans- An operator is a symbol that tells the compiler to perform specific mathematical or
logical manipulations. C++ is rich in built-in operators and provide the following types of
operators −
Arithmetic Operators
2
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
This chapter will examine the arithmetic, relational, logical, bitwise, assignment and
other operators one by one.
Arithmetic Operators
Show Examples
3
Relational Operators
Show Examples
== Checks if the values of two operands are equal or not, if yes then condition
becomes true. (A == B) is not true.
!= Checks if the values of two operands are equal or not, if values are not equal
then condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand, if
yes then condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes
then condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right
operand, if yes then condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right
operand, if yes then condition becomes true. (A <= B) is true.
Logical Operators
Show Examples
4
Operator Description Example
&& Called Logical AND operator. If both the operands are non-zero, then condition
becomes true. (A && B) is false.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a
condition is true, then Logical NOT operator will make false. !(A && B) is true.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &,
|, and ^ are as follows −
Assume if A = 60; and B = 13; now in binary format they will be as follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
A = 0011 1100
B = 0000 1101
5
A|B = 0011 1101
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table.
Assume variable A holds 60 and variable B holds 13, then −
Show Examples
& Binary AND Operator copies a bit to the result if it exists in both operands.
(A & B) will give 12 which is 0000 1100
^ Binary XOR Operator copies the bit if it is set in one operand but not both.
(A ^ B) will give 49 which is 0011 0001
~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.
(~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed
binary number.
<< Binary Left Shift Operator. The left operands value is moved left by the number
of bits specified by the right operand. A << 2 will give 240 which is 1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by the
number of bits specified by the right operand. A >> 2 will give 15 which is 0000
6
1111
Assignment Operators
Show Examples
= Simple assignment operator, Assigns values from right side operands to left side
operand. C = A + B will assign value of A + B into C
+= Add AND assignment operator, It adds right operand to the left operand and
assign the result to left operand. C += A is equivalent to C = C + A
-= Subtract AND assignment operator, It subtracts right operand from the left
operand and assign the result to left operand. C -= A is equivalent to C = C - A
*= Multiply AND assignment operator, It multiplies right operand with the left
operand and assign the result to left operand. C *= A is equivalent to C = C * A
/= Divide AND assignment operator, It divides left operand with the right operand
and assign the result to left operand. C /= A is equivalent to C = C / A
%= Modulus AND assignment operator, It takes modulus using two operands and
assign the result to left operand. C %= A is equivalent to C = C % A
Misc Operators
The following table lists some other operators that C++ supports.
7
Sr.No Operator & Description
sizeof
sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is integer,
and will return 4.
Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X otherwise returns
value of Y.
Member operators are used to reference individual members of classes, structures, and
8
unions.
Cast
Casting operators convert one data type to another. For example, int(2.2000) would
return 2.
&
Pointer operator & returns the address of a variable. For example &a; will give actual
address of the variable.
Pointer operator * is pointer to a variable. For example *var; will pointer to a variable
var.
9
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom. Within an expression, higher precedence operators
will be evaluated first.
Show Examples
(4 Marks)
11
while(condition)
statement(s)
while loop checks whether the condition written in ( ) is true or not. If the
condition is true, the statements written in the body of the while loop i.e.,
inside the braces { } are executed. Then again the condition is checked, and
if found true, again the statements in the body of the while loop are
executed. This process continues until the condition becomes false.
int main(){
int n = 1;
n++;
return 0;
12
}
Output
while(n <= 10) - checks the condition 'n <= 10'. Since the value of n is
1 which is less than 10, the statements within the braces { } are
executed.
The value of 'n' i.e. 1 is printed and n++ increases the value of 'n' by 1.
So, now the value of 'n' becomes 2.
Now, again the condition is checked. This time also 'n <= 10' is true
because the value of 'n' is 2. So, again the value of 'n' i.e., 2 gets printed
and the value of 'n' will be increased to 3.
When the value of 'n' becomes 10, again the condition 'n <= 10' is true
and 10 gets printed for the tenth time. Now, n++ increases the value to
'n' to 11.This time, the condition 'n <= 10' becomes false and the
program terminates.
for loop
13
Let's go to our first example in which we printed first 10 natural
numbers using while loop. We can also do this with for loop.
statement(s)
#include <iostream>
int main(){
int n;
return 0;
Output
14
n=1 - This step is used to initialize a variable and is executed first and
only once. Here, 'n' is assigned a value 1.
n++ - This is executed after the code in the body of the for loop has
been executed. In this example, the value of 'n' increases by 1 every
time the code in the body of for loop executes. There can be any
expression here which you want to run after every loop.
Once the codes in the body of for loop are executed, step n++ is
executed which increases the value of 'n' by 1. So now the value of 'n' is
2.
15
Again the condition 'n<=10' is checked which is true because the value
of 'n' is 2. Again codes in the body of for loop are executed and 2 gets
printed and then the value of 'n' is again incremented.
When the value of 'n' becomes 10, the condition 'n <= 10' is true and
10 gets printed. Now, when n++ increases the value to 'n' to 11, the
condition 'n<=10' becomes false and the loop terminates.
Question 2:
(a) What is a class? Explain how a class is created in C++, with the
help of an example.
Instances of a class data type are known as objects and can contain
member variables, constants, member functions, and overloaded
operators defined by the programmer.For Example: Consider the Class
of Cars. There may be many cars with different names and brand but all
of them will share some common properties like all of them will have 4
wheels, Speed Limit, Mileage range etc. So here, Car is the class and
16
wheels, speed limits, mileage are their properties.
Syntax:
ClassName ObjectName;
EXAMPLES
// C++ program to demonstrate
// accessing of data members
#include <bits/stdc++.h>
using namespace std;
17
class Geeks
{
// Access specifier
public:
// Data Members
string geekname;
// Member Functions()
void printname()
{
cout << "Geekname is: " << geekname;
}
};
int main() {
18
obj1.printname();
return 0;
}
Output:
Declaring Objects: When a class is defined, only the specification for the
object is defined; no memory or storage is allocated. To use the data and
access functions defined in the class, you need to create objects.
The Research and analysis wing (R&AW), having 10 core members has
come in possession of sensitive confidential information regarding
national security. Now we can correlate these core members to data
members or member functions of a class which in turn can be
correlated to the R&A wing. These 10 members can directly access
confidential information from their wing (the class), but anyone apart
from these 10 members can’t access this information directly i.e.
outside functions other than those prevalent in the class itself can’t
access information that is not entitled to them, without having either
assigned privileges (such as those possessed by friend class and
19
inherited class as will be seen in this article ahead) or access to one of
these 10members who is allowed direct access to the confidential
information (similar to how private members of a class can be accessed
in the outside world through public member functions of the class that
have direct access to private members). This is what data hiding is in
practice.
Public
Private
Protected
Note: If we do not specify any access modifiers for the members inside
the class then by default the access modifier for the members will be
Private.
1. Public: All the class members declared under the public specifier will
be available to everyone. The data members and member functions
declared as public can be accessed by other classes and functions too.
The public members of a class can be accessed fromanywhere in the
program using the direct member access operator (.) with the object of
that class.
20
Example:
// access modifier
#include<iostream>
// class definition
class Circle
public:
double radius;
double compute_area()
return 3.14*radius*radius;
};
21
// main function
int main()
Circle obj;
obj.radius = 5.5;
return 0;
Output:
Use cases
#include <iostream>
class Bar {
private:
int a = 0;
public:
23
void show(Bar& x, Foo& y);
};
class Foo {
private:
int b = 6;
public:
};
24
void show(Bar& x, Foo& y) {
int main() {
Bar a;
Foo b;
show(a,b);
a.show(a,b);
function_name(oject_name);
Example: In this Example there is a class which has an integer
variable ‘a’ and a function ‘add’ which takes an object as
argument. The function is called by one object and takes
another as an argument. Inside the function, the integer value
of the argument object is added to that on which the ‘add’
26
function is called. In this method, we can pass objects as an
argument and alter them.
#include <bits/stdc++.h>
using namespace std;
a = a + E.a;
}
};
27
// Driver Code
int main()
{
// Create objects
Example E1, E2;
28
// Changed values after passing
// object as argument
cout << "New values \n";
cout << "Value of object 1: " << E1.a
return 0;
}
Output
Initial Values
Value of object 1: 50
29
Heterogeneous container class can hold mixed objects in memory
whereas when it is holding same objects, it is called as homogeneous
container class.
- Container class is one of the classes that were put into class libraries.
To handle objects that contain other objects, container classes are used.
A GUI class library contains a group of container classes.
1. std::map :
2. std::vector :
30
such as bunds checking through the at () member function, inserting or
removing elements, automatic memory management and throwing
exceptions.
std::string :
int arr1[20];
int arr2[10];
void g()
f(arr1,20);
f(arr2,20);
31
program.
ans-The capability of a class to derive properties and characteristics
from another class is called Inheritance. Inheritance is one of the most
important feature of Object Oriented Programming.
Sub Class: The class that inherits properties from another class is called
Sub class or Derived Class.
Consider a group of vehicles. You 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:
You 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:
32
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:
33
// C++ program to demonstrate implementation
// of Inheritance
#include <bits/stdc++.h>
using namespace std;
//Base class
class Parent
{
public:
int id_p;};
//main function
int main()
{
34
Child obj1;
return 0;
}
Output
Child id is 7
Parent id is 91
35
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:
Syntax:
36
//body of subclass
};3. Multilevel Inheritance: In this type of inheritance, a derived class is
created from another derived class.
C++ Multiple Inheritance Example
Here is a simple example illustrating the concept of C++ multiple
inheritance.
// multiple inheritance.cpp
#include
using namespace std;
class A
{
public:
int x;
void getx()
{
cout << "enter value of x: "; cin >> x;
}
};
class B
{
public:
int y;
void gety()
37
{
cout << "enter value of y: "; cin >> y;
}
};
class C : public A, public B //C is derived from class A and class B
{
public:
void sum()
{
cout << "Sum = " << x + y;
}
};
int main()
{
C obj1; //object of derived class C
obj1.getx();
obj1.gety();
obj1.sum();
return 0;
} //end of program
Output
38
enter value of x: 5
enter value of y: 4
Sum = 9
Explanation
In the above program, there are two base class A and B from which class
C is inherited. Therefore, derived class C inherits all the public members
of A and B and retains their visibility. Here, we have created the object
obj1 of derived class C.
Example:
public:
// Classes object of string
char s1[25], s2[25];
// Parameterized Constructor
AddString(char str1[], char str2[])
{
// Initialize the string to class object
strcpy(this->s1, str1);
strcpy(this->s2, str2); }
40
// Overload Operator+ to concat the string
void operator+()
{
cout << "\nConcatenation: " << strcat(s1, s2);
}
};
// Driver Code
int main()
{
// Declaring two strings
char str1[] = "arpit";
char str2[] = "gochar";
41
return 0;
}
output:
Concatenation: arpitgochar
Question 4:
(a) Explain the following in detail with the help of
examples, in context of C++ programming
(9 Marks)
i. Destructor
ii. Virtual Function
iii. Inline function
ans- Destructor is an instance member function which is
invoked automatically whenever an object is going to be
destroyed. Meaning, a destructor is the last function that is
going to be called before an object is destroyed.
Syntax:
~constructor-name();
42
Properties of Destructor:
43
Virtual Functions
Deleting a derived class object using a pointer of base class
type that has a non-virtual destructor results in undefined
behavior. To correct this situation, the base class should be
defined with a virtual destructor. For example, following
program results in undefined behavior.
class base {
public:
base()
{ cout<<"Constructing base \n"; }
44
~base()
{ cout<<"Destructing base \n"; }
};
int main(void)
{
derived *d = new derived();
base *b = d;
delete b;
getchar();
return 0;
}
output:
45
Constructing base
Constructing derived
Destructing base
iii. Inline function and classes:
When the program executes the function call instruction the CPU stores
the memory address of the instruction following the function call,
copies the arguments of the function on the stack and finally transfers
control to the specified function. The CPU then executes the function
code, stores the function return value in a predefined memory
location/register and returns control to the calling function. This can
become overhead if the execution time of function is less than the
switching time from the caller function to called function (callee). For
functions that are large and/or perform function to called function
(callee).. It is also possible to define the inline function inside the class.
In fact, all the functions defined inside the class are implicitly inline.
Thus, all the restrictions of inline functions are also applied here. If you
need to explicitly declare inline function in the class then just declare
the function inside the class and define it outside the class using inline
keyword.
For example:
class S
{
public:
inline int square(int s) // redundant use of inline
{ // this function is automatically inline
// function body
46
}
};
The above style is considered as a bad programming style. The best
programming style is to just write the prototype of function inside the
class and specify it as an inline in the function definition.
For example:
class S
{
public:
int square(int s); // declare the function
};
47
(b) What is template? Write appropriate statements to create a
template class for Stack data
Structure in C++.
#include<iostream.h>
48
#define SIZE 10
class stack
private:
T *array;
int top;
int capacity;
public:
void push(T);
T pop();
};
stack<T>::stack(int size)
49
array = new T[size];
top = -1;
capacity = size;
if (top == (capacity-1))
else
array[++top] = value;
50
template <class T>
T stack<T>::pop()
if (top == -1)
return 0;
else
return array[top--];
// main function
51
void main()
int retn;
stack<int> obj(2);
obj.push(10);
obj.push(20);
retn = obj.pop();
retn = obj.pop();
obj.push(30);
retn = obj.pop();
Output
Inserting 10
Inserting 20
Removing 20
Removing 10
Inserting 30
52
Removing 30
Question 5:
overflow as exception
53
conditions to handle errors. These conditions and the code to
handle errors get mixed up with the normal flow. This makes the
code less readable and maintainable. With try catch blocks, the
code for error handling becomes separate from the normal flow.
54
{
ex.Execute();
ctr++;
if (ctr % 50 == 0)
Execute();
ctr--;
55
// The example displays the following output:
56
// Call number 950 to the Execute method
//
overloading.
Now that we know what is parameter list lets see the rules of
overloading: we can have following functions in the same scope.
57
The easiest way to remember this rule is that the parameters
should qualify any one or more of the following conditions, they
should have different type, number or sequence of parameters.
For example:
All of the above three cases are valid case of overloading. We can
have any number of functions, just remember that the parameter
list should be different. For example:
58
int sum(int, int)
This is not allowed as the parameter list is same. Even though they
have different return types, its not valid.
#include <iostream>
public:
return num1+num2;
return num1+num2+num3;
59
};
int main(void) {
Addition obj;
cout<<obj.sum(20, 15)<<endl;
return 0;
Output:
35
191
(c) Explain use of any two I/O formatting flags in C++ with
example.
ans- C++ defines some format flags for standard input and output,
which can be manipulated with the flags(), setf(), and unsetf()
functions. For example,
width(): The width method is used to set the required field width.
60
The output will be displayed in the given width
fill(): The fill method is used to set a character to fill in the blank
space of a field
setf(): The setf method is used to set various flags for formatting
output
Working:
#include<bits/stdc++.h>
61
char c = 'A';
cout.width(5);
cout<<temp;
void IOS_precision()
62
{cout << "\n \n";
cout.setf(ios::fixed, ios::floatfield);
cout.precision(2);
cout<<3.1422;
void IOS_fill()
char ch = 'a';
63
// the white spaces in a value with a
cout.fill('*');
cout.width(10);
int i = 1;
cout.width(5);
cout<<i;
64
void IOS_setf()
int val1=100,val2=200;
cout.setf(ios::showpos);
cout<<val1<<" "<<val2;
void IOS_unsetf()
cout.setf(ios::showpos|ios::showpoint);
cout.unsetf(ios::showpos);
cout<<200.0;
65
}
// Driver Method
int main()
IOS_width();
IOS_precision;
IOS_fill();
IOS_setf();
IOS_unsetf();
return 0;
Output:
--------------------------Implementing ios::width
10
66
Implementing ios::fill
*********a
****1
Implementing ios::setf
+100 +200
Implementing ios::unsetf
200.000
67
68