Sei sulla pagina 1di 81

BANGALORE INSTITUTE OF TECHNOLOGY

K.R.Road, V.V.Puram, Bengaluru-560004

Department of
Master of Computer Applications
C++ Programming Laboratory
Subject Code: 18MCA16
I Semester MCA
2018-2019
BANGALORE INSTITUTE OF TECHNOLOGY
K.R.Road, V.V.Puram, Bengaluru-560004

Department of
Master of Computer Applications

LAB CERTIFICATE
This is to certify that BHARATH CR has satisfactorily completed the
course on experiments in C++ PROGRAMMING LABORATORY as
prescribed by the VISHVESVARAYA TECHNOLOGICAL UNIVERSITY
for
I Semester MCA during the academic year 2018-2019.

USN No:1IH18MCA03

Prof. MADHU H K Prof.A G VISWANATH


(Asst. Professor, Dept. of MCA) (Asst. Professor, Dept. of MCA)
BIT, Bengaluru. BIT, Bengaluru.

Examiners
Prof. A M Shivaram
1. Assoc. Professor,
2. HOD, Dept. of MCA
BIT, Bengaluru.
Bangalore Institute of Technology
K.R. Road, V.V. Puram, Bangalore – 560004
Department of Master of Computer Application

Vision
To transform young graduates into skilled computer professionals to meet Industrial and societal
needs.
Mission
 To enhance the Teaching learning process to meet quality education in the field of Computer
applications
 To impart the knowledge in current technologies to meet the industrial needs
 To inculcate ethical values and leadership qualities for the betterment of society

PEO’s

 PEO1: To develop quality software with innovative ideas to meet the industrial requirements
 PEO2: To imbibe the current technologies and to adopt in computing profession as per the
changing needs
 PEO3: To progress in their career with leadership qualities and ethical values that enhances
self and societal growth

Program Outcome:

PO1 Apply knowledge of computing fundamentals, computing specialization,


mathematics and domain knowledge appropriate for conceptualization of
computing models as per the requirement

PO2 Identify, analyze systematize and solve computer application related


problems using the principles of mathematics, computing sciences and
relevant domain knowledge

PO3 Design, develop and evaluate software solution to solve complex problem
with societal and environment concern.
PO4 Conduct investigations of complex computing problems using research
based methods to provide valid conclusions.

PO5 Select, adapt and apply appropriate techniques, resources and modern
tools for complex computing activities .

PO6 Understand ethical responsibilities and cyber regulations to perform


professionally.

PO7 Involve in independent learning for continual development as computing


professionals

PO8 Apply and demonstrate the computing and management principle to


manage projects in multidisciplinary environment as an individual or as a
member in team.

PO9 Comprehend and write effective reports and make quality presentations
about complex computing activities

PO10 Understand and assess the impact of computing practices and socio-
environmental concern

PO11 Work as an individual and a member or a leader in multidisciplinary


environment

PO12 Identify business opportunity and pursue using innovative ideas to create
value and wealth for the betterment of society
Bangalore Institute of Technology
K.R. Road, V.V. Puram, Bangalore – 560004
Department of Master of Computer Applications

C++ PROGRAMMING LABORATORY

Course Outcome

At the end of this course, the students will be able to

CO1:Apply and implement major programming and object oriented concepts like function
overloading, operator overloading, Encapsulations, and inheritance, message passing to solve
real-world problems.
CO2: Use major C++ features such as Virtual functions, Templates for data type independent designs
and File I/O to deal with large data sets.
CO3: Analyze, design and develop solutions to real-world problems applying OOP Concepts of C++.

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 3 3 3
18MCA18 CO2 3 3 3
CO3 3 3 3
CO4 3 3 3
C++ PROGRAMMING LABORATORY
Subject Code : 18MCA16 I.A Marks : 40
Hours/Week : 3 Exam Marks : 60
Total Hours : 42 Exam Hours : 3

Implement the following using windows operating system.

PART-A
1. Write a C++ program to find the sum for the given variables using function with default arguments.

2. Write a C++ program to swap the values of two variables and demonstrates a function using call by
value.

3. Write a C++ program to swap the values of two variables and demonstrates a function using Call by
reference using reference type (&).

4. Write a C++ program to swap the values of two variables and demonstrates a function using Call
by reference using pointer (*).

5. Write a C++ program to swap the values of two dynamically allocated variables and release the
memory after swapping. (use new & delete operators)

6. Write a program to find the largest, smallest & second largest of three numbers. (use inline function
MAX and MIN to find largest & smallest of 2 numbers)

7. Write a program to calculate the volume of different geometric shapes like cube, cylinder and
sphere and hence implement the concept of Function Overloading.

8. Write a C++ program to create a template function for Bubble Sort and demonstrate sorting of
integers and doubles.
PART-B
1. Define a STUDENT class with USN, Name, and Marks in 3 tests of a subject. Declare an array of
Ten STUDENT objects. Using appropriate functions, find the average of the two better marks for
each student. Print the USN, Name and the average marks of all the students.

2. Write a C++ program to create a class called COMPLEX and implement the following overloading
functions ADD that return a complex number: (i) ADD (a, s2) – where ‘a’ is an integer (real part) and
s2 is a complex number (ii) ADD (s1, s2) – where s1 and s2 are complex numbers.

3. Friend functions and friend classes:


a) Write a program to define class name HUSBAND and WIFE that holds the income respectively.
Calculate and display the total income of a family using Friend function.

b) Write a program to accept the student detail such as name and 3 different marks by get_data()
method and display the name and average of marks using display() method. Define a friend class for
calculating the average of marks using the method mark_avg().

