UG - BCA - Computer Applications - B - C - A - 101 24 - Lab - Programming in C++
UG - BCA - Computer Applications - B - C - A - 101 24 - Lab - Programming in C++
sruIncrease
oC eht fothe
ezifont
s tnosize
f ehof
t esthe
aerCourse
cnI .1 Name.
.egaP revoC e2.ht nuse
i rethe
daefollowing
h a sa gniwasolaloheader
f eht esin
u the
.2 Cover Page.
YTISREVINUALAGAPPA
APPAGALAUNIVERSITY
B.C.A. elcyC drihT eht ni )46.3:APGC( CA[Accredited
AN yb edarG
]CGU-DRHM yb ytisrevinU I–yrogeand
300 036 – IDUKIARA
KARAIKUDI
K
with
’+A’’A+’
taC Graded
htiw
sa dedaras
– 630 003
Grade
detidby
ercNAAC
cA[ (CGPA:3.64) in the Third Cycle
G Category–I
dna University by MHRD-UGC]
B.C.A.
101 24
itnem sYou
a egaare
p reinstructed
voc eht etatodpupdate
u ot dethe
tcurcover
tsni erpage
a uoYas mentioned below:
.emaN e1.sruIncrease
oC eht fothe
ezifont
s tnosize
f ehof
t esthe
aerCourse
cnI .1 Name.
aP revoC e2.ht nuse
i rethe
daefollowing
h a sa gniwasolaloheader
f eht esin
u the
.2 Cover Page.
ISREVINUALAGAPPA
APPAGALAUNIVERSITY
rihT eht ni )46.3:APGC( CA[Accredited
AN yb edarGwith
’+A’’A+’
htiwGrade
detidby
ercNAAC
cA[ (CGPA:3.64) in the Third Cycle
]CGU-DRHM yb ytisrevinU I–yrogeand
taC Graded
sa dedarasG Category–I
dna University by MHRD-UGC]
300 036 – IDUKIARA
KARAIKUDI
TACUDE ECNATSIDDIRECTORATE
K
FO ETAROTCEOF
– 630 003
RIDDISTANCE EDUCATION
LAB: PROGRAMMING IN C++
II - Semester
ALAGAPPA UNIVERSITY
[Accredited with ‘A+’ Grade by NAAC (CGPA:3.64) in the Third Cycle
and Graded as Category–I University by MHRD-UGC]
(A State University Established by the Government of Tamil Nadu)
B.C.A.
II - Semester
101 24
LAB: PROGRAMMING IN C ++
Author:
Dr. Kavita Saini, Associate Professor, Galgotias University, Greater Noida
All rights reserved. No part of this publication which is material protected by this copyright notice
may be reproduced or transmitted or utilized or stored in any form or by any means now known or
hereinafter invented, electronic, digital or mechanical, including photocopying, scanning, recording
or by any information storage or retrieval system, without prior written permission from the Alagappa
University, Karaikudi, Tamil Nadu.
Information contained in this book has been published by VIKAS® Publishing House Pvt. Ltd. and has
been obtained by its Authors from sources believed to be reliable and are correct to the best of their
knowledge. However, the Alagappa University, Publisher and its Authors shall in no event be liable for
any errors, omissions or damages arising out of use of this information and specifically disclaim any
implied warranties or merchantability or fitness for any particular use.
Work Order No. AU/DDE/DE1-291/Preparation and Printing of Course Materials/2018 Dated 19.11.2018 Copies - 500
LAB: PROGRAMMING IN C ++
Syllabi
BLOCK 1
1. Simple Programs using decisions, loops and arrays
2. Simple functions & Inline functions
BLOCK 2
3. Usage of classes and Objects
4. This pointer and Static functions
5. Constructors and Destructors
BLOCK 3
6. Function overloading
7. Operator Overloading
8. Friend functions
BLOCK 4
9. Inheritance & Multiple Inheritance
10. Pointers
11. Polymorphism
12. Virtual Functions
BLOCK 5
13. Files
14. I/O Streams
Introduction
INTRODUCTION
C++ has become one of the most popular OOP languages used for developing
NOTES real-world applications. C++ is a programming language that extended from
the ubiquitous C language. It treats data as a crucial element—not allowing
it to move freely around the system. Therefore, the main emphasis in C is
on data and not on the procedure. You can design programs around the data
being operated upon in C++. An object-oriented language helps in combining
data and functions that operate on data into a single unit known as object.
C++ is used for developing different types of applications, such as real-time
systems, simulation modelling, expert systems. It also provides flexibility
to a user to introduce new types of objects in his programming on the basis
of the requirement of the application.
This lab manual, Lab: Programming in C++, contains several
programs based on C++ concepts, such as classes, inheritance, constructors
and destructors, to provide the concept of programming. In addition, it will
help students in coding and debugging their programs. The manual provides
all logical, mathematical and conceptual programs that can help to write
programs very easily in C++ language. These exercises shall be taken as the
base reference during lab activities for students of BCA. There are also many
Try Yourself Questions provided to students for implementation in the lab.
Self-Instructional
Material
Lab: Programming in C++
INTRODUCTION
When we can copy .exe file to any other computer which contain
window operating system then it works properly, because the native code of
application of operating system is same.
Self-Instructional
Material 1
Lab: Programming in C++
RECOMMENDED SYSTEM / SOFTWARE
REQUIREMENTS
NOTES 1. Intel based desktop PC of 166MHz or faster processor with at least 64
MB RAM and 100 MB free disk space.
2. Turbo C++ compiler or GCC compilers.
In this manual we have used Turbo C++. To write C++ code first we
need to open Turbo C++. For every C++ program we need to follow following
steps for writing and executing a program.
Write a program code → save your program (F2) → compile (Alt+F9)
→ Run(Ctrl +F9)
Step 1: Click on Turbo C++ from start menu or double click on Turbo C++
on desktop.
Self-Instructional
2 Material
Step 2: Click on Start Turbo C++. After clicking on Start Turbo C++ button Lab: Programming in C++
following screen will appear:
NOTES
Self-Instructional
Material 3
Lab: Programming in C++ Step 5: Compile program i.e. hello.cpp by pressing Alt+F9 keys or by using
menu option Compile → Compile:
NOTES
Step 6: Run program i.e. hello.cpp by pressing Ctrl +F9 keys or by using
menu option Run → Run.
Output:
1. Write a program that takes two numbers as input and print their
sum and average.
//Program to take two numbers as input and provides
sum and average
#include<iostream.h>
Self-Instructional
4 Material
void main() Lab: Programming in C++
{
int num1, num2, sum, avg;
cout<<”Enter two numbers”<<endl; //output statement
NOTES
cin>>num1; //input statement
cin>>num2;
sum=num1+num2;
avg=sum/2;
cout<<”Sum of two numbers “<<sum<<endl;
cout<<”Average of two numbers “<<avg;
}
Output:
Output:
Self-Instructional
Material 5
Lab: Programming in C++
Try yourself:
(i) Write a program to calculate volume of cylinder.
Volume of cylinder= PI*r*r*h.
NOTES
(ii) Write a program to calculate curved surface area of cylinder.
Curved surface area of cylinder= 2*PI*r*h
(iii) Write a program to print ASCII value of digits, uppercase and
lowercase alphabets.
#include <iostream.h>
void main()
{
int num;
cout<<”Enter a number “;
cin>>num;
if(num%2==0)
{
cout<<”Number is even “;
}
else
{
cout<<”Number is odd “;
}
}
Output:
Enter a number 2
Number is even
#include <iostream.h>
void main()
{
Self-Instructional
6 Material
int num1, num2, num3; Lab: Programming in C++
cout<<”Enter three numbers”<<endl;
cin>>num1>>num2>>num3;
NOTES
if(num1 >= num2 && num1 >= num3)
{
cout << “Largest number: “ << num1;
}
else if(num2 >= num1 && num2 >= num3)
{
cout << “Largest number: “ << num2;
}
else
{
cout << “Largest number: “ << num3;
}
}
Output:
Output:
Try yourself:
(i) Write a program to convert a lowercase alphabet to uppercase
and vice-versa.
(ii) Write a program to check whether a year is leap year or not.
(iii) Write a program to check whether a given character is uppercase
or lowercase alphabet or a digit or a special character.
#include <iostream.h>
void main()
{
int num, i;
cout<<”Enter a number: “;
cin>>num;
Self-Instructional
8 Material
Lab: Programming in C++
cout<<”Table of “<<num<<endl;
for(i=1;i<=10;i++)
{
NOTES
cout<<num*i<<endl;
}
}
Output:
Self-Instructional
Material 9
Lab: Programming in C++ Output:
NOTES
Self-Instructional
10 Material
Output: Lab: Programming in C++
Output:
Self-Instructional
Material 11
Lab: Programming in C++
Try yourself:
(i) Write a program to reverse a given number.
(ii) Write a program to check whether a number is prime or not.
NOTES
(iii) Write a program to convert binary number to decimal number.
10. Write a program that takes values in an array and also display them.
//C++ program to scan and print values using array
#include <iostreamh>
int main()
{
int arr[5],i;
cout << “Enter 5 numbers:\n “;
for(i=0;i<5;i++)
cin >> arr[i];
cout<<”\n Array values are “<<endl;
for(i=0;i<5;i++)
cout<<arr[i]<<endl;
}
Output:
Self-Instructional
12 Material
for(i=0;i<5;i++) Lab: Programming in C++
cin>>arr[i];
max=arr[0];
for(i = 1;i < 5; i++)
NOTES
{
if(max < arr[i])
max = arr[i];
}
cout<<”Largest element”<<max;
}
Output:
Self-Instructional
Material 13
Lab: Programming in C++ EXIT
ELSE IF KEY < LIST [MID] THEN
SET MAX := MID -1
NOTES ELSE
SET MIN := MID +1
[END OF IF]
[END OF LOOP]
5. IF FOUND = FALSE THEN
WRITE : VALUE IS NOT IN LIST
ELSE
WRITE VALUE FOUND AT MID LOCATION
6. END
Self-Instructional
14 Material
} Lab: Programming in C++
}
if ( flag ==1)
{
NOTES
cout<<”value found at location”<<mid +1;
}
else
cout<<”value not found”;
}
void main()
{
int arr[10],i,k;
cout<<”Enter 10 values\n”;
for(i=0;i<10;i++)
cin>>arr[i];
cout<<”Enter value to be searched “;
cin>>k;
//call of binary_Search function
binary_search(arr,10,k);
}
Output:
Self-Instructional
Material 15
Lab: Programming in C++ int temp ,i,j, min;
}
}
//main function
void main()
{
int arr[10],i;
cout<<”Enter 10 values\n”;
for(i=0;i<10;i++)
cin>>arr[i];
//call of selection sort function
selection_sort(arr,10);
cout<<” \n Sorted Values \n”;
for(i=0;i<10;i++)
cout<<endl<<arr[i];
}
Self-Instructional
16 Material
Output: Lab: Programming in C++
NOTES
void main()
{
int arr[10],i;
cout<<”Enter 10 values\n”;
for(i=0;i<10;i++)
cin>>arr[i];
Output:
Self-Instructional
18 Material
15. Write a program for quick sort. Lab: Programming in C++
#include <iostream.h>
void quick_sort (int a[ ], int first, int last)
{
int low ,high ,pivot, temp, i ;
low= first ;
high =last ;
pivot =a[(first +last)/2];
do
{
while (a[low]<pivot)
{
low++;
}
Self-Instructional
Material 19
Lab: Programming in C++ while (a [high]>pivot)
{
high--;
}
NOTES
if(low <=high)
{
temp= a [low];
a [low]= a[high];
a[high]= temp ;
low++;
high--;
}
}while (low <=high);
if (first <high)
{
quick_sort (a, first, high);
}
if(low< last)
{
quick_sort (a, low, last);
}
}
void main()
{
int arr[10],i,k;
cout<<”Enter 10 values\n”;
for(i=0;i<10;i++)
cin>>arr[i];
//call of Quick Sort function
quick_sort(arr,0,10);
cout<<” \n Sorted Values \n”;
for (i=0;i<10;i++)
cout<<endl<<arr[i];
}
Self-Instructional
20 Material
Output: Lab: Programming in C++
NOTES
#include <iostream.h>
Self-Instructional
Material 21
Lab: Programming in C++
// function to merge the two half into a sorted data.
void merge_array(int a[], int low, int high, int mid)
{
NOTES
// low to mid and mid+1 to high array are already
sorted
int i, j, k;
int temp_arr[high-low+1];
i = low;
k = 0;
j = mid + 1;
void main()
{
int arr[10],i,k;
cout<<”Enter 10 values\n”;
for(i=0;i<10;i++)
cin>>arr[i];
//call of merge sort function
merge_sort(arr, 0, 9);
cout<<” \n Sorted Values \n”;
for(i=0;i<10;i++)
cout<<endl<<arr[i];
}
Self-Instructional
Material 23
Lab: Programming in C++ Output:
NOTES
Try Yourself:
(i) Write a program to sort n numbers in descending order using
bubble sort.
(ii) Write a program to implement selection sort method using
functions.
(iii) Write a program to sort the n names in an alphabetical order.
17. Write a Program that takes string as input and print it.
//C++ program to take string as input and print it
#include <iostream.h>
#include <conio.h>
void main()
{
char str[15];
cout<<”Enter your name: “;
cin>>str;
cout<<”\nWelcome “<<str;
getch();
}
Self-Instructional
24 Material
Output: Lab: Programming in C++
Welcome Rajan
Output:
if (flag == 1)
cout<<” \n string is a palindrome”;
else
cout<<” \n string is a not palindrome”;
}
Self-Instructional
26 Material
Output: Lab: Programming in C++
NOTES
Try yourself:
(i) Write a program to insert an element in an array.
(ii) Write a program to find sum of elements of an array.
(iii) Write a program to find largest number from an array.
Self-Instructional
Material 27
Lab: Programming in C++ for ( j = 0 ; j<3 ; j++ )
{ sum[i][j] = m1[i][j]+m2[i][j];
cout << sum[i][j] << “\t”;
NOTES
}
cout<<endl;
}
}
Output:
int main()
{
int i, j, k, m1[10][10], m2[10][10], res[10][10];
cout << “Enter the elements of first matrix\n”;
for ( i = 0 ;i < 3 ; i++ )
{
cout<<”\n enter values for row “<<i+1<<endl;
Self-Instructional
28 Material
for ( j = 0 ; j<3 ; j++ ) Lab: Programming in C++
{ cin >> m1[i][j];}
}
NOTES
cout << “Enter the elements of second matrix\n”;
}
cout<<endl;
}
}
Self-Instructional
Material 29
Lab: Programming in C++ Output:
NOTES
Try yourself:
(i) Write a program to print sum of diagonal values of a square Matrix.
(ii) Write a program to find highest and lowest element of a Matrix.
(iii) Write a program to convert first letter of each word of a string to
uppercase and other to lowercase.
(iv) Write a program to find substring in string (Pattern
Matching).
Self-Instructional
30 Material
cout << “Factorial of “ << n << “ = “ << fact(n); Lab: Programming in C++
return 0;
}
NOTES
int fact(int n)
{
if(n > 1)
return n * fact(n - 1);
else
return 1;
}
Output:
#include <iostream.h>
bool leapYear (int y);
int main()
{
int y;
cout<<”Enter year: “;
cin>>y;
//Calling function
bool flag = leapYear(y);
if(flag == true)
cout<<y<<” is a leap Year”;
else
cout<<y<<” is not a leap Year”;
return 0;
}
bool leapYear(int y)
{
Self-Instructional
Material 31
Lab: Programming in C++ bool flag = false;
if (y % 4 == 0)
{
if (y % 100 == 0)
NOTES
{
if (y % 400 == 0)
{
flag = true;
}
}
else flag = true;
}
return flag;
}
Output:
Self-Instructional
32 Material
Output: Lab: Programming in C++
NOTES
#include <iostream.h>
//definition of sequential Search function
Self-Instructional
Material 33
Lab: Programming in C++ void sequential_search (int a[ ] ,int size ,int key)
{
int flag , i ;
flag =0;
NOTES
for ( i=0 ; i<size ; i++)
{
if ( a [i] == key )
{
flag = 1 ;
break ;
}
}
if ( flag == 1)
cout<<”value found at “<<i+1<<” location”;
else
cout<<”value not found”;
}
void main()
{
int arr[10],i,k;
cout<<”Enter 10 values”;
for(i=0;i<10;i++)
cin>>arr[i];
cout<<”Enter values to be searched”;
cin>>k;
//call of sequential_search function
sequential_search(arr,10,k);
}
Output:
Self-Instructional
34 Material
26. Write a program to print factorial of a number using recursive Lab: Programming in C++
function.
//C++ Program to print factorial using recursive
function
#include<iostream.h> NOTES
// Factorial Function
int factorial(int n)
{
if(n > 1)
return n * factorial(n - 1);
//recursive call of factorial function
else
return 1;
}
int main()
{
int n;
cout << “Enter a number : “;
cin >> n;
cout << “Factorial of “ << n << “ is “ << factorial(n);
return 0;
}
Output:
Self-Instructional
Material 35
Lab: Programming in C++ else
{
return (Fibonacci(n-1)+Fibonacci(n-2));
NOTES
//recursive call of Fibonacci function
}
}
int main()
{
int n,i;
Output:
INLINE FUNCTION
1. We must keep inline functions small, small inline functions have better
efficiency.
2. Inline functions do increase efficiency, but we should not make all the
functions inline. Because if we make large functions inline, it may lead
to code bloat, and might affect the speed too.
3. Hence, it is adviced to define large functions outside the class definition
using scope resolution ::operator, because if we define such functions
inside class definition, then they become inline automatically.
Self-Instructional
36 Material
4. Inline functions are kept in the Symbol Table by the compiler, and all Lab: Programming in C++
the call for such functions is taken care at compile time.
28. Write a program to demonstrate the concept of inline function.
#include <iostream.h>
NOTES
int main()
{
cout<<”\n\tThe Sum is : “ << sum(310,230);
cout<<”\n\tThe Sum is : “ << sum(145,823);
cout<<”\n\tThe Sum is : “ << sum(427,438);
}
Output:
Try yourself:
(i) Write a C++ program to find average marks of three subjects of
N students in a class.
(ii) Write a C++ program to take input of two distances in inch-feet
system and stores in data members of two structure variables.
Also, this program calculates the sum of two distances and
displays it.
(iii) Write a C++ program in which user is asked to enter two time
periods and these two periods are stored in structure variables.
The program calculates the difference between these two time
periods.
(iv) Write a C++ Program to find total salary of N employees in a
department where DA=35% basic_salary and HRA=10% of
basic_salary.
Self-Instructional
Material 37
Lab: Programming in C++ 29. Write a program to demonstrate the concept of class and object.
//C++ sample program for class and object
#include<iostream.h>
//class
NOTES
class student
{
private: //scope of variables is private
//member variables
int rno;
char name[10];
void display()
{
cout<<”\n Roll Number :”<<rno;
cout<<”\n Name :”<<name;
}
} ; //class closed
int main()
{
student obj; //object of student class
obj.input(); //call of input function
obj.display(); //call of display function
}
Output:
Self-Instructional
38 Material
30. Write a program that shows the use of this pointer. Lab: Programming in C++
#include <iostream.h>
class Demo
{
NOTES
private:
int num;
char ch;
public:
void setvalue(int num, char ch)
{
this->num =num;
this->ch=ch;
}
void putvalue()
{
cout<<num<<endl;
cout<<ch;
}
};
int main()
{
Demo obj;
obj.setvalue(450, ‘A’);
obj.putvalue();
Output:
//static function
static void function1()
{
cout << “\nResult is: “ << count<<endl;
}
//Normal function
void counter()
{
cout << “\n Counter is: “ << n<<endl;
}
//Destructor
~test ()
{
count =count-1;
}
};
int test::count=0;
int main()
{
test obj1;
//Static function is accessed using class name and
scope resolution operator (::)
test::function1();
test obj2,obj3,obj4;
test::function1();
//normal function is accessed using object name
and the dot member access operator(.)
obj1.counter();
obj2.counter();
Self-Instructional
40 Material
obj3.counter(); Lab: Programming in C++
obj4.counter();
}
Output: NOTES
#include<iostream.h>
class static_class
{
int n;
static int count; //static variable
public:
//constructor
static_class ()
{
n = ++count;
}
void obj_number()
{
cout << “\n\t Object number is :” << n;
}
static void obj_count()
{
cout << “\n Number of Objects :” << count;
}
Self-Instructional
Material 41
Lab: Programming in C++ };
int static_class::count;
NOTES
int main()
{
static_class obj1, obj2;
obj1.obj_count();
obj1.obj_number();
obj2.obj_count();
obj2.obj_number();
return 0;
}
Output:
//class
class student
{
private: //scope of variables is private
//member variables
int rno;
char name[10];
// member functions
NOTES
void input()
{
cout<<”\n Enter student roll number :”;
cin>>rno;
cout<<”\n Enter student name :”;
cin>>name;
}
void display()
{
cout<<”\n Roll Number :”<<rno;
cout<<”\n Name :”<<name;
}
} ;
int main()
{
student obj;
obj.input ();
obj.display ();
}
Output:
class student
NOTES
{
private:
//member variables
int rno;
char name[10];
public
// constructor
student()
{
cout<<”Constructor \n”;
rno=0;
}
// member functions
void input()
{
cout<<”\n Enter student roll number :”;
cin>>rno;
cout<<”\n Enter student name :”;
cin>>name;
}
void display()
{
cout<<”\n Roll Number :”<<rno;
cout<<”\n Name :”<<name;
}
//destructor
~student()
{
cout<<”\n Destructor \n”;
}
} ;
Self-Instructional
44 Material
int main() Lab: Programming in C++
{
student obj;
obj.input();
NOTES
obj.display();
}
Output:
35. Write a program to add two matrices. Create two objects of the class
and each of which refers one 2D matrix. Use constructor to allocate
memory dynamically and use copy constructor to allocate memory
when one array object is used to initialize another.
#include <iostream.h>
class matrix
{
int **a;
public:
// Dynamic Constructor
matrix()
{
int i,j;
a=new int*[3];
for(i=0; i<3; i++)
a[i]=new int[3];
cout<<”Enter elements for a 3x3 matrix:\n”;
for(i=0; i<3; i++)
for(j=0; j<3; j++)
cin>>a[i][j];
}
// Copy Constructor
matrix(matrix & x)
Self-Instructional
Material 45
Lab: Programming in C++ {
int i,j;
a=new int*[3];
for(i=0; i<3; i++)
NOTES
a[i]=new int[3];
for(i=0; i<3; i++)
for(j=0; j<3; j++)
a[i][j]=x.a[i][j];
}
// Destructor
~matrix()
{
int i;
for(i=0; i<3; i++)
delete a[i];
delete a;
}
void showdata()
{
int i,j;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
cout<<a[i][j]<<” “;
}
cout<<endl;
}
}
friend void add(matrix,matrix);
};
//main function
int main()
{
matrix obj1;
matrix obj2(obj1);
cout<<”value of Matrix 1 and Matrix 2\n”;
obj1.showdata ();
cout<<”SUM of the Matrices:\n”;
add(obj1,obj2);
}
Output:
class dyncons
{
private:
int *p;
public:
Self-Instructional
Material 47
Lab: Programming in C++ dyncons ()
{
p=new int;
*p=100;
NOTES
}
dyncons (int v)
{
p= new int;
*p=v;
}
int dis()
{
return (*p);
}};
int main()
{
dyncons obj1,obj2(50);
cout<<”the value of object obj1 p is “;
cout<<obj1.dis();
cout<<”\n the value of object of obj2 p is:”<<obj2.
dis();
Output:
Self-Instructional
48 Material
count++; Lab: Programming in C++
}
int main()
NOTES
{
cout << “Static variable “ <<endl;
for (int i=0; i<5; i++)
test();
}
Output:
Try yourself:
(i) Write a program to swap two numbers using class.
(ii) Write a program to print numbers from 1 to N using class.
(iii) Write a program to calculate area of a circle, a rectangle or a
triangle depending on input using overloaded calculate function.
class Test
{
public:
Self-Instructional
Material 49
Lab: Programming in C++ return a + b + c;
}
};
NOTES
int main()
{
Test obj;
cout<<”Sum of two integers “<<obj.sum(310,
220)<<endl;
cout<<”Sum of three integers “<<obj.sum(12, 20, 23);
Output:
Self-Instructional
50 Material
}; Lab: Programming in C++
int main()
{
Test obj;
NOTES
cout<<”Value before ++ operator \n”;
obj.display ();
++obj; // calling of operator void operator ++()
cout<<”\nValue after ++ operator \n”;
obj.display ();
Output:
Self-Instructional
Material 51
Lab: Programming in C++ cout<<value<<endl;
}
};
NOTES
int main()
{
overloading obj1,obj2,result;
int a,b;
cout<<”Enter the value of a and b:”;
cin>>a>>b;
obj1.setValue(a);
obj2.setValue(b);
result = obj1+obj2;
cout<<”Input Values:\n”;
obj1.display();
obj2.display();
cout<<”Result:”;
result.display();
Output:
class arithmetic
{
float n;
public:
void get()
{
cout<”\n enter number:\n”;
cin>>n;
Self-Instructional
52 Material
} Lab: Programming in C++
arithmetic operator +( arithmetic &a)
{
arithmetic t;
NOTES
t.n=n+a.n;
return t;
}
arithmetic operator -( arithmetic &a)
{
arithmetic t;
t.n=n-a.n;
return t;
}
arithmetic operator *( arithmetic &a)
{
arithmetic t;
t.n=n*a.n;
return t;
}
arithmetic operator /( arithmetic &a)
{
arithmetic t;
t.n=n/a.n;
return t;
}
void display()
{
cout<<n;
}
};
int main()
{
arithmetic a1,a2,a3;
a1.get();
a2.get();
a3 = a1+a2;
cout<<”\n Addition of two number:”;
a3.display();
Self-Instructional
Material 53
Lab: Programming in C++ a3 = a1-a2;
cout<<”\n Subtraction of two number:”;
a3.display();
a3 = a1*a2;
NOTES
cout<<”\n Multiplication of two number:”;
a3.display();
a3 = a1/a2;
cout<<”\n Division of two number:”;
a3.display();
}
Output:
//class
class student
{
private: //scope of variables is private
//member variables
int rno;
char name[10];
Self-Instructional
54 Material
void input() Lab: Programming in C++
{
cout<<”\n Enter student roll number :”;
cin>>rno;
NOTES
cout<<”\n Enter student name :”;
cin>>name;
}
void display()
{
cout<<”\n Roll Number :”<<rno;
cout<<”\n Name :”<<name;
}
} ; //class closed
public:
void input_data()
{
input();
//call of input function of
student class
cout<<”\n Enter Fee :”;
cin>>fee;
}
void display_data()
{
//call of display function of
student class
display();
cout<<”\n Fee :”<<fee;
}
};
Self-Instructional
Material 55
Lab: Programming in C++ int main()
{
fee obj; //object of fee class
obj.input_data();
NOTES
obj.display_data();
}
Output:
class student
{
protected:
int rno,m1,m2;
public:
void get()
{
cout<<”Enter the Roll no :”;
cin>>rno;
cout<<”Enter the two marks :”;
cin>>m1>>m2;
}
};
class sports
{
protected:
int sm; // sm = Sports mark
public:
void getsm()
Self-Instructional
56 Material
{ Lab: Programming in C++
cout<<”\nEnter the sports mark :”;
cin>>sm;
}
NOTES
};
class statement:public student,public sports
{
int tot,avg;
public:
void display()
{
tot=(m1+m2+sm);
avg=tot/3;
cout<<”\n\n\tRoll No : “<<rno<<”\n\tTotal : “<<tot;
cout<<”\n\tAverage : “<<avg;
}
};
int main()
{
statement obj;
obj.get();
obj.getsm();
obj.display();
}
Output:
Self-Instructional
Material 57
Lab: Programming in C++ 44. Write a program to demonstrate the concept of multilevel inheritance.
#include <iostream.h>
//base class
class top
NOTES
{
public :
int a;
void getdata()
{
cout<<”\n\nEnter Any Number : “;
cin>>a;
}
void putdata()
{
cout<<”\nValue is:\t”<<a;
}
};
Self-Instructional
58 Material
c=b*a; Lab: Programming in C++
cout<<”\n\nCube :\t”<<c;
}
};
NOTES
int main()
{
bottom b1;
b1.cube();
}
Output:
Try Yourself:
(i) Write a program to demonstrate the multilevel inheritance.
(ii) Write a program to demonstrate the multiple inheritance.
(iii) Write a program to demonstrate the virtual derivation of a class.
//base class
class base
{
public:
virtual void display()
{
cout << “\nThis is display method of base class”;
}
void show()
{
Self-Instructional
Material 59
Lab: Programming in C++ cout << “\nThis is show method of base class”;
}
};
NOTES
//derived class
class derived : public base
{
public:
// Overriding method - new working of
// base class’s display method
void display()
{
cout << “\nThis is display method of derived
class”;
}
};
// main function
int main()
{
derived dr;
base &bs = dr;
bs.display();
dr.show();
}
Output:
Self-Instructional
60 Material
46. Write a program using virtual function. Lab: Programming in C++
#include <iostream.h>
class base
NOTES
{
public:
virtual void show()
{
cout << “\n Base class show:”;
}
void display()
{
cout << “\n Base class display:”;
}
};
void display()
{
cout << “\n Drive class display:”;
}
void show()
{
cout << “\n Drive class show:”;
}
};
int main()
{
base obj1;
base *p;
cout << “\n\t P object points to base:\n”;
p = &obj1;
p->display();
p->show();
Self-Instructional
Material 61
Lab: Programming in C++ cout << “\n\n\t P object points to drive:\n”;
drive obj2;
p = &obj2;
p->display();
NOTES
p->show();
}
Output:
void Display3()
{
cout<<”\n\tThis is Display3() method of Base Class”;
}
Self-Instructional
62 Material
}; Lab: Programming in C++
void Display2()
{
cout<<”\n\tThis is Display2() method of Derived
Class”;
}
};
int main()
{
DerivedClass D;
D.Display1();
// This will invoke Display1()
method of Derived Class
D.Display2();
// This will invoke Display2()
method of Derived Class
D.Display3(); // This will invoke Display3()
method of Base Class
Output:
Self-Instructional
Material 63
Lab: Programming in C++
Try yourself:
(i) Write a program that overloads the + operator and relational
operators (suitable) to perform the following operations:
NOTES (a) Concatenation of two strings. (b) Comparison of two strings.
(ii) Write a programs functions to find the GCD of two given integers
using pointer.
void main ()
{
ofstream file1;
file1.open (“data.txt”);
file1 << “This is my first file.\n”;
file1.close();
getch();
}
49. Write a program to create and write on a text file.
// C++ program of writing on a text file
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
ofstream file_out;
char file_name[20];
char str [80];
clrscr ();
Self-Instructional
64 Material
file_out.open (file_name, ios::out); Lab: Programming in C++
//close file
file_out.close ();
getch ();
}
50.
Write a program to retrieve data from a text file.
// C++ program of retrieve data from a text file
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
{
ifstream file_in;
char file_name [20];
char str[80];
clrscr();
file_in.get(str, 80);
cout<<str;
file_in.close();
getch();
}
Self-Instructional
Material 65
Lab: Programming in C++ 51. Write a program to read and write on a binary file.
#include<iostream.h>
#include<fstream.h>
#include<cstdio.h>
NOTES
class Student
{
int rno;
char name[50];
public:
void setData()
{
cout << “\n Enter roll number”;
cin >>rno;
cout << “Enter name “;
cin.getline (name,50);
}
void showData()
{
cout << “\n Admission no. : “ << rno;
cout << “\n Student Name : “ << name;
}
};
file_out.close ();
}
Self-Instructional
66 Material
void display() Lab: Programming in C++
{
ifstream file_in;
file_in.open(“student.dat”, ios::binary);
NOTES
Student obj;
file_in.close ();
}
};
int main()
{
for(int i = 1; i <= 4; i++)
write_record (); //Display all records
cout << “\n List of records”;
display ();
//Search record
cout << “\n Search result”;
search (100);
//Delete record
delete_record (100);
cout << “\n Record Deleted”;
//Modify record
cout << “\n Modify Record 101 “;
modify_record (101);
return 0;
}
Self-Instructional
Material 67
Lab: Programming in C++
Try yourself:
(i) What task does the following program perform?
#include<iostream.h>
NOTES #include<fstream.h>
int main()
{
ofstream ofile;
ofile.open (“text.txt”);
ofile << “geeksforgeeks” << endl;
cout << “Data written to file” << endl;
ofile.close();
}
(ii) Write a program which copies one file to another.
(iii) Write a program to that counts the characters, lines and words in
the text file.
Self-Instructional
68 Material
.emaN e1.sruIncrease
oC eht fothe
ezifont
s tnosize
f ehof
t esthe
aerCourse
cnI .1 Name.
.egaP revoC e2.ht nuse
i rethe
daefollowing
h a sa gniwasolaloheader
f eht esin
u the
.2 Cover Page.
YTISREVINUALAGAPPA
APPAGALAUNIVERSITY
B.C.A. elcyC drihT eht ni )46.3:APGC( CA[Accredited
AN yb edarG
]CGU-DRHM yb ytisrevinU I–yrogeand
300 036 – IDUKIARA
KARAIKUDI
K
with
’+A’’A+’
taC Graded
htiw
sa dedaras
– 630 003
Grade
detidby
ercNAAC
cA[ (CGPA:3.64) in the Third Cycle
G Category–I
dna University by MHRD-UGC]
B.C.A.
101 24
itnem sYou
a egaare
p reinstructed
voc eht etatodpupdate
u ot dethe
tcurcover
tsni erpage
a uoYas mentioned below:
.emaN e1.sruIncrease
oC eht fothe
ezifont
s tnosize
f ehof
t esthe
aerCourse
cnI .1 Name.
aP revoC e2.ht nuse
i rethe
daefollowing
h a sa gniwasolaloheader
f eht esin
u the
.2 Cover Page.
ISREVINUALAGAPPA
APPAGALAUNIVERSITY
rihT eht ni )46.3:APGC( CA[Accredited
AN yb edarGwith
’+A’’A+’
htiwGrade
detidby
ercNAAC
cA[ (CGPA:3.64) in the Third Cycle
]CGU-DRHM yb ytisrevinU I–yrogeand
taC Graded
sa dedarasG Category–I
dna University by MHRD-UGC]
300 036 – IDUKIARA
KARAIKUDI
TACUDE ECNATSIDDIRECTORATE
K
FO ETAROTCEOF
– 630 003
RIDDISTANCE EDUCATION
LAB: PROGRAMMING IN C++
II - Semester