BCS-031 ASSIGNMENT SOLUTION (2018-19)

If you have any queries please leave a message here
Your Message
×


In this ASSIGNMENT all the below PROGRAMMINGS are written and run in Turbo C++ 3.0

We have removed clrscr( ) and getch( ) functions from each programming because of different version of C++ compiler.




Question 1 :

a) Write advantages of Object Oriented Programming. Also differentiate between Object Oriented Programming approach and Structured Programming Approach.

Answer : -

Advantage of Object Oriented Programming System (OOPs) -


Differentiate between Object Oriented Programming approach and Structured Programming approach -




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

Answer : -

Data Types available in C++ -

The lists of modifiers used in C++ are -


Character Data Types -

Data Type
Size
Range
char1 byte-128 to 127 or 0 to 255
signed char1 byte-128 to 127
unsigned char1 byte0 to 255
wchar_t2 or 4 bytes1 wide character


Integer Data Types -

Data Type
Size
Range
int2 bytes-32768 to 32767
signed int2 bytes-32768 to 32767
unsigned int2 bytes0 to 65535
short2 bytes-32768 to 32767
signed short2 bytes-32768 to 32767
unsigned short2 bytes0 to 65535
long4 bytes-2147483648 to 2147483647
signed long4 bytes-2147483648 to 2147483647
unsigned long4 bytes0 to 4294967295


Floating-point Data Types -

Data Type
Size
Range
float4 bytes+/- 3.4e +/- 38 (7 digits)
double8 bytes+/- 1.7e +/- 308 (15 digits)
long double10 bytes+/- 3.4e +/- 4932 (18 digits)




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

Answer : - Decision making statements in programming languages decides the direction of flow of program execution.

if statement

if-statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.

Syntax :
if(condition)
{
// Statements
}

Here, condition after evaluation will be either true or false. If the value is true then it will execute the block of statements below it otherwise not.

If we do not provide the curly braces ‘{‘ and ‘}’ after if(condition) then by default if-statement will consider the first immediately below statement to be inside its block.

An if-statement can be followed by an optional else statement, which executes when the boolean expression is false.

Syntax :
if(condition)
{
// Statements
}
else
{
// Statements
}

Example :

#include<iostream.h>
class if_statement
{
public:
void OddEvenCheck(int n)
{
if(n % 2 == 0)
cout << "Even Number";
else
cout << "Odd Number";
}
};

void main()
{
int number;
cout << "Enter the number : ";
cin >> number;
if_statement ob1;
ob1.OddEvenCheck(number);
}


for statement

A loop is used for executing a block of statements repeatedly until a particular condition is satisfied.

for loop working process

Syntax :
for(initialization; condition; increment/decrement)
{
// Statement(s);
}

Example :

// Find sum of 1+3+5+…. up to n terms
#include<iostream.h>
class series
{
public:
void calculation(int n)
{
int i, a=1, sum=0;
for(i=1;i<=n;i++)
{
sum=sum+a;
a=a+2;
}
cout << "\n Answer = " << sum;
}
};

void main()
{
int num;
cout << "\n Enter the value of n : ";
cin >> num;
series ob1;
ob1.calculation(num);
}


switch statement

Switch case statements are a substitute for long if statements that compare a variable to several integral values

Syntax :
switch(choice)
{
case 1:
/* code to be executed if choice = 1; */
break;
case 2:
/* code to be executed if choice = 2; */
break;
default:
/* code to be executed if choice doesn't match any cases */
}

Important points about Switch Case statements -

Example :

#include<iostream.h>
class switch_statement
{
public:
void SwitchCase(int n)
{
switch(n)
{
case 1:
cout << "Choice is 1";
break;
case 2:
cout << "Choice is 2";
break;
case 3:
cout << "Choice is 3";
break;
default:
cout << "Choice other than 1, 2 and 3";
}
}
};

void main()
{
int choice;
cout << "Enter your choice : ";
cin >> choice;
switch_statement ob1;
ob1.SwitchCase(choice);
}




Question 2 :

a) What is class? What are different access specifiers in C++? Differentiate between public and protected class.

Answer : - A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical.

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 - 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 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.