4. Create a class called MATRIX using two-dimensional array of integers. Implement the following
operations by overloading the operator == which checks the compatibility of two matrices to be added
and subtracted. Perform the addition and subtraction by overloading the + and – operators
respectively. Display the results by overloading the operator < < If (m1== m2) then m3 = m1+m2 and
m4 = m1- m2 else display error.

5. Write a program to create an HUMAN class with features as number of Head, Legs, Hands.(NOTE:
Number of Head, Legs and Hands are of integer types) a. Create an object HUMAN1 using default
constructor. (Default features to have 1 Head, 2 Legs and 2 Hands) b. Create an object HUMAN2
with customized inputs using Parameterized Constructor c. Create an object HUMAN3 using existing
object HUMAN1 (Copy Constructor). d. All Humans die after their lifetime. (Destructor)

6. Demonstrate Simple Inheritance concept by creating a base class FATHER with data members
SurName and BankBalance and creating a derived class SON, which inherits SurName and
BankBalance feature from base class but provides its own feature FirstName and DOB. Create and
initialize F1 and S1 objects with appropriate constructors and display the Father & Son details. (Hint :
While creating S1 object, call Father base class parameterized constructor through derived class by
sending values)

7. Create an abstract base class EMPLOYEE with data members: Name, EmpID and BasicSal and a
pure virtual function Cal_Sal().Create two derived classes MANAGER (with data members: DA and
HRA and SALESMAN (with data members: DA, HRA and TA). Write appropriate constructors and
member functions to initialize the data, read and write the data and to calculate the net salary. The
main() function should create array of base class pointers/references to invoke overridden functions
and hence it implements run-time polymorphism.
8. Write a program to implement FILE I/O operations on characters. I/O operations includes inputting
a string, Calculating length of the string, Storing the string in a file, fetching the stored characters
from it, etc.

9. Write a program to implement Exception Handling with minimum 5 exceptions Classes including
two built-in exceptions.

10. a.Write a program to concatenate 2 strings using STL String class functions.

b.Write a simple C++ program to store and display integer elements using STL Vector class.

Note: In the examination questions must be given based on above lots


Bangalore Institute of Technology
K.R. Road, V.V. Puram, Bangalore – 560004
Department of Master of Computer Applications

C++ PROGRAMMING LABORATORY

Subject Code : 18MCA16 I.A Marks : 40

Hours/Week : 3 Exam Marks : 60

Total Hours : 42 Exam Hours : 3

Lesson Plan

Sl No. Weeks Topic to be covered


1 Week-1 Find the Sum for given variable
Swap the two values using call by value
2 Week-2 Swap the two values using call by reference using reference type
Swap the two values using call by reference using pointer
3 Week-3 Swap the values of two dynamically allocated variables and release the
memory after swapping.
Program to find largest, seclargest and smallest.
4 Week-4 Program to calculate the volume of different geometric shapes like cube,
cylinder and sphere.
Program to create a template function for Bubble Sort and demonstrate
sorting of integers and doubles.
5 Week-5 Define a STUDENT class with USN, Name, and Marks in 3 tests of a
subject, Find the average of the two better marks for each student
6 Week-6 Program to create a class called COMPLEX and implement the following
(i) ADD (a, s2) – where ‘a’ is an integer (real part) and s2 is a complex
number
(ii) ADD (s1, s2) – where s1 and s2 are complex numbers.
7 Week-7 Friend functions and friend classes:
Program to define class name HUSBAND and WIFE that holds the
income
Program to accept the student detail such as name and 3 different marks
by get_data() method and display the name and average of marks using
display() method
8 Week-8 Create a class called MATRIX using two-dimensional array of integers.
Implement the following operations by overloading
9 Week-9 Write a program to create an HUMAN class with features as number of
Head, Legs, Hands.
10 Week-10 Demonstrate Simple Inheritance concept by creating a base class
FATHER with data members SurName and Bank Balance and creating a
derived class SON
11 Week-11 Create an abstract base class EMPLOYEE with data members: Name,
EmpID and BasicSal and a pure virtual function Cal_Sal().
12 Week-12 Write a program to implement FILE I/O operations on characters. I/O
operations includes inputting a string
13 Week-13 Write a program to implement Exception Handling with minimum 5
exceptions Classes
14 Week-14 Write a program to concatenate 2 strings using STL String class
functions.
Write a simple C++ program to store and display integer elements using
STL Vector class
C++ PROGRAMMING LABORATORY
Subject Code : 18MCA186 I.A Marks : 40
Hours/Week : 3 Exam Marks : 60

SL NO. Contents WRITE EXECUTIO VIVA Staff


UP N signature
(5)
(10) (5)
PART A

1 Program 1

2 Program 2

3 Program 3

4 Program 4

5 Program 5

6 Program 6

7 Program 7

8 Program 8

PART B

1 Program 1

2 Program 2

3 Program 3a and 3b

4 Program 4

5 Program 5

6 Program 6
7 Program 7

8 Program 8

9 Program 9

10 Program 10a and


10b

Total Hours : 42 ExamHours : 3


Bangalore Institute of Technology
K.R. Road, V.V. Puram, Bangalore – 560004
Department of Master of Computer Applications

C++ PROGRAMMING LABORATORY

Subject Code : 18MCA16 I.A Marks : 40

Hours/Week : 3 Exam Marks : 60

Total Hours : 42 Exam Hours : 3

LAB INTERNALS

Rubrix Max Marks-20

TEST Max Marks-20

TOTAL Max Marks-40

Signature of the Faculty


CONTENTS

PART-A

SL No Programs Pg No
Write a C++ program to find the sum for the given variables
1 using function with default arguments. 1-2
2 Write a C++ program to swap the values of two variables and 3-4
demonstrates a function using call by value.
3 Write a C++ program to swap the values of two variables and 5-6
demonstrates a function using Call by reference using reference
type (&).
4 Write a C++ program to swap the values of two variables and 7-8
demonstrates a function using Call by reference using pointer
(*).
5 Write a C++ program to swap the values of two dynamically 9-10
allocated variables and release the memory after swapping. (use
new & delete operators).
6 Write a program to find the largest, smallest & second largest of 11-13
three numbers. (use inline function MAX and MIN to find
largest & smallest of 2 numbers).
7 Write a program to calculate the volume of different geometric 14-15
shapes like cube, cylinder and sphere and hence implement the
concept of Function Overloading.
8 Write a C++ program to create a template function for Bubble 16-18
Sort and demonstrate sorting of integers and doubles.
PART-B
SL No Programs Pg No
Define a STUDENT class with USN, Name, and Marks in 3
1 tests of a subject. Declare an array of Ten STUDENT objects. 20-22
Using appropriate functions, find the average of the two better
marks for each student. Print the USN, Name and the average
marks of all the students.
2 Write a C++ program to create a class called COMPLEX and 23-25
implement the following overloading functions ADD that return
a complex number: (i) ADD (a, s2) – where ‘a’ is an integer
(real part) and s2 is a complex number (ii) ADD (s1, s2) – where
s1 and s2 are complex numbers.
3 Friend functions and friend classes: 26-31
a) Write a program to define class name HUSBAND and WIFE
that holds the income respectively. Calculate and display the
total income of a family using Friend function.
b) Write a program to accept the student detail such as name and
3 different marks by get_data() method and display the name
and average of marks using display() method. Define a friend
class for calculating the average of marks using the method
mark_avg().
4 Create a class called MATRIX using two-dimensional array of 32-35
integers. Implement the following operations by overloading the
operator == which checks the compatibility of two matrices to
be added and subtracted. Perform the addition and subtraction by
overloading the + and – operators respectively. Display the
results by overloading the operator < < If (m1== m2) then m3 =
m1+m2 and m4 = m1- m2 else display error.
5 Write a program to create an HUMAN class with features as 36-38
number of Head, Legs, Hands.(NOTE: Number of Head, Legs
and Hands are of integer types) a. Create an object HUMAN1
using default constructor. (Default features to have 1 Head, 2
Legs and 2 Hands) b. Create an object HUMAN2 with
customized inputs using Parameterized Constructor c. Create an
object HUMAN3 using existing object HUMAN1 (Copy
Constructor). d. All Humans die after their lifetime. (Destructor)

6 Demonstrate Simple Inheritance concept by creating a base class 39-41


FATHER with data members SurName and BankBalance and
creating a derived class SON, which inherits SurName and
BankBalance feature from base class but provides its own
feature FirstName and DOB. Create and initialize F1 and S1
objects with appropriate constructors and display the Father &
Son details. (Hint : While creating S1 object, call Father base
class parameterized constructor through derived class by sending
values)
7 Create an abstract base class EMPLOYEE with data members: 42-45
Name, EmpID and BasicSal and a pure virtual function
Cal_Sal().Create two derived classes MANAGER (with data
members: DA and HRA and SALESMAN (with data members:
DA, HRA and TA). Write appropriate constructors and member
functions to initialize the data, read and write the data and to
calculate the net salary. The main() function should create array
of base class pointers/references to invoke overridden functions
and hence it implements run-time polymorphism.
8 Write a program to implement FILE I/O operations on 46-47
characters. I/O operations includes inputting a string,
Calculating length of the string, Storing the string in a file,
fetching the stored characters from it, etc.

9 Write a program to implement Exception Handling with 48-51


minimum 5 exceptions Classes including two built-in
exceptions.

10 a). Write a program to concatenate 2 strings using STL String 52-55


class functions.
b).Write a simple C++ program to store and display integer
elements using STL Vector class.
C++ Programming Lab 18MCA16

PART-A

1. Write a C++ program to find the sum for the given variables using
function with default arguments.

#include<iostream.h>
#include<conio.h>

void sum(int a, int b, int c=6, int d=10);


int main()
{
clrscr();
int a,b,c,d;
cout<<"Enter any two numbers\n";
cin>>a>>b;
sum(a,b);
getch();
}

void sum(int a1,int a2,int a3,int a4)


{
int temp;
temp=a1+a2+a3+a4;
cout<<"a=" <<a1<<endl;
cout<<"b=" <<a2<<endl;
cout<<"c=" <<a3<<endl;
cout<<"d=" <<a4<<endl;

Bangalore Institute Of Technology Page 1


C++ Programming Lab 18MCA16

cout<<" sum="<<temp;
}

Bangalore Institute Of Technology Page 2


C++ Programming Lab 18MCA16

Output:

Bangalore Institute Of Technology Page 3


C++ Programming Lab 18MCA16

2. Write a C++ program to swap the values of two variables and


demonstrates a function using call by value.

#include<iostream.h>
#include<conio.h>

void swap(int x,int y);


int main()
{
clrscr();
int a=100;
int b=200;
cout<<"Before swap value of a:"<<a<<endl;
cout<<"Before swap value of b:"<<b<<endl;
//calling a function to swap the values
cout<<"After swapping"<<endl;
swap(a,b);
getch();
}

//function definition to swap the values


void swap(int x,int y)
{
int temp;
temp=x;
x=y;

Bangalore Institute Of Technology Page 4


C++ Programming Lab 18MCA16

y=temp;
cout<<"After swap, value of a:"<<x<<endl;
cout<<"After swap, value of b:"<<y<<endl;
}

Bangalore Institute Of Technology Page 5


C++ Programming Lab 18MCA16

Output:

Bangalore Institute Of Technology Page 6


C++ Programming Lab 18MCA16

3. Write a C++ program to swap the values of two variables and


demonstrates a function using Call by reference using reference type (&).