b) Define the class Saving_Account with all the basic attributes of a saving bank account. Define the default constructor, parameterised constructor, member functions deposit(int) for depositing money in account and display_balance() for displaying the balance of account. Use appropriate access control specifiers in this program.

Answer : -

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

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

void main()
{
Saving_Account ob1;
Saving_Account ob2(10000);
ob1.deposit(8000);
ob2.deposit(5000);
ob1.display_balance();
ob2.display_balance();
}

Output

Balance = 8000

Balance = 15000




c) Explain the following in detail, in context of C++ programming.

Answer : -

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 -

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;
ob1->show();
}


Friend Function

A friend function of a class is defined outside that class scope but it has the right to access all private and protected members of the class.

By using the keyword friend compiler knows the given function is a friend function.

For accessing the data, the declaration of a friend function should be done inside the body of a class starting with the keyword friend.

Characteristics of a Friend function -

Example -

#include<iostream.h>
class Circle
{
private:
double area;

public:
void AreaCalculation(double radius)
{
area=3.14*radius*radius;
}
friend void print(Circle c);
};

inline void print(Circle c)
{
cout << "Area = " << c.area;
}

void main()
{
Circle ob1;
ob1.AreaCalculation(3.5);
print(ob1);
}


Operator Overloading

Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special meaning to the user-defined data type. Operator overloading is used to overload or redefines most of the operators available in C++. It is used to perform the operation on the user-defined data type.

The advantage of Operators overloading is to perform different operations on the same operand.

Example -

#include<iostream.h>
class Increment
{
private:
int count;
public:
Increment(int n)
{
count=n;
}
void operator ++()
{
count=count+2;
}
void Print()
{
cout << "Current Value = " << count;
}
};

void main()
{
Increment ob1(4);
++ob1;
ob1.Print();
}

Output

Current Value = 6




Question 3 :

a) What is inheritance? What are different types of inheritance? Explain order of constructor calling in multilevel inheritance with the help of a program.

Answer : - 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 -


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 add two complex numbers.

Answer : -

#include<iostream.h>
class ComplexNumber
{
private:
int real, imaginary;

public:
ComplexNumber(int r, int i)
{
real = r;
imaginary = i;
}
void operator +(ComplexNumber c)
{
int x = real + c.real;
int y = imaginary + c.imaginary;
cout << "Answer = " << x << " + " << y << "i";
}
};

void main()
{
int a, b, c, d;
cout << "Enter real and imaginary parts of first complex number : ";
cin >> a >> b;
cout << "Enter real and imaginary parts of second complex number : ";
cin >> c >> d;
ComplexNumber ob1(a,b), ob2(c,d);
ob1 + ob2;
}

Output

Enter real and imaginary parts of first complex number : 4 3

Enter real and imaginary parts of second complex number : 2 5

Answer = 6 + 8i




c) Explain use of static data member with the help of an example.

Answer : - When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member.

A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present. We can't put it in the class definition but it can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to.

Example

#include<iostream.h>
class A
{
public:
static int ObjectCount;
A(double length, double breadth)
{
cout << "Area = " << (length * breadth) << endl;
ObjectCount++;
}
};
int A::ObjectCount=0;

void main()
{
A ob1(4.5,2.5);
A ob2(3,6);
cout << "Total Objects = " << A::ObjectCount;
}

Output

Area = 11.25

Area = 18

Total Objects = 2




Question 4 :

a) Explain concept of function overriding with the help of an example.

Answer : - Function overriding is a feature that allows us to have a same function in child class which is already present in the parent class. A child class inherits the data members and member functions of parent class, but when you want to override a functionality in the child class then you can use function overriding.

Example

#include<iostream.h>
class Base
{
public:
void show()
{
cout << "Function of Base Class" << endl;
}
};
class Derived : public Base
{
public:
void show()
{
cout << "Function of Derived Class" << endl;
}
};
void main()
{
Derived ob1;
ob1.show();
ob1.Base::show();
}

Output

Function of Derived Class

Function of Base Class




b) Explain the following functions for manipulating file pointers, with the help of example program :

Answer : - The class istream and ostream each have a member function that allows you to change the file position marker (where in a file the data is to be written to and read form). In istream it's called seekg() and in ostream it's called seekp(). The function seekg() is associated with the file's "get or read" pointer, and the function seekp() with the file's "put or write" pointer. The declaration of this two functions are as follows :