#include<iostream.h>
#include<conio.h>

void swap(int &x,int &y);


int main()
{
clrscr();
//local variable declaration:
int a=100;
int b=200;
cout<<"Before swap, value of a:"<<a<<endl;
cout<<"Before swap, value of b:"<<b<<endl;
swap(a,b);
cout<<"After swap, value of a:"<<a<<endl;
cout<<"After swap. value of b:"<<b<<endl;
getch();
}

void swap(int &x,int &y)


{
int temp;

Bangalore Institute Of Technology Page 7


C++ Programming Lab 18MCA16

temp=x; /* save the value of x */


x=y; /* put y into x */
y=temp; /* put x into y */
}

Bangalore Institute Of Technology Page 8


C++ Programming Lab 18MCA16

Output:

Bangalore Institute Of Technology Page 9


C++ Programming Lab 18MCA16

4. Write a C++ program to swap the values of two variables and


demonstrates a function using Call by reference using pointer (*).

// Program: Call by reference using „&‟ operator.


#include <iostream.h>
#include <conio.h>

void swap (int *x, int *y)


{
int temp;

temp = *x;
*x = *y;
*y = temp;
}

void main ()
{
cout<<"---------- Swapping Using Call By Reference UsingPointer(*)----------
\n"<<endl;
int a = 100;
int b = 200;

cout << "**** Output Before swap ****"<< endl;


cout << " a = " << a << endl;
cout << " b = " << b << endl;

Bangalore Institute Of Technology Page 10


C++ Programming Lab 18MCA16

swap (&a, &b);


cout << "**** Output After swap ****"<< endl;
cout << " a = " << a << endl;
cout << " b = " << b << endl;
}

Bangalore Institute Of Technology Page 11


C++ Programming Lab 18MCA16

Output:

Bangalore Institute Of Technology Page 12


C++ Programming Lab 18MCA16

5. Write a C++ program to swap the values of two dynamically allocated


variables and release the memory after swapping. (use new & delete
operators)

// Program: Call by reference using „&‟ operator.


#include <iostream>
using namespace std;
void swap (int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}

int main ()
{
cout<<"******** Swapping Using Dynamic Variable ******\n"<<endl;
int *a;
int *b;

a = new int (50);


b = new int (100);

cout << "**** Output Before swap ****"<< endl;


cout << " a = " << *a << endl;
cout << " b = " << *b << endl;

Bangalore Institute Of Technology Page 13


C++ Programming Lab 18MCA16

swap (a, b);


cout << "**** Output After swap ****"<< endl;
cout << " a = " << *a << endl;
cout << " b = " << *b << endl;
}

Bangalore Institute Of Technology Page 14


C++ Programming Lab 18MCA16

Output:

Bangalore Institute Of Technology Page 15


C++ Programming Lab 18MCA16

6. Write a program to find the largest, smallest & second largest of three
numbers. (use inline function MAX and MIN to find largest & smallest of 2
numbers)

#include <iostream.h>
#include<conio.h>

inline void max(int a, int b, int c)


{
int largest, seclargest;
if (a >= b && a >= c)
{
largest = a;
if (b >= c)
seclargest = b;
else
seclargest = c;
}
else if (b >= c && b >= a)
{
largest = b;
if (a >= c)
seclargest = a;
else
seclargest = c;
}
else

Bangalore Institute Of Technology Page 16


C++ Programming Lab 18MCA16

{
largest = c;
if (a >= b)
seclargest = a;
else
seclargest = b;
}
cout << "largest number:" << largest << endl;
cout << "second largest number:" << seclargest << endl;
}

inline void min(int a, int b, int c)


{
int smallest;
if (a <= b && a <= c)
{
smallest = a;
}
else
{
if (b <= c)
smallest = b;
else
smallest = c;
}
cout << "smallest number:" << smallest << endl;

Bangalore Institute Of Technology Page 17


C++ Programming Lab 18MCA16

int main()
{
clrscr();
int a, b, c;
cout << "please enter 3 numbers to compare:";
cin >> a >> b >> c;
max(a, b, c);
min(a, b, c);
getch();
}

Bangalore Institute Of Technology Page 18


C++ Programming Lab 18MCA16

Output:

Bangalore Institute Of Technology Page 19


C++ Programming Lab 18MCA16

7. Write a program to calculate the volume of different geometric shapes


like cube, cylinder and sphere and hence implement the concept of
Function Overloading.

#include<iostream.h>
#include<conio.h>

float vol(int,int);
float vol(float);
int vol(int);

int main()
{
clrscr();
int r,h,a;
float r1;
cout<<"Enter radius and height of a cylinder:";
cin>>r>>h;
cout<<"Enter side of cube:";
cin>>a;
cout<<"Enter radius of sphere:";
cin>>r1;
cout<<"volume of cylinder is"<<vol(r,h);
cout<<"\n volume of cube is"<<vol(a);
cout<<"\n volume of sphere is"<<vol(r1);
getch();

Bangalore Institute Of Technology Page 20


C++ Programming Lab 18MCA16

return 0;
}

float vol(int r,int h)


{
return(3.14*r*h);
}

float vol(float r1)


{
return((4*3.14*r1*r1*r1)/3);
}

int vol(int a)
{
return(a*a*a);
}

Bangalore Institute Of Technology Page 21


C++ Programming Lab 18MCA16

Output:

Bangalore Institute Of Technology Page 22


C++ Programming Lab 18MCA16

8. Write a C++ program to create a template function for Bubble Sort and
demonstrate sorting of integers and doubles.

#include <iostream.h>
#include <iomanip.h>
#include <conio.h>

template <class t>


class bubble
{
t a[10];

public:
void get(int);
void sort(int);
void display(int);
};
template <class t>
void bubble<t>::get(int n)
{
int i;
cout << "The sorted array is\n";
for (i = 0; i < n; i++)
cin >> a[i];
}
template <class t>

Bangalore Institute Of Technology Page 23


C++ Programming Lab 18MCA16

void bubble<t>::display(int n)
{
int i;
cout << "The sorted array is\n";
for (i = 0; i < n; i++)
cout << a[i] << setw(10);
}
template <class t>
void bubble<t>::sort(int n)
{
int i, j;
t temp;
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n - i - 1; j++)
{
if (a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
int main()

Bangalore Institute Of Technology Page 24


C++ Programming Lab 18MCA16

{
clrscr();
int n;
bubble<int> b1;
bubble<double> b2;

cout << "\n Bubble sort on integer values\n";


cout << "Enter the size of array:\n";
cin >> n;
b1.get(n);
b1.sort(n);
b1.display(n);
cout << "\n bubble sort on double values \n";
cout << "Enter the size of array:\n";
cin >> n;
b2.get(n);
b2.sort(n);
b2.display(n);
getch();
}

Bangalore Institute Of Technology Page 25


C++ Programming Lab 18MCA16

Output:

Bangalore Institute Of Technology Page 26


C++ Programming Lab 18MCA16

Bangalore Institute Of Technology Page 27


C++ Programming Lab 18MCA16

PART B

1. Define a STUDENT class with USN, Name, and Marks in 3 tests of a


subject. Declare an array of 10 STUDENT objects. Using appropriate
functions, find the average of the two better marks for each student. Print
the USN, Name and the average marks of all the students.

#include <iostream.h>
#include <conio.h>

class student
{
char usn[10], name[20];
int t1, t2, t3;
float avg;

public:
void read();
void disp();
void calc();
};

void student::read()
{
cout << "Enter usn\n";
cin >> usn;
cout << "Enter name\n";
cin >> name;
cout << "Enter 3 test marks\n";
cin >> t1;
cin >> t2;
cin >> t3;
}

void student::calc()
{
if ((t1 < t2) && (t1 < t3))
{
avg = (t2 + t3) / 2;
cout << avg;
}
else if (t2 < t3)

Bangalore Institute Of Technology Page 28


C++ Programming Lab 18MCA16

avg = (t1 + t3) / 2;


else
avg = (t1 + t2) / 2;
}

void student::disp()
{
cout << usn << "\t" << name << "\t" << t1 << "\t" << t2 << "\t" << t3 << "\t"
<< avg << endl;
}

int main()
{
clrscr();
student stud[' '];
int i, n;
cout << "Enter number of students\n";
cin >> n;
for (i = 0; i < n; i++)
{
stud[i].read();
stud[i].calc();
}
cout << "\n USN\tNAME\tTEST1\tTEST2\tTEST3\tAVERAGE\n";
for (i = 0; i < n; i++)
stud[i].disp();
getch();
return 0;
}

Bangalore Institute Of Technology Page 29


C++ Programming Lab 18MCA16

Output:

Bangalore Institute Of Technology Page 30


C++ Programming Lab 18MCA16

2. Write a C++ program to create a class called COMPLEX and implement


the following overloading functions ADD that return a complex
number:
(i) ADD (a, s2) – where ‘a’ is an integer (real part) and s2 is a complex
number
(ii) ADD (s1, s2) – where s1 and s2 are complex numbers.

#include <iostream.h>
#include<conio.h>

class complex
{
int real, imag;

public:
void read();
void disp();
complex ADD(int a, complex);
complex ADD(complex, complex);
};
void complex::read()
{
cout << "Enter real part\n";
cin >> real;
cout << "Enter imaginary part\n";
cin >> imag;
}
void complex::disp()
{
cout << "\t" << real << "+" << imag << "i"
<< "\n";
}
complex complex::ADD(int a, complex s2)
{
s2.real = s2.real + a;
return s2;
}
complex complex::ADD(complex s1, complex s2)
{
complex s3;
s3.real = s1.real + s2.real;
s3.imag = s1.imag + s2.imag;

Bangalore Institute Of Technology Page 31


C++ Programming Lab 18MCA16

return s3;
}

int main()
{
clrscr();
complex s1, s2, s3;
int a, ch;
do
{
cout << "1.Adding a number to real part\n";
cout << "2.Adding two complex number\n";
cout << "3.Exit";
cout << "Enter your choice:\n";
cin >> ch;
switch (ch)
{
case 1:
cout << "Enter complex number\n";
s2.read();
cout << "Enter integer to add\n";
cin >> a;
s3 = s2.ADD(a, s2);
s3.disp();
break;
case 2:
cout << "Enter two complex numbers\n";
cout << "Enter first complex number\n";
s1.read();
cout << "Enter second complex number\n";
s2.read();
s3 = s2.ADD(s1, s2);
s3.disp();
break;
case 3:
break;
default:
cout << "Invalid choice\n";
break;
}
} while (ch != 3);
getch();

Bangalore Institute Of Technology Page 32


C++ Programming Lab 18MCA16

return 0;
}
Output:

Bangalore Institute Of Technology Page 33


C++ Programming Lab 18MCA16

3. Friend functions and friend classes:


a) Write a program to define class name HUSBAND and WIFE that holds
the income respectively. Calculate and display the total income of a family
using Friend function.

#include <iostream.h>
#include <conio.h>

class wife;
class husband
{
float incomeh;

public:
void read()
{
cout << "enter income husband\n";
cin >> incomeh;
}
friend void total(husband, wife);
};
class wife
{
float incomew;

public:
void read()
{
cout << "enter income wife\n";
cin >> incomew;
}
friend void total(husband, wife);
};
void total(husband h, wife w)
{
float sum;
sum = h.incomeh + w.incomew;
cout << "total income is " << sum;
}

Bangalore Institute Of Technology Page 34


C++ Programming Lab 18MCA16

int main()
{
clrscr();
husband h;
h.read();
wife w;
w.read();
total(h, w);
getch();
return 0;
}

Bangalore Institute Of Technology Page 35


C++ Programming Lab 18MCA16

Output:

Bangalore Institute Of Technology Page 36


C++ Programming Lab 18MCA16

b) Write a program to accept the student detail such as name and 3


different marks by get_data() method and display the name and average of
marks using display() method. Define a friend class for calculating the
average of marks using the method mark_avg().

#include<iostream>
using namespace std;
class Student
{
private:
char name[15];
float m1,m2,m3,avg;
public:
void getData();
friend class AVGMARKS;
void showData();
};
class AVGMARKS
{
public:
int getAvg(Student t)
{
t.avg = (t.m1 + t.m2 + t.m3) / 3.0;
return t.avg;
}
};
void Student::getData()
{
cout << "Enter Student name : " ;

Bangalore Institute Of Technology Page 37


C++ Programming Lab 18MCA16

cin >> name;


cout << "Enter test marks of 3 Subjects :" << endl;
cout << "Test1 = " ;
cin >> m1;
cout << "Test2 = " ;
cin >> m2;
cout << "Test3 = " ;
cin >> m3;
}

void Student::showData()
{
cout<<"--------------------------------------"<<endl;
cout<<name<<" Details are:"<<endl;
cout<<"--------------------------------------"<<endl;
cout<<"Name:"<<name<<endl; cout<<"Test1:"<<m1<<endl;
cout<<"Test2:"<<m2<<endl; cout<<"Test3:"<<m3<<endl;
cout<<"---------------------------------------\n";
}
int main()
{
Student s1; AVGMARKS ob;
s1.getData();
s1.showData();
cout<< "Avgerage Marks = " ;
cout << ob.getAvg(s1) ;
}

Bangalore Institute Of Technology Page 38


C++ Programming Lab 18MCA16

Output:

Bangalore Institute Of Technology Page 39


C++ Programming Lab 18MCA16

4. Create a class called MATRIX using two-dimensional array of integers.


Implement the following operations by overloading the operator == which
checks the compatibility of two matrices to be added and subtracted.
Perform the addition and subtraction by overloading the + and – operators
respectively. Display the results by overloading the operator <<. If (m1==
m2) then m3 = m1+m2 and m4 = m1- m2 else display error.

#include <iostream.h>
#include <conio.h>

class mat
{
int a[10][10], row, col;

public:
void readord();
void readmat();
int operator==(mat);
mat operator+(mat);
mat operator-(mat);
friend ostream &operator<<(ostream &, mat &);
};
void mat::readord()
{
int i, j;
cout << "Enter number of rows\n";
cin >> row;
cout << "\nEnter number of coloumns\n";
cin >> col;
}
void mat::readmat()
{
int i, j;
cout << "Enter mat elements\n";
for (i = 0; i < row; i++)
for (j = 0; j < col; j++)
cin >> a[i][j];
}
int mat::operator==(mat m2)
{
if (row == m2.row && col == m2.col)
return 1;

Bangalore Institute Of Technology Page 40


C++ Programming Lab 18MCA16

else
return 0;
}
mat mat::operator+(mat m2)
{
mat temp;
int i, j;
for (i = 0; i < row; i++)
for (j = 0; j < col; j++)
temp.a[i][j] = a[i][j] + m2.a[i][j];
temp.row = row;
temp.col = col;
return temp;
}
mat mat::operator-(mat m2)
{
mat temp;
int i, j;
for (i = 0; i < row; i++)
for (j = 0; j < col; j++)
temp.a[i][j] = a[i][j] - m2.a[i][j];
temp.row = row;
temp.col = col;
return temp;
}
ostream &operator<<(ostream &fout, mat &d)
{
for (int i = 0; i < d.col; i++)
{
for (int j = 0; j < d.col; j++)
{
fout << d.a[i][j];
cout << " ";
}
cout << endl;
}
return fout;
}
int main()
{
clrscr();
mat m1, m2, m3, m4;

Bangalore Institute Of Technology Page 41


C++ Programming Lab 18MCA16

cout << "\nEnter order of first matrix:\n";


m1.readord();
cout << "\nEnter order of second matrix:\n";
m2.readord();
if (m1 == m2)
{
cout << "\nEnter the elements of first mat:\n";
m1.readmat();
cout << "\nEnter the elements of second mat:\n";
m2.readmat();
cout << "First matrix is\n";
cout << m1;
cout << "\n Second matrix is\n";
cout << m2;
m3 = m1 + m2;
m4 = m1 - m2;
cout << "Sum of 2 matrices are\n"
<< endl;
cout << m3;
cout << "Difference of 2 matrices are\n"
<< endl;
cout << m4;
}
else
cout << "mat sum and difference cannot be computed\n";
getch();
return 0;
}

Bangalore Institute Of Technology Page 42


C++ Programming Lab 18MCA16

Output:

Bangalore Institute Of Technology Page 43


C++ Programming Lab 18MCA16

5. Write a program to create an HUMAN class with features as number of


Head, Legs, Hands.(NOTE: Number of Head, Legs and Hands are of
integer types) a. Create an object HUMAN1 using default constructor.
(Default features to have 1 Head, 2 Legs and 2 Hands) b. Create an object
HUMAN2 with customized inputs using Parameterized Constructor c.
Create an object HUMAN3 using existing object HUMAN1 (Copy
Constructor). d. All Humans die after their lifetime. (Destructor)

#include<iostream.h>
#include<conio.h>
#include<string.h>

class HUMAN
{
private:
char name[30];
int head; int legs; int hands;
public: HUMAN()
{
strcpy(name , "\n--man1--\n");
head = 1;
legs = 2;
hands = 2;
}

HUMAN (int head, int legs, int hands)


{
strcpy(name , "\n--man2--\n");
this->head = head;
this->legs = legs;

Bangalore Institute Of Technology Page 44


C++ Programming Lab 18MCA16

this->hands = hands;
}

HUMAN ( HUMAN &man)


{
strcpy(name , "\n--man3--\n");
head = man.head;
legs = man.legs;
hands = man.hands;
}

~HUMAN()
{
cout << name << " is killed "<<endl;
getch();
}
void show()
{
cout << "head=" << head << endl << "legs=" << legs <<endl;
cout << "hands=" << hands << endl;
}
};

void main()
{
HUMAN man1, man2(3,4,5), man3 = man1;
cout << "Human1 values:"<< endl;

Bangalore Institute Of Technology Page 45


C++ Programming Lab 18MCA16

cout << "--------------"<< endl;


man1.show();
cout << "Human2 values:" << endl;
cout << "--------------" << endl;
man2.show();
}
cout << "Human3 values:" <<endl;
cout <<"--------------" <<endl;
man3.show();
}