// Class istream
istream& seekg(streampos);
istream& seekg(streamoff, ios::seek_dir);

// Class ostream
ostream& seekp(streampos);
ostream& seekp(streamoff, ios::seek_dir);

Where streampos and streamoff represent long integers, and seek_dir is a public enumerated type defined as follows :

enum seek_dir { beg, cur, end };

Note that each function has been overloaded. If the 1-argument form of the function is used, then the argument is the offset from the beginning of the file. If the 2-argument form is used, then the first argument is the offset number of bytes (positive or negative) from the absolute seek_dir position. For example, a call to seekg() with a single argument of 0L causes the file to rewind and data to be read starting with the first record. A call with the first argument of 0L and the second of ios::end places the file position marker on the end-of-file byte.

#include<iostream.h>
#include<fstream.h>
#define MAX 256
void main()
{
fstream in_out("TEMP.TXT", ios::in | ios::out);
if(!in_out)
{
cerr << "\n File open failed !";
}
char buffer[MAX];
/* Write into the file */
cout << "Enter the content : ";
while(!cin.getline(buffer, MAX).eof())
{
in_out << buffer << endl;
}
/* Return to the start of the file */
in_out.seekg(0L);
/* Read and print the file content */
while(!in_out.getline(buffer, MAX).eof())
{
cout << buffer << endl;
}
}

Output

Enter the content : C++ programming
Assignment BCS-031 Solution

C++ programming
Assignment BCS-031 Solution




c) What is an exception? Explain advantages of exception handling. Write a program in C++ to add two matrices with provision of exceptions handling.

Answer : - Exceptions are run-time anomalies or abnormal conditions that a program encounters during its execution. C++ provides following specialized keywords for this purpose.

try - Represents a block of code that can throw an exception.

catch - Represents a block of code that is executed when a particular exception is thrown.

throw - Used to throw an exception. Also used to list the exceptions that a function throws, but doesn’t handle itself.


Advantages of Exception Handling

Separation of Error Handling code from Normal Code - In traditional error handling codes, there are always if else 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.

Functions/Methods can handle any exceptions they choose - A function can throw many exceptions, but may choose to handle some of them. The other exceptions which are thrown, but not caught can be handled by caller. If the caller chooses not to catch them, then the exceptions are handled by caller of the caller.

In C++, a function can specify the exceptions that it throws using the throw keyword. The caller of this function must handle the exception in some way (either by specifying it again or catching it)

Grouping of Error Types - In C++, both basic types and objects can be thrown as exception. We can create a hierarchy of exception objects, group exceptions in namespaces or classes, categorize them according to types.

#include<iostream.h>
void main()
{
int i, j, k, n, a[5][5], b[5][5], c[5][5];
cout << "\n Enter the number of row/column present in the matrix : ";
cin >> n;
// Input Matrix A
cout << "\n Enter the element of matrix A";
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cout << "\n Enter the value of A[" << i << "][" << j <<"] : ";
cin >> a[i][j];
}
}
// Input Matrix B
cout << "\n Enter the element of matrix B";
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cout << "\n Enter the value of B[" << i << "][" << j <<"] : ";
cin >> b[i][j];
// Matrix C initialization
c[i][j] = 0;
}
}
// try block
try
{
// Add matrix A and B
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
}
// catch block
catch(char* message)
{
cerr << message;
}
// Print the matrix C
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cout <<"\t" << c[i][j];
}
cout << endl;
}
}

Output

Enter the number of row/column present in the matrix : 2

Enter the Element of First Matrix
Enter the value of A[0][0] : 5

Enter the value of A[0][1] : 8

Enter the value of A[1][0] : 3

Enter the value of A[1][1] : 4

Enter the Element of Second Matrix
Enter the value of B[0][0] : 7

Enter the value of B[0][1] : 6

Enter the value of B[1][0] : 7

Enter the value of B[1][1] : 9

1214
1013




Question 5 :

a) Explain use of following functions with the help of example code :

Answer : -

I. get( ) - istream::get

int get();
Extracts a character from the stream and returns its value.

istream& get (char& c );
Extracts a character from the stream and stores it in c.

istream& get (char* s, streamsize n );
istream& get (char* s, streamsize n, char delim );