Bangalore Institute Of Technology Page 46


C++ Programming Lab 18MCA16

Output:

Bangalore Institute Of Technology Page 47


C++ Programming Lab 18MCA16

6. Demonstrate Simple Inheritance concept by creating a base class


FATHER with data members SurName and BankBalance and creating a
derived class SON, which inherits SurName and BankBalance feature from
base class but provides its own feature FirstName and DOB. Create and
initialize F1 and S1 objects with appropriate constructors and display the
Father & Son details. (Hint : While creating S1 object, call Father base
class parameterized constructor through derived class by sending values)

#include <iostream.h>
#include<conio.h>

class FATHER
{
char fname[20], dob[20];

protected:
char surname[20];
float bal;

public:
FATHER();
void disp1();
};
FATHER::FATHER()
{
cout << "enter first name of father\n";
cin >> fname;
cout << "enter sur name of father\n";
cin >> surname;
cout << "enter date of birth of father\n";
cin >> dob;
cout << "enter bank balance of father\n";
cin >> bal;
}
void FATHER::disp1()
{
cout << "FATHER FIRST NAME IS" << fname << "\n";
cout << "FATHER SUR NAME IS" << surname << "\n";
cout << "FATHER DATE OF BIRTH IS" << dob << "\n";
cout << "BANK BALANCE IS" << bal << "\n";
}
class SON : public FATHER