Extracts characters from the stream and stores them into successive locations in the array pointed by s. Characters are extracted until either (n - 1) characters have been extracted, the delimiter (parameter delim or '\n' if not specified) is found, or if the end of file or any error occurs in the input sequence.

istream& get (streambuf* sb);
istream& get (streambuf* sb, char delim );

Extracts characters from the stream and inserts them in stream buffer sb. Characters are extacted until either the delimiter (parameter delim or '\n' if not speciffied) is found, or if the end of file or any error occurs in the input or output sequences.

Example

#include<iostream.h>
#include<fstream.h>
void main ()
{
char c, str[256];
ifstream file;
cout << "Enter the file name : ";
cin.get(str,256);
file.open(str);
while (file.good())
{
// get character from file
c = file.get();
cout << c;
}
file.close();
}


III. peek( ) - istream::peek

int peek ( );
Reads and returns the next character without extracting it from the stream.
Returns EOF if stream is at the end of file and in any case where member good( ) (ios::good) would return false.

Example

#include<iostream.h>
void main ()
{
int n;
char c, str[256];
cout << "Enter a number or a word : ";
c=cin.peek();
if ( (c >= '0') && (c <= '9') )
{
cin >> n;
cout << "You have entered number - " << n << endl;
}
else
{
cin >> str;
cout << " You have entered word - " << str << endl;
}
}

Output

Enter a number or a word : 1024

You have entered number - 1024


IV. ignore( ) - istream::ignore

istream& ignore ( streamsize n = 1, int delim = EOF );
Extracts characters from input stream and discards them.
Extraction ends when n characters have been discarded or when delim is found, whichever comes first. In this last case delim is also extracted.

Example

#include<iostream.h>
void main ()
{
char first, last;
cout << "Enter your full name : ";
first=cin.get();
cin.ignore(256,' ');
last=cin.get();
cout << "Your initials are - " << first << last;
}

Output

Enter your full name : Amit Das

Your initials are - AD




b) What is template? Write appropriate statements to create a template class for Stack Data Structure in C++.

Answer : - Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.

There are three kinds of templates: function templates, class templates and variable templates.

#include<iostream.h>
/* Define default capacity of stack */
#define SIZE 10
/* Class for stack */
template <class T>
class stack
{
private:
T *array;
int top;
int capacity;
public:
stack(int size = SIZE);// constructor
void push(T);
T pop();
};

/* Constructor to initialize stack */
template <class T>
stack<T>::stack(int size)
{
array = new T[size];
top = -1;
capacity = size;
}

/* Function to insert an element into the stack */
template <class T>
void stack<T>::push(T value)
{
if (top == (capacity-1))
cout << "Stack Overflow" << endl;
else
{
cout << "Inserting " << value << endl;
array[++top] = value;
}
}

/* Function to pop top element from the stack */
template <class T>
T stack<T>::pop()
{
/* check for stack underflow */
if (top == -1)
{
cout << "Stack UnderFlow" << endl;
return 0;
}
else
{
cout << "Removing " << array[top] << endl;
/* Decrease stack size by 1 and (optionally) return the popped element */
return array[top--];
}
}

// main function
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
Removing 30




Write C++ program to copy the content from one file into another file.

Answer : -

#include<iostream.h>
#include<fstream.h>
#define MAX 256
void main()
{
ifstream file1("Source.txt");
if(!file1)
{
cerr << "\n Source file open failed !";
}
ofstream file2("TEMP.TXT");
if(!file2)
{
cerr << "\n Destination file open failed !";
}
char buffer[MAX];
while(!file1.getline(buffer, MAX).eof())
{
file2 << buffer << endl;
}
}



ABOUT US

QuestionSolves.com is an educational website that helps worldwide students in solving computer education related queries.

Also, different software like Visual Studio, SQL Server, Oracle etc. are available to download in different versions.

Moreover, QuestionSolves.com provides solutions to your questions and assignments also.


MORE TOPIC


Windows Command

UNIX Command

IGNOU Assignment Solution

IGNOU Question Paper Solution

Solutions of Different Questions


WHAT WE DO


Website Devlopment

Training

Home Learning

Provide BCA, MCA Projects

Provide Assignment & Question Paper Solution


CONTACT US


Follow Us