Bangalore Institute Of Technology Page 48


C++ Programming Lab 18MCA16

{
char fname[20], dob[20];

public:
void read();
void disp();
};
void SON::read()
{
cout << "enter first name of son\n";
cin >> fname;
cout << "enter date of birth of son\n";
cin >> dob;
}
void SON::disp()
{
cout << " name of son is" << fname << "\n";
cout << " sur name is" << surname << "\n";
cout << " son date of birth is" << dob << "\n";
cout << " son bank balance is" << bal << "\n";
}
int main()
{
clrscr();
SON s;
s.read();
s.disp1();
s.disp();
getch();
return 0;
}

Bangalore Institute Of Technology Page 49


C++ Programming Lab 18MCA16

Output:

Bangalore Institute Of Technology Page 50


C++ Programming Lab 18MCA16

7. Create an abstract base class EMPLOYEE with data members: Name,


EmpID and BasicSal and a pure virtual function Cal_Sal().Create two
derived classes MANAGER (with data members: DA and HRA and
SALESMAN (with data members: DA, HRA and TA). Write appropriate
constructors and member functions to initialize the data, read and write
the data and to calculate the net salary. The main() function should create
array of base class pointers/references to invoke overridden functions and
hence it implements run-time polymorphism.

#include <iostream.h>
#include<conio.h>

class employee
{
protected:
char name[25];
int eid, bp;

public:
virtual void input() = 0;
virtual void calsal() = 0;
virtual void output() = 0;
};
class manager : public employee
{
protected:
float da, hra, dap, hrap, tax, gp, np;

public:
manager()
{
dap = 7;
hrap = 5;
tax = 500;
}
void input()
{
cout << "\n manager details\n";
cout << "Enter name id bp";
cin >> name >> eid >> bp;
}
void calsal()

Bangalore Institute Of Technology Page 51


C++ Programming Lab 18MCA16

{
da = dap * bp;
hra = hrap * bp;
gp = da + hra + tax;
np = gp - tax;
}
void output()
{
cout << "\nname\tda\tHRA\tgp\tbp\n";
cout << name << "\t" << da << "\t" << hra << "\t" << gp << "\t" << bp <<
"\n";
}
};
class salesman : public employee
{
protected:
float da, ta, hra, tap, dap, hrap, tax, gp, np;

public:
salesman()
{
tap = 5;
dap = 7;
hrap = 5;
tax = 500;
}

void input()
{
cout << "\nsales man details\n";
cout << "enter name id bp\n";
cin >> name >> eid >> bp;
}
void calsal()
{
ta = tap * bp;
da = dap * bp;
hra = hrap * bp;
gp = da + hra + tax;
np = gp - tax;
}
void output()

Bangalore Institute Of Technology Page 52


C++ Programming Lab 18MCA16

{
cout << "\n salesman details\n";
cout << "\nname\tDA\tHRA\tGP\tBP\n";
cout << name << "\t" << da << "\t" << hra << "\t" << gp << "\t" << bp <<
"\n";
}
};

int main()
{
clrscr();
int m1, m2, i, j;
cout << "\nEnter number of managers\n";
cin >> m1;
cout << "\nEnter number of salesman\n";
cin >> m2;
employee *p[25];
manager m[25];
salesman s[25];
for (i = 1; i <= m1; i++)
{
p[i] = &m[i];
p[i]->input();
p[i]->calsal();
}
for (i = m1 + 1, j = 1; i <= m1 + m2; i++, j++)
{
p[i] = &s[j];
p[i]->input();
p[i]->calsal();
}

cout << "\nmanager details\n";


for (i = 1; i <= m1; i++)
{
p[i]->output();
}
for (i = m1 + 1; i <= m1 + m2; i++)
{
p[i]->output();
}
getch();

Bangalore Institute Of Technology Page 53


C++ Programming Lab 18MCA16

return 0;
}

Output:

Bangalore Institute Of Technology Page 54


C++ Programming Lab 18MCA16

8. Write a program to implement FILE I/O operations on characters. I/O


operations includes inputting a string, Calculating length of the string,
Storing the string in a file, fetching the stored characters from it, etc.

#include <fstream.h>
#include <iostream.h>
#include <conio.h>

void write(ofstream &outfile)


{
int l=0;
char str[50];
cout << "read str from user" << endl;
cin.getline(str, 50); //reading the input using getline
for (int i = 0; str[i] != '\0'; i++)
l = i+1;
cout << "\nlength of str=" << l;
outfile << str;
}
void read(ifstream &infile)
{
char str[50];
cout << "\nread str from user" << endl;
while (infile.eof())
{
infile >> str;
cout << str << " "; //display data on screen
}
}
int main()
{
clrscr();
char str[50];

ofstream outfile;
outfile.open("data.txt"); //open a file data.txt
write(outfile); //display
outfile.close(); //closing the file data.txt
ifstream infile;
infile.open("data.txt");
read(infile);
infile.close();

Bangalore Institute Of Technology Page 55


C++ Programming Lab 18MCA16

getch(); }
Output:

Bangalore Institute Of Technology Page 56


C++ Programming Lab 18MCA16

9. Write a program to implement Exception Handling with minimum


5 exceptions Classes including two built-in exceptions.

#include <iostream>

using namespace std;

class BagException {
public:
char *what() { return " Bag weight is exceeding 40 kg.. Not allowed "; }
};

class AgeException {
public:
char *what() { return " Age is Less than 10 years..Not allowed to travel"; }
};

class LuggageException {
public:
char *what() { return " No. of Luggage are exceeding 10..Not allowed"; }
};

int main() {
int bagWeight, age, luggageCount, seatNo;
float cost;

cout << "Enter Bag weight :" << endl;


cin >> bagWeight;

Bangalore Institute Of Technology Page 57


C++ Programming Lab 18MCA16

cout << "Enter Passsenger Age :" << endl;


cin >> age;

cout << "Enter number of Luggage Passenger has :" << endl;
cin >> luggageCount;

cout << "Enter Seat No :" << endl;


cin >> seatNo;

cout << "Enter Flight Cost Paid:" << endl;


cin >> cost;

try {
if (bagWeight > 40)
throw BagException(); // throw exception of type BagException

if (age < 10) throw AgeException(); // throw exception of type


AgeException

if (luggageCount > 10)


throw LuggageException(); // throw exception of type LuggageException

if (seatNo < 5) throw seatNo; // throw exception of type int

if (cost < 0) throw cost; // throw exception of type float

cout << "Passenger can board the Plane ...";

Bangalore Institute Of Technology Page 58


C++ Programming Lab 18MCA16

} catch (BagException e) {
cout << "\nCaught an exception : " << endl;
cout << e.what() << endl;
}
catch (AgeException e) {
cout << "\nCaught an exception : " << endl;
cout << e.what() << endl;
}
catch (LuggageException e) {
cout << "\nCaught an exception : " << endl;
cout << e.what() << endl;
}
catch (int seatNo) {
cout << "\nCaught an exception :" << endl;
cout << "Seat no below -" << seatNo << " are a reserved...." << endl;
}
catch (float price) {
cout << "\nCaught an exception :" << endl;
cout << "Cost : " << price << " is less than zero and Invalid...." << endl;
}
cout << "\n End";

return 0;
}

Bangalore Institute Of Technology Page 59


C++ Programming Lab 18MCA16

Output:

Bangalore Institute Of Technology Page 60


C++ Programming Lab 18MCA16

10. a.Write a program to concatenate 2 strings using STL String class


functions.

#include <iostream.h>
#include <string.h>
#include <conio.h>

int main()
{
clrscr();
char s1[10], s2[10], s3[20];
cout << "Enter the string-1:";
cin >> s1;
cout << "Enter the string-2:";
cin >> s2;
cout << "Concatenation of two-string:";
strcpy(s3, s1);
strcat(s3, s2);
cout << s3;
getch();
return 0;
}

Bangalore Institute Of Technology Page 61


C++ Programming Lab 18MCA16

Output:

Bangalore Institute Of Technology Page 62


C++ Programming Lab 18MCA16

b) Write a simple C++ program to store and display integer elements using
STL Vector class.

#include<iostream>
#include<vector>

using namespace std;


int main ()
{
vector <int> v(5);
int i;
cout<<"size of a vector is "<<v.size()<<endl;
for(i=0;i<5;i++)
v[i]=i+1;
cout<<"content are \n";
for(i=0;i<v.size();i++)
cout<<v[i]<<"\t";
}

Bangalore Institute Of Technology Page 63


C++ Programming Lab 18MCA16

Output:

Bangalore Institute Of Technology Page 64


C++ Programming Lab 18MCA16

Note 1: In the practical Examination each student has to pick one question
from PART-A and PART-B each.

Note 2: Change of program is not permitted in the Practical Examination.

Bangalore Institute Of Technology Page 65

Potrebbero piacerti anche