SlideShare a Scribd company logo
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 1 P a g e
1. write a program to generate following pattern:-
(a) A B C D E F G
A B C E F G
A B F G
A G
CODING :-
#include<iostream.h> //header file
#include<conio.h>
int main() //main function
{
clrscr();
char i,j,k,l,n='D'; //variable declaration
k = n; //assigning value of k in "n"
l = n;
for(i='A';i<='D';i++) //Outer for loop execution
{
for(j='A';j<='G';j++) //inner for loop execution
{
if(j>k && j<l) //If statement
cout<<" ";
else
cout<<j;
}
k --;
l ++;
cout<<endl;
}
getch();
return 0 ;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 2 P a g e
(b) 1
1 2
1 2 3
CODING :-
#include<iostream.h> //header file
#include<conio.h>
int main() //main function
{
clrscr();
int i,j; //variable declaration
for(i=1;i<=3;i++) //Outer for loop execution
{
for(j=1;j<=i;j++) //inner for loop execution
{
cout<<j; //Printing value of “j”
}
cout<<endl;
}
getch() ;
return 0;
}
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 3 P a g e
OUTPUT :-
(c) *
* *
* * *
CODING :-
#include<iostream.h> //header file
#include<conio.h> //header file
int main () //main function
{
int i ,j , k ; //variable declaration and initialization
clrscr (); //clear the screen funtion
for(i=1;i<=3;i++) //for loop execution
{
for(int k=3-i;k>0;k--)
{
cout<<" " ;
}
for(int j=1;j<=i;j++)
{
cout<<" * " ;
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 4 P a g e
}
cout<<endl;
}
getch();
return 0;
}
OUTPUT :-
(d) 1
121
1331
14641
CODING :-
#include<iostream.h> //header file
#include<conio.h>
#include<math.h>
int main() //main function
{
clrscr();
int i , p=1; //variable declaration
cout<<endl<<p;
for(i=2;i<=4;i++) //For loop execution
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 5 P a g e
{
p = pow(11,i); //liberary function
cout<<endl<<p;
}
getch();
return 0;
}
OUTPUT :-
2. Write member functions which when called ask pattern type:
if user enters 11 then a member function is called which
generates first pattern using for loop. If user enters 12 then
a member function is called which generates first pattern
using while loop. If user enters 13 then a member function
is called which generates second pattern using for loop and
so on.
CODING :-
#include<iostream.h> //header file
#include<conio.h>
class PatternGenerator //class definition
{
public: //visibility mode
void generatePattern() //member function
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 6 P a g e
{
int patternType; //variable declaration
clrscr();
cout << "Enter pattern type 11, 12, 13 : ";
cin >> patternType;
switch (patternType) //switch statement
{
case 11:
generatePatternUsingForLoop(0);
break;
case 12:
generatePatternUsingWhileLoop(1);
break;
case 13:
generatePatternUsingForLoop(2);
break;
default:
cout << "Invalid pattern type." << endl;
}
getch(); // Wait for a key press before exiting
}
private: //visibility mode
void generatePatternUsingForLoop(int patternNumber)
//member function definition
{
char i,j,k,l,n='D'; //variable declaration
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 7 P a g e
k = n; //assigning value of k in "n"
l = n;
for(i='A';i<='D';i++) //Outer for loop execution
{
for(j='A';j<='G';j++) //inner for loop execution
{
if(j>k && j<l) //If statemnet
cout<<" ";
else
cout<<j;
}
k --;
l ++;
cout<<endl;
}
}
void generatePatternUsingWhileLoop(int patternNumber)
//member function definition
{
int i,j; //variable declaration
for(i=1;i<=4;i++) //Outer for loop execution
{
for(j=1;j<=i;j++) //inner for loop execution
{
cout<<j;
}
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 8 P a g e
cout<<endl;
}
}
};
int main() //main function
{
PatternGenerator patternGen; //declaration of
class object
patternGen.generatePattern(); //calling function of
class through object
getch();
return 0;
}
OUTPUT :-
3. Write a program to display number 1 to 10 in octal, decimal and hexa-
decimal system.
CODING :-
#include <iostream.h> //header file
#include <conio.h> //header file
#include <iomanip.h>
int main() //main function
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 9 P a g e
{
clrscr(); //clear the screen function
cout << "DecimaltOctaltHexadecimal" << endl; //printing
statement
for (int i = 1; i <= 10; i++) //for loop execution
{
cout << dec << i << "t" << oct << i << "t" << hex << i << endl;
}
getch(); //holding the screen
return 0;
}
OUTPUT :-
P.T.O.
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 10 P a g e
4. Write program to display number from one number system to
another number system. The program must ask for the number
system in which you will input integer value then the program
must ask the number system in which you will want output of
the input number after that you have to input the number in
specified number system and program will give the output
according to number system for output you mentioned earlier.
CODING :-
#include <iostream.h> //header file
#include <conio.h> //header file
#include <iomanip.h> //header file
#include <math.h>
long decimalToBinary(long decimalNum) // Function to
convert from decimal to binary
{
long binaryNum = 0, remainder, base = 1; //variable declaration
while (decimalNum > 0) //while loop execution
{
remainder = decimalNum % 2;
binaryNum = binaryNum + remainder * base;
decimalNum = decimalNum / 2;
base = base * 10;
}
return binaryNum;
}
char* decimalToHexadecimal(long decimalNum) //Function to convert
decimal to hexadecimal
{
char hexadecimalNum[20]; //variable declaration
int index = 0;
while (decimalNum > 0) //while loop execution
{
int remainder = decimalNum % 16;
if (remainder < 10) //if statement
{
hexadecimalNum[index++] = remainder + '0';
}
else
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 11 P a g e
{
hexadecimalNum[index++] = remainder - 10 + 'A';
}
decimalNum = decimalNum / 16;
}
hexadecimalNum[index] = '0';
int start = 0;
int end = index - 1;
while (start < end) //while loop execution
{
char temp = hexadecimalNum[start];
hexadecimalNum[start] = hexadecimalNum[end];
hexadecimalNum[end] = temp;
start++;
end--;
}
return hexadecimalNum;
}
int main() //main function
{
clrscr(); //clear the screen function
int inputBase, outputBase; //variable declaration
long inputNumber, outputNumber;
cout << "Enter the input number system (2 for binary, 10 for decimal,
16 for hexadecimal): ";
cin >> inputBase;
cout << "Enter the output number system (2 for binary, 10 for decimal,
16 for hexadecimal): ";
cin >> outputBase;
if (inputBase != 2 && inputBase != 10 && inputBase != 16) //if
statement
{
cout << "Invalid input number system." << endl;
}
else if (outputBase != 2 && outputBase != 10 && outputBase != 16)
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 12 P a g e
{
cout << "Invalid output number system." << endl;
}
else {
cout << "Enter the number in the input number system: ";
cin >> inputNumber;
if (inputBase == 2 && outputBase == 10) //if statement
{
outputNumber = 0;
int bitPosition = 0;
while (inputNumber > 0) //while loop
execution
{
int digit = inputNumber % 10;
outputNumber += digit * pow(2, bitPosition);
inputNumber /= 10;
bitPosition++;
}
cout << "Output in decimal: " << outputNumber << endl;
}
else if (inputBase == 10 && outputBase == 2)
{
outputNumber = decimalToBinary(inputNumber);
cout << "Output in binary: " << outputNumber << endl;
}
else if (inputBase == 16 && outputBase == 10)
{
outputNumber = 0;
int hexLength = 0;
char hexChar;
while (inputNumber > 0) //while loop execution
{
hexChar = inputNumber % 10;
if (hexChar >= '0' && hexChar <= '9') //if
statement
{
outputNumber += (hexChar - '0') * pow(16, hexLength);
}
else if (hexChar >= 'A' && hexChar <= 'F')
{
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 13 P a g e
outputNumber += (hexChar - 'A' + 10) * pow(16,
hexLength);
}
else
{
cout << "Invalid hexadecimal digit." << endl;
return 1;
}
inputNumber /= 10;
hexLength++;
}
cout << "Output in decimal: " << outputNumber << endl;
}
else if (inputBase == 10 && outputBase == 16)
{
char* hexadecimalNum =
decimalToHexadecimal(inputNumber);
cout << "Output in hexadecimal: " << hexadecimalNum <<
endl;
}
else
{
cout << "Conversion between these number systems is not
supported." << endl;
}
}
getch(); // Wait for a key press before exiting
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 14 P a g e
P.T.O.
B
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 15 P a g e
ARRAY
5. Write a program using function to add, subtract and multiply
two matrices of order 3*3. You have to create one function for
addition, which accepts three array arguments. First two array
arguments are matrices to add and third matrix is destination
where the resultant of addition of first two matrices is stored. In
similar way create functions for matrix subtraction and
multiplication.
CODING :-
#include <iostream.h> //header file
#include<conio.h>
void add(int arr1[3][3], int arr2[3][3]) //Function to add arrays.
{
int arr3[3][3]; //array variable declaration
cout <<"Sum of array -n";
for (int i = 0; i < 3; i++) //outer for loop execution
{
for (int j = 0; j < 3; j++) //inner for loop
{
arr3[i][j] = arr1[i][j] + arr2[i][j]; //performing addition
operation
cout << arr3[i][j] << "t"; //printing addition of 2
arrays
cout << endl;
}
}
void subt(int arr1[][3], int arr2[][3]) //Function for subtracting
arrays.
{
int arr3[3][3]; //array variable declaration
cout << "Subtraction of array -n";
for (int i = 0; i < 3; i++) //outer for loop execution
{
for (int j = 0; j < 3; j++) //inner for loop
{
arr3[i][j] = arr1[i][j] - arr2[i][j]; //performing subtraction
operation
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 16 P a g e
cout << arr3[i][j] << "t"; //printing subtraction of
2 arrays
}
cout << endl;
}
}
void multi(int arr1[][3], int arr2[][3]) //Function to multiply arrays.
{
int arr3[3][3];
cout << "Multiplication of array -n";
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
arr3[i][j] = arr1[i][j] * arr2[i][j];
cout << arr3[i][j] << "t";
}
cout << endl;
}
}
int main() //main function
{
clrscr();
int i,j;
int arr1[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; //Array declaration
& initialization
int arr2[3][3] = {9, 8, 7, 6, 5, 4, 3, 2, 1};
cout<<"First Array is - "<<endl;
for(i=0;i<3;i++) //outer for loop
{
for(j=0;j<3;j++) //inner for loop
{
cout<<"t"<<arr1[i][j]; //printing array 1
elements
}
cout<<endl;
}
cout<<"Second Array is - "<<endl;
for(i=0;i<3;i++) //outer for loop
{
for(j=0;j<3;j++) //inner for loop
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 17 P a g e
{
cout<<"t"<<arr2[i][j]; //printing array 2
elements
}
cout<<endl;
}
add(arr1, arr2); //add function call
cout << endl;
subt(arr2, arr1); //subt function call
cout << endl;
multi(arr1, arr2); //multi function call
getch();
return 0;
}
OUTPUT :-
6. create a single program to perform following tasks without
using library functions:
a) To reverse the string accepted as argument :-
CODING :-
#include <iostream.h> //header file
#include <conio.h>
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 18 P a g e
int main() //main function
{
clrscr();
char str[100]; //variable declaration
cout << "Enter a string: ";
cin>>str; //read the value entered by the user
int length = 0; //variable declaration
while (str[length] != '0') // Calculate the length of the string
using while loop
{
length++;
}
for (int i = 0, j = length - 1; i < j; i++, j--) // Reverse the string using for
loop
{
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
cout << "Reversed string: " << str << endl;
getch(); // hold the screen
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 19 P a g e
b) To count the number of characters in string passed as
argument in form of character array.
CODING :-
#include <iostream.h> //header file
#include <conio.h>
int main() //main function
{
clrscr();
char str[100]; //variable declaration
cout << "Enter a string: ";
cin>>str; //read input by the user
int count = 0;
// Count characters in the string
while (str[count] != '0') //while loop execution
{
count++;
}
cout << "Number of characters in the string: " << count << endl;
getch();
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 20 P a g e
c) To copy the one string to other string passed as arguments in
form of source character array and destination character array
without using library function.
CODING :-
#include <iostream.h> //header file
#include <conio.h>
int main() //main function
{
clrscr();
char source[100], copy[100]; //variable declaration
cout << "Enter a string: ";
cin>>source;
// Copy the source string to the destination string without using library
functions
int i = 0;
while (source[i] != '0') //while loop execution
{
copy[i] = source[i];
i++;
}
copy[i] = '0';
cout << "Source string: " << source << endl;
cout << "Copied string: " <<copy<< endl;
getch();
return 0;
}
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 21 P a g e
OUTPUT :-
d) To count no. of vowels, consonants in each word of a
sentence passed as argument in form of character array.
CODING :-
#include <iostream.h> //header file
#include<conio.h>
int main() //main function
{
clrscr();
char line[150]; //variable declaration
int vowels, consonants, digits, spaces; //variable declaration
vowels = consonants = digits = spaces = 0;
cout << "Enter a line of string: ";
cin.getline(line, 150); //read line or sentence given by the
user
for(int i = 0; line[i]!='0'; ++i) //for loop execution
{
if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u' ||
line[i]=='A' ||
line[i]=='E' || line[i]=='I' || line[i]=='O' || line[i]=='U') //if statement
{
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 22 P a g e
++vowels;
}
else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
{
++consonants;
}
else if(line[i]>='0' && line[i]<='9')
{
++digits;
}
else if (line[i]==' ')
{
++spaces;
}
}
cout << "Vowels: " << vowels << endl;
cout << "Consonants: " << consonants << endl;
cout << "Digits: " << digits << endl;
cout << "White spaces: " << spaces << endl;
getch();
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 23 P a g e
CLASS, OBJECT, ARRAY OF OBJECT, OBJECT
USING ARRAY
7. Create a class student having data members to store roll number, name of
student, name of three subjects, max marks, min marks, obtained marks.
Declare an object of class student. Provide facilities to input data in data
members and show result of student.
CODING :-
#include <iostream.h> //header file
#include <conio.h>
#include <stdio.h>
class Student //Class Definition
{
private: //Access specifier
int rollNumber; //variable Declaration
char name[50];
char subjects[3][50];
int maxMarks[3];
int minMarks[3];
int obtainedMarks[3];
public: //Access Specifier
void input() //Member function Definition inside the class
{
cout << "Enter Roll Number: ";
cin >> rollNumber;
cout << "Enter Student Name: ";
gets(name);
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 24 P a g e
for (int i = 0; i < 3; i++) //For Loop Execution
{
cout << "Enter Name of Subject " << i + 1 << " - ";
gets(subjects[i]);
cout << "Enter Max Marks for Subject " << i + 1 << " - ";
cin >> maxMarks[i];
cout << "Enter Min Marks for Subject " << i + 1 << " - ";
cin >> minMarks[i];
cout << "Enter Obtained Marks for Subject " << i + 1 << " - ";
cin >> obtainedMarks[i];
}
}
void show(); //member function declaration
};
void Student::show() //Function Definion outside the Class
{
clrscr(); // Clear the screen
cout << "ttt -: Student Details :- "<<endl;
cout << "Roll Number: " << rollNumber << endl;
cout << "Student Name: " << name << endl;
for (int i = 0; i < 3; i++) //For Loop Execution
{
cout << "Subject " << i + 1 << " Name: " << subjects[i] << endl;
cout << "Max Marks for Subject " << i + 1 << " = " << maxMarks[i] << endl;
cout << "Min Marks for Subject " << i + 1 << " = " << minMarks[i] << endl;
cout << "Obtained Marks for Subject " << i + 1 << " = " << obtainedMarks[i]
<< endl;
}
}
int main() //Main Function
{
clrscr(); // Clear the screen
Student s1; //object Declaration of "Student" class
s1.input(); //Accessing Class's member function through object
s1.show(); // Show data
getch();
return 0;
}
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 25 P a g e
OUTPUT :-
P.T.O.
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 26 P a g e
8. Create a class student having data members to store roll number,
name of student, name of three subjects, max marks, min marks,
obtained marks. Declare array of object to hold data of 3 students.
Provide facilities to show result of all students. Provide also facility
to show result of specific student whose roll number is given.
CODING :-
#include <iostream.h> //header file
#include <conio.h>
class student //class definition
{
int rollno, maxm, minm, obtm; //data member
char name[50], subnm[3];
public : //access specifier
void get() //member function
{
cout <<endl<< "Enter Roll Number = ";
cin >> rollno;
cout << "Enter student Name = ";
cin.getline(name,50);
cin.ignore();
cout <<endl<< "Enter name of subjects - ";
for (int i = 0; i < 3; i++) //for loop execution
{
cin.ignore();
cout << "Subject " << i + 1 << " = ";
getline(cin, subnm[i]);
}
cout <<endl<< "Enter maximum marks = ";
cin >> maxm;
cout <<endl<< "Enter minimum marks = ";
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 27 P a g e
cin >> minm;
cout <<endl<< "Enter obtained marks = ";
cin >> obtm;
}
void disp()
{
cout << endl<< "Student Details!!!nn";
cout << "Roll Number = " << rollno << endl;
cout << "Student Name = " << name << endl;
cout << "Subject details - "<<endl;
for (int i = 0; i < 3; i++)
{
cout << "Subject " << i + 1 << " : " << subnm[i] << endl;
}
cout << "Result - "<<endl<<endl;
cout << "Maximum marks = " << maxm <<endl<< “Max marks = " << minm <<endl<<
"Obtainde
marks = " << obtm;
}
};
int main() //main function
{
int a = 1;
student s1[3]; //Initializing array of objects
do
{
cout << "Enter 1 - To see all student's result "<<endl;
cout << "Enter 2 - To see any specific student's result”<<endl<<”Enter 0 - To
exit”<<end<<”Value here = ";
cin >> a;
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 28 P a g e
if (a == 1)
{
cout << "nEnter details of the students -n";
for (int i = 0; i < 3; i++)
{
s1[i].get();
s1[i].disp();
}
}
else if (a == 2)
{
int rln;
cout << "Enter the roll number from 100 to 102 = ";
cout <<endl<< "Enter details of the students -"<<endl;
cin >> rln;
switch (rln) //Using switch case
{
case 100:
s1[0].get();
s1[0].disp();
break;
case 101:
s1[1].get();
s1[1].disp();
break;
case 102:
s1[2].get();
s1[2].disp();
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 29 P a g e
break;
default:
cout << "Invalid Roll number...";
break;
}
}
}
while (a!= 0);
cout << endl;
getch();
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 30 P a g e
9. Create a class Sarray having an array of integers having 5 elements
as data member provide following facilities:
a) Constructor to get number in array elements
b) Sort the elements
c) Find largest element
CODING :-
#include<iostream.h> //header file
#include<conio.h>
class Sarray //Class Definition
{
private: //Access Specifier
int arr[5]; //Data Member
public:
Sarray() // Constructor to initialize the array elements
{
for (int i = 0; i < 5; i++) //For Loop Execution
{
cout << "Enter element " << i + 1 << ": ";
cin >> arr[i];
cout<<endl;
}
}
void sort() // sort the array elements
{
for (int i = 0; i < 4; i++) //Outer For loop Execution
{
for (int j = i + 1; j < 5; j++) //inner For Loop
{
if (arr[i] > arr[j]) //If Statement
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 31 P a g e
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
int findlrg() // find the largest element
{
int largest = arr[0];
for (int i = 1; i < 5; i++) //For loop Execution
{
if (arr[i] > largest) //if Statement
{
largest = arr[i];
}
}
return largest;
}
void show() // show the array elements
{
for (int i = 0; i < 5; i++) //For loop
{
cout << arr[i] << " ";
}
cout << endl;
}
};
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 32 P a g e
int main() //Main Function
{
Sarray sarr ; //Object Declaration of Class Sarray
cout << "Unsorted array: ";
sarr.show(); //Calling class member function through Object
sarr.sort();
cout << "Sorted array: ";
sarr.show();
int largest = sarr.findlrg(); //Variable initialization through Object
cout << "Largest element: " << largest << endl;
getch();
return 0;
}
OUTPUT :-
STATIC MEMBER FUNCTION
10.Create a class Simple with static member functions for following
tasks :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 33 P a g e
a) To find fact by recursive member function.
CODING :-
#include <iostream.h> //header file
#include<conio.h>
class Simple //Class Definition
{
public : //Access Specifier
static int fact(int n) //Static Member Function definition
{
if (n == 0 || n == 1) //if else statement
{
return 1;
}
else
{
return n * fact(n - 1);
}
}
};
int main() //Main Function
{
clrscr();
int num; //variable declaration
cout<<"Enter a number : ";
cin >> num;
int factValue = Simple::fact(num); //assigns the value returned by the fact()
cout<<"Factorial of " << num << " is - " << factValue << endl;
getch();
return 0;
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 34 P a g e
}
OUTPUT :-
b) To check whether a no. is prime or not.
CODING :-
#include<iostream.h> //header file
#include<conio.h>
class findprime //Class Definition
{
public : //Access Specifier
static void prime(int a) //Static Member function
{
int b = 0;
for (int i = 2; i < a; i++) //For Loop Execution
{
if (a%i==0) //if else statement
{
b++;
}
}
if (b==0)
{
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 35 P a g e
cout<<a<<" is a prime number"<<endl;
}
else //else statement
{
cout<<a<<" is not a prime number"<<endl;
}
}
};
int main() //main function
{
clrscr();
int l; //variable initialization
cout<<"enter any number";
cin>>l;
findprime::prime(l); //calling Static member function
getch();
return 0;
}
OUTPUT :-
c) To generate Fibonacci series up to requested terms.
CODING :-
#include <iostream.h> //header file
#include<conio.h>
class fibonacci //class definition
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 36 P a g e
{
public: //Access Specifier
static void fibo() //Static Member Function
{
int n,a=0,b=1,c,i=0; //variable initialization
cout<<"Enter number of terms = ";
cin>>n;
cout<<"Fibonaci series of "<<n<<" term are :- "<<endl<<a<<" "<<b<<" ";
while (i<n-2) //While Loop execution
{
c = a+b;
cout<<c<<" ";
a = b;
b = c;
i++; //Increment Operator
}
}
};
int main() //Main Function
{
clrscr();
fibonacci::fibo(); //Calling static member-function
cout << endl;
getch();
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 37 P a g e
OBJECT AS ARGUMENT TO FUNCTION ,
FUNCTION RETURNING OBJECT
11. Write program using class having class name Darray. Darray has
pointer to pointer to integer as data member to implement double
dimension dynamic array and provide following facilities:
a) Constructor to input values in array elements
b) Input member function to get input in array element
c) Output member function to print element value
d) Add member function to perform matrix addition using objects
e) Subtract member function to perform matrix subtraction using
objects
f) Multiply member function to perform matrix multiplication using
objects .
CODING :-
#include<iostream.h> //header file
#include<conio.h>
class Darray //Class definition
{
protected: //access specifier
int a,*ptr = &a,**ptr1 = &ptr; //Pointers declaration &
initialization
int *arr,*arr1;
public: //Access Specifier
Darray() //Default Constructor Definition
{
cout<<"Enter the number of rows = ";
cin>>**(ptr1);
arr = new int[a * 3];
cout<<"Enter the values in array - "<<endl;
for (int i = 0; i < a; i++) //outer for loop execution
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 38 P a g e
{
for (int j = 0; j < 3; j++) //Inner for loop execution
{
cin>>*(arr + i*3 + j);
}
}
}
void input() //Input member function
{
cout<<"Enter the number of rows = ";
cin>>**(ptr1);
arr1 = new int[a * 3]; //Dynamic memory allocation
cout<<"Enter the values in array - "<<endl;
for (int i = 0; i < a; i++) //outer for loop execution
{
for (int j = 0; j < 3; j++) //inner for loop execution
{
cin>>*(arr1 + i*3 + j);
}
}
}
void output() //Output member function
{
cout<<"Elements in first array -”<<endl;
for (int i = 0; i < a; i++) //outer for loop
{
for (int j = 0; j < 3; j++) //inner for loop
{
cout<<*(arr + i*3 + j)<<"t";
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 39 P a g e
}
cout<<endl;
}
cout<<"Elemnets in second array -”<<endl;
for (int i = 0; i < a; i++) //outer for loop
{
for (int j = 0; j < 3; j++) //inner for loop
{
cout<<*(arr1 + i*3 + j)<<"t";
}
cout<<endl;
}
}
void add() //add member function
{
cout<<"Sum of first & second matrix -”<<endl;
for (int i = 0; i < a; i++) //outer for loop
{
for (int j = 0; j < 3; j++) //inner for loop
{
cout<<(*(arr + i*3 + j) + *(arr1 + i*3 + j))<<"t";
}
cout<<endl;
}
}
void subtract() //subtract member
function
{
cout<<"Subtraction of first matrix from second matrix -”<<endl;
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 40 P a g e
for (int i = 0; i < a; i++) //outer for loop
{
for (int j = 0; j < 3; j++) //inner for loop
{
cout<<(*(arr + i*3 + j) - *(arr1 + i*3 + j))<<"t";
}
cout<<endl;
}
}
void multiply() //multiply member function
{
int res[3][3] = 0;
cout<<"Multiplication of first & second matrix -”<<endl;
for (int i = 0; i < a; i++) //outer for loop
{
for (int j = 0; j < 3; j++) //inner for loop
{
res[i][j]=0;
for (int k = 0; k < 3; k++)
{
res[i][j] += (*(arr + i*3 + k)) * (*(arr1 + k*3 + j));
}
cout<<res[i][j]<<"t";
}
cout<<endl;
}
}
};
int main() //main function
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 41 P a g e
{
Darray D1; //Object declaration of class “Darray”
D1.input(); //calling member function through object
D1.output(); //calling member function through
object
D1.add(); //calling member function through object
D1.subtract(); //calling member function through
object
D1.multiply(); //calling member function through
object
cout << endl;
getch(); //Hold the Console
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 42 P a g e
12.Write a program to create class complex having data members to
store real and imaginary part. provide following facilities:
a. Add two complex no. using objects
b. Subtract two complex no. using objects
c. Multiply two complexes no. using objects
d. Divide two complex no. using objects
CODING :-
#include<iostream.h> //header file
#include<conio.h> //header file
class Complex //class Definition
{
private: //Access specifier
float real; //Data member
float imgn; //Data Member
public: //access specifier
Complex(float r = 0, float i = 0) : real(r), imgn(i) //Constructor to initialize the complex
number
{
}
Complex add(const Complex& c) // Function to add two complex
numbers
{
return Complex(real + c.real, imgn + c.imgn);
}
Complex subtract(const Complex& c) // Function to subtract two complex
numbers
{
return Complex(real - c.real, imgn - c.imgn);
}
Complex multiply(const Complex& c) // Function to multiply two complex
numbers
{
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 43 P a g e
return Complex((real * c.real) - (imgn * c.imgn), (real * c.imgn) + (imgn * c.real));
}
Complex divide(const Complex& c) // Function to divide two complex numbers
{
float denominator = (c.real * c.real) + (c.imgn * c.imgn);
if (denominator == 0) //if statement
{
cout << "Division by zero is undefined." << endl;
return Complex();
}
return Complex(((real * c.real) + (imgn * c.imgn)) / denominator, ((imgn * c.real) - (real
* c.imgn)) / denominator);
}
void display() //display member Function
{
cout << "Complex number: " << real << " + " << imgn << "i" << endl;
}
};
int main() //main function
{
clrscr(); //clear screen function
Complex c1(1, 3); //class object declaration and
initialization
Complex c2(2, 4);
Complex sum = c1.add(c2); //calling member function of class through
object
Complex difference = c1.subtract(c2);
Complex product = c1.multiply(c2);
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 44 P a g e
Complex quotient = c1.divide(c2);
cout <<" Sum :- "<<endl; // Displaying results
sum.display();
cout <<endl<<" Difference :- "<<endl;
difference.display();
cout <<endl<<" Multiplication :- "<<endl;
product.display();
cout <<endl<<" Division :- "<<endl;
quotient.display();
getch();
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 45 P a g e
Friend Function
13. Create class Polar having data member radius and angle. It
contains member functions taking input in data members and
member function for displaying value of data members. Class Polar
contains declaration or friend function add which accepts two
objects of class Polar and returns object of class Polar after addition.
Test the class using main function and objects of class Polar.
CODING :-
#include <iostream.h> //header file
#include<conio.h> //header file
class polar //class definition
{
int radius , angle; //Data members
public: //Access Specifier
void get() //member function
{
cout<<"Enter radius = " ;
cin>>radius ;
cout<<"Enter angle = " ;
cin>>angle ;
}
void put() //member function
{
cout<<endl<<"Radius = "<<radius;
cout<<endl<<"Angle = "<<angle<<endl;
}
friend polar add(polar , polar); //Friend function declaration
};
polar add(polar a , polar b) //Friend Function definition
{
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 46 P a g e
polar c; //variable Declaration
c.radius = a.radius + b.radius;
c.angle = a.angle + b.angle;
return c;
}
int main() //Main Function
{
polar a , b , c; // Object Declaration of class “Polar”
clrscr();
cout<<"Enter 1 st object -"<<endl;
a.get(); //Accessing member function of class through
object
cout<<endl<<"Enter 2 nd object -"<<endl;
b.get(); //Accessing member function of class through object
cout<<endl<<"Object's values are :-"<<endl;
cout<<"1st obj :-";
a.put(); //Accessing member function of class through object
cout<<endl<<"2nd obj :-";
b.put(); //Accessing member function of class through object
cout<<endl<<"-: Additon of objects :- ";
c = add(a,b); //Adding two objects
c.put();
getch();
return 0;
}
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 47 P a g e
OUTPUT :-
14.Write program to create class distance having data members feet
and inch (A single object will store distance in form such as 5 feet 3
inch). It contains member functions for taking input in data members
and member function for displaying value of data members. Class
Distance contains declaration of friend function add which accepts
two objects of class Distance and returns object of class Distance
after addition. Class Distance contains declaration of another friend
function. Subtract that accepts two objects of class Distance and
returns object of class Distance after subtraction. Test the class
using main function and objects of class Distance.
CODING :-
#include <iostream.h> //header file
#include<conio.h>
class Distance //class definition
{
int feet; //data member
int inch;
public: //access specifier
void inputData() //member function
{
cout << "Enter feet: ";
cin >> feet;
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 48 P a g e
cout << "Enter inches: ";
cin >> inch;
}
void displayData() //member function definition
{
cout << "Distance: " << feet << " feet, " << inch << " inches" << endl;
}
friend Distance add(Distance d1, Distance d2); //friend function
declaration
friend Distance subtract(Distance d1, Distance d2);
};
Distance add(Distance d1, Distance d2) //friend function
definition
{
Distance d3;
d3.feet = d1.feet + d2.feet;
d3.inch = d1.inch + d2.inch;
if (d3.inch >= 12) //if statement
{
d3.feet++;
d3.inch -= 12;
}
return d3;
}
Distance subtract(Distance d1, Distance d2) //friend function
definition
{
Distance d3;
d3.feet = d1.feet - d2.feet;
if (d1.inch < d2.inch) //if statement
{
d3.feet--;
d3.inch = 12 + d1.inch - d2.inch;
}
else
{
d3.inch = d1.inch - d2.inch;
}
return d3;
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 49 P a g e
}
int main() //main function
{
Distance d1, d2, d3, d4; /object declaration
cout << "Enter data for first distance:" << endl;
d1.inputData(); //calling member function through object
cout << "Enter data for second distance:" << endl;
d2.inputData();
cout << "First distance: ";
d1.displayData();
cout << "Second distance: ";
d2.displayData();
d3 = add(d1, d2);
cout << "Sum of distances: ";
d3.displayData();
d4 = subtract(d1, d2);
cout << "Difference of distances: ";
d4.displayData();
getch();
return 0;
}
OUTPUT :-
15.Write a program to create class Mother having data member to store
salary of Mother, create another class Father having data member to
store salary of Father. Write a friend function, which accepts objects
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 50 P a g e
of class Mother, and Father and prints Sum of Salary of Mother and
Father objects.
CODING :-
#include <iostream.h> //header file
#include<conio.h>
class father; //Forward declaration
class mother //class definition
{
int sal; //data member
friend int sum(mother,father); //Friend function declaration
};
class father
{
int sal;
friend int sum(mother,father);
};
int sum(mother a,father b) //friend Function to sum & print salary
{
a.sal = 100000;
b.sal = 200000;
cout<<"Sum of salary of mother and father = "<<a.sal + b.sal;
}
int main() //main function
{
mother m; //object declaration
father f;
sum(m,f); //Sum function called
getch();
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 51 P a g e
Friend Class
16. Write a Program to create class Mother having data member to store
salary of Mother, create another class Father having data member to
store salary of Father. Declare class Father to be friend class of
Mother. Write a member function in Father, which accepts object of
class Mother and Father Objects. Create member function in each
class to get input in data member and to display the value of data
member.
CODING :-
#include <iostream.h> //header file
#include<conio.h>
class mother //class definition
{
int slry; //data member
friend class father; //Friend class declaration
public: //access specifier
void get() //member function
{
cout<<"Enter the salary - ";
cin>>slry;
cout<<"Salary of Mother = "<<slry;
}
};
class father //friend class Definition
{
int slry;
public: //access specifier
void get() //member function
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 52 P a g e
{
cout<<endl<<endl<<”Father -”<<endl<<"Enter the salary - ";
cin>>slry;
cout<<"Salary of father = "<<slry;
}
int sum(mother a,father b) //sum member function
{
cout<<endl<<endl<<"Sum of salary of mother and father = "<<a.slry + b.slry;
return 0;
}
};
int main() //main function
{
clrscr();
mother mtr; //declaration of class “mother” object “mtr”
father ftr; //declaration of class “mother” object “mtr”
mtr.get(); //calling member function through object
ftr.get(); //calling member function through object
ftr.sum(mtr,ftr); //calling member function through object
getch();
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 53 P a g e
STATIC DATA MEMBER
17. Create a class Counter having a static data member, which keeps
track of no. of objects created of type Counter. One static member
function must be created to increase value of static data member as
the object is created. One static member function must be created to
decrease value of static data member as the object is destroyed.
One static member function must be created to display the current
value of static data member. Use main function to test the class
Counter.
CODING :-
#include<iostream.h> //header file
#include<conio.h> //header file
class Counter //class defition
{
public: //access specifier
static int count; //static member function declaration
Counter() //Default constructor definition
{
count++;
cout<<" tCreated Object - " << count<<endl;
}
~Counter() //Destructor Difinition
{
count--;
cout<<" tDestroyed Object - "<<count<<endl;
}
static void displayCount() //static member function
{
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 54 P a g e
cout<<" Current count - "<<count<<endl;
}
};
int Counter::count = 0;
int main() //main function
{
clrscr();
cout<<" Constructor called :- "<<endl;
Counter *c1 = new Counter(); //new operator used and assigns the address of
class object
Counter *c2 = new Counter();
Counter *c3 = new Counter();
Counter::displayCount(); //calls the static member function
cout<<" Destructor called :- "<<endl;
delete c1; //delete operator used to delete the allocated memory by
class object
delete c2;
Counter::displayCount();
getch(); //hold the console
return 0;
}
OUTPUT :-
P.T.O.
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 55 P a g e
STRUCTURE AND CLASS
18.Define structure student. Structure student has data members for storing
name, roll no, name of three subjects and marks. Write member function
to store and print data.
CODING :-
#include <iostream.h> //header file
#include<conio.h> //header file
struct student //structure definition
{
char name[50]; //data member of structure
int rollNo;
char subjects[3][50];
float marks[3];
void getdata() //member function of structure
{
cout<<"Enter student's name : ";
cin.getline(name, 50);
cout<<"Enter roll number : ";
cin>>rollNo;
for (int i = 0; i < 3; i++) //for loop execution
{
cout<<"Enter subject "<< i + 1 <<" name : ";
cin.ignore();
cin.getline(subjects[i], 50);
cout<<"Enter marks for "<<subjects[i]<<" : ";
cin>>marks[i];
}
}
void putdata() //member function of structure
{
cout<<endl<<"Student Information :-" <<endl;
cout<<"Name - " << name <<endl;
cout<<"Roll Number - " <<rollNo<<endl;
for (int i = 0; i < 3; i++) //for loop execution
{
cout<<"Subject " << i + 1 << " - " << subjects[i] << endl;
cout<<"Marks - " << marks[i] << endl;
}
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 56 P a g e
}
};
int main() //main function
{
clrscr(); //clear the screen function
student s1; //structure variable declaration by explicit
method
s1.getdata(); //accessing structure member function
through variable
s1.putdata();
getch (); //hold the consol
return 0;
}
OUTPUT :-
P.T.O.
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 57 P a g e
COPY CONSTRUCTOR , CONSTRUCTOR
OVERLOADING , THIS POINTER , CONSTRUCTOR WITH
DEFAULT ARGUMENT
19.write program to create a class Polar which has data member radius
and angle, define overloaded constructor to initialize object and copy
constructor to initialize one object by another existing object keep
name of parameter of parameterized constructor same as data
members. Test function of the program in main function.
CODING :-
#include<iostream.h> //header file
#include<conio.h> //header file
class Polar //class difinition
{
public: //access specifier
int radius, angle; //data member
Polar(int radius, int angle) //Parameterized constructor
{
Polar::radius = radius;
Polar::angle = angle;
}
Polar(Polar &p1) //Copy constructor
{
radius = p1.radius;
angle = p1.angle;
}
void display() //member function
{
cout<<"Radius = "<<radius<<"tAngle = "<<angle;
}
};
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 58 P a g e
int main() //main function
{
clrscr();
Polar p1(10,20); //object declaration of class
Polar p2(p1);
p2.display(); //calling member function through object
cout << endl;
getch();
return 0;
}
OUTPUT :-
20.write program to create a class Polar which has data member radius
and angle, use constructor with default arguments to avoid
constructor overloading and copy constructor to initialize one object
by another existing object keep name of parameter of parameterized
constructor same as data members. Test functioning of the program
in main function
CODING :-
#include <iostream.h> //header file
#include<conio.h> //header file
class Polar //class definition
{
public: //access specifier
int radius, angle; //data member
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 59 P a g e
Polar(int radius=15, int angle=30) //Parameterized constructor with default
arguments
{
Polar::radius = radius;
Polar::angle = angle;
}
Polar(Polar &p1) //Copy constructor
{
radius = p1.radius;
angle = p1.angle;
}
void disp() //display member function
{
cout<<"nRadius = "<<radius<<"tAngle = "<<angle;
}
};
int main() //main function
{
clrscr();
Polar p1; //object declaration of class
Polar p2(p1);
p2.disp(); //calling function through object
getch();
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 60 P a g e
FUNCTION OVERLOAD, REFERENCE VARIABLE,
PARAMETER PASSING BY ADDRESS,
STATIC FUNCTION
21.Write a class having name Calculate that uses static overloaded
function to calculate area of circle, area of rectangle and area of
triangle.
CODING :-
#include <iostream.h> //header file
#include<conio.h> //header file
class Calculate //class definition
{
public: //access specifier
static int area(int a) //static member function
{
float area = a*a*3.14;
cout<<"Area of circle (radius * radius * 3.14)= "<<area;
}
static int area(int l,int b) //static overloaded function
{
float area = l*b;
cout<<endl<<"Area of rectangle (length * width)= "<<area;
}
static int area(int b,int h,float c)
{
float area = c*h*b;
cout<<endl<<"Area of triangle = "<<area;
}
};
int main() //min function
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 61 P a g e
{
clrscr();
Calculate::area(5); //static member function calling
Calculate::area(5,10); //static member function calling
Calculate::area(5,10,1.5); //static member function calling
cout << endl;
getch();
return 0;
}
OUTPUT :-
22.write a class ArraySort that uses static overloaded function to sort an
array of floats, an array of integers.
CODING :-
#include <iostream.h> //header file
#include<conio.h>
class ArraySort //class definition
{
public: //access specifier
static void sort(float arr[], int n) //static member function
{
for(i = 0; i < n - 1; i++) //outer for loop execution
{
for (int j = 0; j < n - i - 1; j++) //inner for loop execution
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 62 P a g e
{
if (arr[j] > arr[j + 1]) //if statement
{
float temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
static void sort(int arr[], int n) //static member function
{
for (i = 0; i < n - 1; i++) //outer for loop execution
{
for (int j = 0; j < n - i - 1; j++) //inner for loop
{
if (arr[j] > arr[j + 1]) //if statment
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
};
int main() //main function
{
clrscr();
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 63 P a g e
int i;
float floatArr[] = {5.6, 3.2, 1.4, 7.8, 9.0};//variable initialization
int intArr[] = {23, 12, 45, 38, 19};
int n1 = sizeof(floatArr) / sizeof(floatArr[0]);
int n2 = sizeof(intArr) / sizeof(intArr[0]);
ArraySort::sort(floatArr, n1); //calling static member function
ArraySort::sort(intArr, n2);
cout << "Sorted float array :- ";
for (i = 0; i < n1; i++) //for loop
{
cout<<floatArr[i]<< " ";
}
cout<<endl<<"Sorted integer array :- ";
for (i = 0; i < n2; i++) //for loop
{
cout<<intArr[i] << " ";
}
getch();
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 64 P a g e
23.Write a program using class, which uses static overloaded function
to swap two integers, two floats methods use reference variable.
CODING :-
#include <iostream.h> //header file
#include<conio.h>
class Swap //class difinition
{
public: //access specifier
static int swp(float &a,float &b) //Swapping through reference
variable
{
float t = a;
a = b;
b = t;
}
static int swp(int &a,int &b) //static member function
{
int t = a;
a = b;
b = t;
}
};
int main() //main function
{
int a = 10,b = 20; //variable initialization
float c = 10.5,d =19.01;
cout<<"Before swap :-"<<endl;
cout<<"a = "<<a<<"tb = "<<b<<endl<<"c = "<<c<<"td = "<<d<<endl;
Swap::swp(a,b); //Calling static function by reference
Swap::swp(c,d);
cout<<"After swap :-"<<endl;
cout<<"a = "<<a<<"tb = "<<b<<endl<<"c = "<<c<<"td = "<<d;
getch();
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 65 P a g e
24.Write a program using class, which uses static overloaded function
to swap two integers, two floats methods use parameter passing by
address.
CODING :-
#include <iostream.h> //header file
#include<conio.h>
class Swap //class difinition
{
public: //ACCESS SPECIFIER
static int swp(float *a,float *b) //Swapping by address
{
float t = *a;
*a = *b;
*b = t;
}
static int swp(int *a,int *b) //static member function
{
int t = *a;
*a = *b;
*b = t;
}
};
int main() //main function
{
int a = 5,b = 50; //variable initialization
float c = 1.414,d =3.14;
cout<<"Before swap - n";
cout<<"a = "<<a<<"tb = "<<b<<endl<<"c = "<<c<<"td = "<<d<<endl;
Swap::swp(&a,&b); //calling statc member function ans Passing address of
variables
Swap::swp(&c,&d);
cout<<"After swap -"<<endl;
cout<<"a = "<<a<<"tb = "<<b<<endl<<"c = "<<c<<"td = "<<d;
getch();
return 0;
}
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 66 P a g e
OUTPUT :-
STRING, POINTER, AND OPERATOR OVERLOADING
25.Create class String having pointer to character as data member and
provide following facilities:
a. Constructor for initialization and memory allocation
b. Destructor for memory release
c. Overloaded operators + to add two string object
d. Overloaded operator = to assign one string object to other
string object
e. Overloaded operator = = to compare whether the two string
objects are equal or not
f. Overloaded operator < to compare whether first string object is
less than second string object
g. Overloaded operator > to compare whether first string object is
greater than second string object or not
h. Overloaded operator <= to compare whether first string object
is less than of equal to second string object or not
i. Overloaded operator >= to compare whether first string object
is greater than or equal to second string object
j. Overloaded operator !=to compare whether first string object is
not equal to second string object or not
k. Overloaded insertion and extraction operators for input in data
member and display output of data members.
CODING :-
#include<iostream>
#include<cstring>
class String {
private:
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 67 P a g e
char *str;
public:
// Constructor
String(const char* s = nullptr) {
if (s != nullptr) {
str = new char[strlen(s) + 1];
strcpy(str, s);
} else {
str = new char[1];
*str = '0';
}
}
// Destructor
~String() {
delete[] str;
}
// Overloaded + operator
String operator+(const String& rhs) const {
String result;
result.str = new char[strlen(str) + strlen(rhs.str) + 1];
strcpy(result.str, str);
strcat(result.str, rhs.str);
return result;
}
// Overloaded = operator
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 68 P a g e
String& operator=(const String& rhs) {
if (this != &rhs) {
delete[] str;
str = new char[strlen(rhs.str) + 1];
strcpy(str, rhs.str);
}
return *this;
}
// Overloaded == operator
bool operator==(const String& rhs) const {
return strcmp(str, rhs.str) == 0;
}
// Overloaded < operator
bool operator<(const String& rhs) const {
return strcmp(str, rhs.str) < 0;
}
// Overloaded > operator
bool operator>(const String& rhs) const {
return strcmp(str, rhs.str) > 0;
}
// Overloaded <= operator
bool operator<=(const String& rhs) const {
return strcmp(str, rhs.str) <= 0;
}
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 69 P a g e
// Overloaded >= operator
bool operator>=(const String& rhs) const {
return strcmp(str, rhs.str) >= 0;
}
// Overloaded != operator
bool operator!=(const String& rhs) const {
return strcmp(str, rhs.str) != 0;
}
// Overloaded << operator for output
friend std::ostream& operator<<(std::ostream& os, const String& s) {
os << s.str;
return os;
}
// Overloaded >> operator for input
friend std::istream& operator>>(std::istream& is, String& s) {
char buffer[1000];
is >> buffer;
delete[] s.str;
s.str = new char[strlen(buffer) + 1];
strcpy(s.str, buffer);
return is;
}
};
int main() {
String s1("Hello");
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 70 P a g e
String s2("World");
// Testing various operators
String s3 = s1 + s2;
std::cout << "Concatenation: " << s3 << std::endl;
String s4;
s4 = s1;
std::cout << "Assignment: " << s4 << std::endl;
std::cout << "Comparison: " << (s1 == s2 ? "Equal" : "Not Equal") << std::endl;
std::cout << "Comparison: " << (s1 < s2 ? "Less" : "Not Less") << std::endl;
// Testing input and output operators
std::cout << "Enter a string: ";
String s5;
std::cin >> s5;
std::cout << "You entered: " << s5 << std::endl;
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 71 P a g e
26. Create a class Matrix having data member double dimension array
of floats of size 3*3. Provide following facilities:
a. Overloaded extraction operator for data input
b. Overloaded insertion operator for data output
c. Overloaded operator + for adding two matrix using objects
d. Overloaded operator – for subtracting two matrix using objects
e. Overloaded operator * for multiply two matrix using objects
CODING :-
#include <iostream.h> //header file
#include<conio.h>
class Matrix //class definition
{
float arr[3][3]; // Array variable declaration
public: //access specifier
void operator >>(float objarr[3][3]) //Overloaded Extraction operator
{
for (int i = 0; i < 3; i++) //outer for loop
{
for (int j = 0; j < 3; j++) //inner for loop
{
arr[i][j] = objarr[i][j];
}
}
}
void operator<<(ostream& c) //Insertion Operator
{
for (int i = 0; i < 3; i++) //outer for loop
{
for (int j = 0; j < 3; j++) //inner for loop
{
c<<arr[i][j]<<"t";
}
c<<endl;
}
}
void operator +(Matrix m) //Addition Operator
{
for (int i = 0; i < 3; i++) //outer for loop
{
for (int j = 0; j < 3; j++) //inner for loop
{
cout<<(arr[i][j] + m.arr[i][j])<<"t";
}
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 72 P a g e
cout<<endl;
}
}
void operator -(Matrix m) //Subtraction Operator
{
for (int i = 0; i < 3; i++) //outer for loop
{
for (int j = 0; j < 3; j++) //inner for loop
{
cout<<(arr[i][j] - m.arr[i][j])<<"t";
}
cout<<endl;
}
}
void operator *(Matrix m) //Multiplication Operator
{
for (int i = 0; i < 3; i++) //outer for loop
{
for (int j = 0; j < 3; j++) //inner for loop
{
int k = 0;
float a = 0;
for (k = 0; k < 3; k++)
{
a += (arr[i][k] * m.arr[k][j]);
}
cout<<a<<"t";
}
cout<<endl;
}
}
};
int main() //main function
{
float arr[3][3]={{3.1, 4.03, 5.7},{1.2, 2.5, 3.9},{6.6, 7.5, 8.2}}; //variable initialization
float arr2[3][3]={{4.3, 8.4, 9.9},{4.56, 2.01, 1.1},{9.9, 0.0, 7.6}};
Matrix m1,m2; //object declaration of class
m1>>arr; //Calling Overloaded Operators
m2>>arr2;
m1<<cout;
cout<<"Second Matrix - "<<endl;
m2<<cout;
cout<<"Sum of array - "<<endl;
m1+m2;
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 73 P a g e
cout<<"Subtraction of array - "<<endl;
m1-m2;
cout<<"Multiplication of array -"<<endl;
m1*m2;
cout << endl;
getch();
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 74 P a g e
OPEARATOR OVERLOADING WITH FRIEND FUNCTION
27.Create a class Polar having radius and angle as data members.
Provide following facilities:
a) Overloaded insertion and extraction operators for data input
and display
b) Overloaded constructor for initialization of data members
c) Overloaded operator + to add two polar co-ordinates using
objects of class Polar
CODING :-
#include <iostream.h> //header file
#include<conio.h>
class Polar //class definition
{
int radius,angle,i=0,k=0;
public: //access specifier
Polar() //default constructor
{}
Polar(int a,int b) //Constructor for initializing values
{
radius = a;
angle = b;
}
Polar& operator >>(int a) //Overloaded operator for data input
{
if (i==0) //IF STATMENT
{
radius = a;
i++;
return *this;
}
if (i==1)
{
angle = a;
}
}
Polar& operator <<(int a)
{
if (a==1)
{
cout<<endl<<radius;
return *this;
}
if (a==2)
{
cout<<"t"<<angle;
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 75 P a g e
return *this;
}
}
Polar operator+(Polar p2) //Operator to add two objects
{
cout<<endl<<"Sum of polar co-ordinates is- "<<endl;
cout<<"Radius = "<<radius+p2.radius;
cout<<"tAngel = "<<angle+p2.angle;
}
};
int main() //main function
{
Polar p1,p2(15,12); //object declaration of class
p1>>10>>20;
cout<<"First object -"<<endl;
p1<<1<<2; //1 for radius & 2 for angle.
cout<<endl<<"Second object -"<<endl;
p2<<1<<2;
p1+p2;
getch();
return 0;
}
OUTPUT :-
28.Create class DegreeCelsius having a single data member to hold
value of temperature in degree Celsius. Provide following facilities:
a. Overloaded operator ++ which will increase value of dta
member by !(consider postfix and prefix operator overloading).
b. Overloaded operator – which will decrease value of data
member by1 (consider postfix and prefix operator overloading)
c. Overloaded insertion and extraction operators for input in data
member and display value of data member.
CODING :-
#include <iostream.h> //header file
#include<conio.h>
class DegreeCelsius //class definition
{
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 76 P a g e
private: //access specifier
float temp; //data member
public:
DegreeCelsius() //constructor definition
{
temp = 0.0;
}
DegreeCelsius(float t) //parameterized constructure
{
temp = t;
}
float getTemp() const
{
return temp;
}
void setTemp(float t)
{
temp = t;
}
DegreeCelsius operator++() //overloaded operator ++
{
temp++;
return *this;
}
DegreeCelsius operator++(int)
{
DegreeCelsius tempC = *this;
temp++;
return tempC;
}
DegreeCelsius operator--() //overloaded operator --
{
temp--;
return *this;
}
DegreeCelsius operator--(int)
{
DegreeCelsius tempC = *this;
temp--;
return tempC;
}
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 77 P a g e
friend ostream& operator<<(ostream& out, const DegreeCelsius& obj)
//insertion operator overloading
{
out << obj.temp << " degrees Celsius";
return out;
}
friend istream& operator>>(istream& in, DegreeCelsius& obj) //extraction
operator overloading
{
in >> obj.temp;
return in;
}
};
int main() //main function
{
clrscr();
DegreeCelsius temp1, temp2; //object declaration of class
cout << "Enter temperature in degrees Celsius : ";
cin >> temp1;
cout << "Temperature 1: " << temp1 << endl;
temp2 = temp1++;
cout << "Temperature 1: " << temp1 << endl;
cout << "Temperature 2: " << temp2 << endl;
temp2 = ++temp1;
cout << "Temperature 1: " << temp1 << endl;
cout << "Temperature 2: " << temp2 << endl;
temp2 = temp1--;
cout << "Temperature 1: " << temp1 << endl;
cout << "Temperature 2: " << temp2 << endl;
temp2 = --temp1;
cout << "Temperature 1: " << temp1 << endl;
cout << "Temperature 2: " << temp2 << endl;
getch();
return 0;
}
P.T.O.
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 78 P a g e
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 79 P a g e
OPERATOR OVERLOADING AND DATA TYPE
CONVERSION
29.Create a class Polar that contains data member radius and angle.
Create another class Cartesian in the same program and provide
following facilities:
a. It should be possible to assign object of polar class to object of
Cartesian class
b. It should be possible to assign object of Cartesian class to
object of polar class
CODING :-
#include <iostream.h> //header file
#include <cmath.h> //header file
#include<conio.h>
class Polar //class definition
{
private: //access specifier
double radius; //data member
double angle;
public: //ACCESS SPECIFIER
Polar(double r, double a) //parameterized constructor
{
radius = r;
angle = a;
}
double getRadius() const
{
return radius;
}
double getAngle() const
{
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 80 P a g e
return angle;
}
void setRadius(double r)
{
radius = r;
}
void setAngle(double a)
{
angle = a;
}
class Cartesian //class definiton
{
private: //access specifier
double x; //data member
double y;
public: //access specifier
Cartesian(double r, double a) //parameterized constructor
{
x = r * cos(a);
y = r * sin(a);
}
double getX() const
{
return x;
}
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 81 P a g e
double getY() const
{
return y;
}
void setX(double x)
{
this->x = x;
}
void setY(double y)
{
this->y = y;
}
};
Cartesian toCartesian()
{
return Cartesian(radius, angle);
}
};
class Cartesian
{
private:
double x;
double y;
public:
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 82 P a g e
Cartesian(double x, double y)
{
this->x = x;
this->y = y;
}
double getX() const
{
return x;
}
double getY() const
{
return y;
}
void setX(double x)
{
this->x = x;
}
void setY(double y)
{
this->y = y;
}
Polar toPolar()
{
double radius = sqrt(x * x + y * y);
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 83 P a g e
double angle = atan2(y, x);
return Polar(radius, angle);
}
};
int main() //main function
{
Polar polar(2.0, 0.5); //object initialization of class
Cartesian cartesian = polar.toCartesian();
cout << "Polar coordinates: (radius, angle) = (" << polar.getRadius() << ", " << polar.getAngle()
<< ")" << endl;
cout << "Cartesian coordinates: (x, y) = (" << cartesian.getX() << ", " << cartesian.getY() << ")"
<< endl;
Cartesian cartesian2(1.0, 1.0);
Polar polar2 = cartesian2.toPolar();
cout << "Polar coordinates: (radius, angle) = (" << polar2.getRadius() << ", " <<
polar2.getAngle() << ")" << endl;
cout << "Cartesian coordinates: (x, y) = (" << cartesian2.getX() << ", " << cartesian2.getY() <<
")" << endl;
getch();
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 84 P a g e
30. Create a class Fahrenheit that contains a data member to hold
temperature in Fahrenheit . Create another class Celsius that
contains a data member to hold temperature in Degree Celsius; in
the same program and provide following facilities:
a. It should be possible to assign object of Fahrenheit class to
object of Celsius class
b. It should be possible to assign object of Celsius class to object
of Fahrenheit class
c. It should be possible to compare objects of class Fahrenheit
and Celsius to find out which object contains higher
temperature.
CODING :-
#include <iostream.h>
#include<conio.h>
class Fahrenheit {
private:
double temp;
public:
Fahrenheit(double t) {
temp = t;
}
double getTemp() const {
return temp;
}
void setTemp(double t) {
temp = t;
}
Celsius toCelsius() const {
double tempC = (temp - 32) * 5 / 9;
return Celsius(tempC);
}
operator Celsius() const {
return toCelsius();
}
bool operator>(const Fahrenheit& f2) const {
return temp > f2.temp;
}
bool operator<(const Fahrenheit& f2) const {
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 85 P a g e
return temp < f2.temp;
}
};
class Celsius {
private:
double temp;
public:
Celsius(double t) {
temp = t;
}
double getTemp() const {
return temp;
}
void setTemp(double t) {
temp = t;
}
Fahrenheit toFahrenheit() const {
double tempF = temp * 9 / 5 + 32;
return Fahrenheit(tempF);
}
operator Fahrenheit() const {
return toFahrenheit();
}
bool operator>(const Celsius& c2) const {
return temp > c2.temp;
}
bool operator<(const Celsius& c2) const {
return temp < c2.temp;
}
};
int main() {
Fahrenheit f1(72);
Celsius c1 = f1; // Implicit conversion from Fahrenheit to Celsius using operator()
cout << "Temperature in Fahrenheit: " << f1.getTemp() << endl;
cout << "Temperature in Celsius: " << c1.getTemp() << endl;
Celsius c2(30);
Fahrenheit f2 = c2; // Explicit conversion from Celsius to Fahrenheit using constructor
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 86 P a g e
cout << "Temperature in Celsius: " << c2.getTemp() << endl;
cout << "Temperature in Fahrenheit: " << f2.getTemp() << endl;
Fahrenheit f3(80);
Celsius c3(26.67);
if (f3 > c3) {
cout << "Fahrenheit object f3 is equal to Celsius object c3" << endl;
} else {
cout << "Celsius object c3 has higher temperature than Fahrenheit object f3" <<
endl;
}
getch();
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 87 P a g e
VOID POINTER , POINTER AND
POINTER TO OBJECT
31.Create a program having pointer to void to store address of integer
variable then print value of integer variable using pointer to void.
Perform the same operation for float variable.
CODING :-
#include <iostream.h> //header file
#include<conio.h>
int main() //main function
{
int num1 = 10; //Declare an integer variable and a void
pointer
void* ptr1 = &num1; //void pointer declaration and initialiazation
cout << "Value of integer variable: " << *(int*)ptr1 << endl; // Print the value of the
integer variable using the void pointer
float num2 = 5.2; // Declare a float variable
void* ptr2 = &num2; //void pointer declaration and initialization
cout << "Value of float variable: " << *(float*)ptr2 << endl;
getch();
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 88 P a g e
32.Write program to find biggest number among three numbers using
pointer and function.
CODING :-
#include<iostream.h> //header file
#include<conio.h> //header file
int findBiggest(int* num1, int* num2, int* num3) // Function using pointers
{
int biggest = *num1;
if (*num2 > biggest) //if statement
{
biggest = *num2;
}
if (*num3 > biggest) //if statement
{
biggest = *num3;
}
return biggest;
}
int main() //main function
{
int num1 = 10, num2 = 15, num3 = 20; // Declare three integer variables
int biggestNumber = findBiggest(&num1, &num2, &num3); // Find the biggest
number using pointers and function
cout<<" Biggest number :- "<<biggestNumber<<endl; // Print the biggest
number
getch();
return 0;
}
OUTPUT :-
33.Write swapping program to demonstrate cal by value, call by address
and call by reference in a single program.
CODING :-
#include<iostream.h> //header file
#include<conio.h>
void value(int a,int b) //Call by value
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 89 P a g e
{
int t = a;
a = b;
b = t;
}
void address(int *a,int *b) //Call by address
{
int t = *a;
*a = *b;
*b = t;
}
void reference(int &a,int &b) //Call by reference
{
int t = a;
a = b;
b = t;
}
int main() //main function
{
int a = 40,b = 50; //Variable Initialization
cout<<"Before Swapping :- "<<endl;
cout<<"a = "<<a<<"tb = "<<b<<endl;
value(a,b); //calling function by Value
cout<<"After call by value :- "<<endl;
cout<<"a = "<<a<<"tb = "<<b<<endl;
address(&a,&b); //calling function by address
cout<<"After call by address :- "<<endl;
cout<<"a = "<<a<<"tb = "<<b<<endl;
reference(a,b); //calling function by reference
cout<<"After call by Reference :-"<<endl;
cout<<"a = "<<a<<"tb = "<<b;
getch();
return 0;
}
P.T.O.
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 90 P a g e
OUTPUT :-
34.Write a program to create a class Employee having data members to
store name of employee, employee id, salary. Provide member
function for data input, output. Use Pointer to object to simulate
array of object to store information of 3 employees and test the
program in function main.
CODING :-
#include<iostream.h> //header file
#include<conio.h> //header file
class Employee //class definition
{
private: //access specifier
char name[50]; //data member
int Id;
float salary;
public: //access specifier
void inputData() //member function for input data
{
cout<<"Enter employee name : ";
cin.getline(name, 50);
cout<<"Enter employee ID: ";
cin >>Id;
cout<<"Enter employee salary: ";
cin>>salary;
}
void displayData() //member function to output data
{
cout<<"Employee Name - "<<name<<endl;
cout<<"Employee ID - "<<Id<<endl;
cout<<"Employee Salary - "<<salary<<endl;
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 91 P a g e
}
};
int main() //main function
{
clrscr();
int i;
Employee* employees = new Employee[3];//Create an array of Employee objects
for (i = 0; i < 3; i++) //For loop for Input data
{
employees[i].inputData();
}
for (i = 0; i < 3; i++) //For loop for Display data
{
employees[i].displayData();
cout << endl;
}
delete[] employees; // Delete the dynamically allocated array
getch();
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 92 P a g e
INLINE FUNCTION
35.Write a program using inline function to calculate area of circle.
CODING :-
#include<iostream.h> //header file
#include<conio.h>
inline int area(int r) //Inline function declaration
{
return (3.14*r*r);
}
int main() //main function
{
clrscr();
int r;
cout<<"Enter radius = ";
cin>>r;
cout<<endl<<"Area = "<<area(r); //Calling inline function
getch();
return 0;
}
OUTPUT :-
36.Write a program using inline function to find minimum of two
functions. The inline function should take two arguments and
should return the minimum value.
CODING :-
#include <iostream.h> //header file
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 93 P a g e
#include<conio.h>
inline int minvalue(int x,int y) //Inline function declaration
{
if (x<y) //if else statement
{
return x;
}
else
{
return y;
}
}
int fnc1(int a) //function definition
{
return a;
}
int fnc2(int a) //function definition
{
return a;
}
int main() //main function
{
clrscr();
int a,b; //variable declaration
cout<<"Enter two number - ";
cin>>a>>b;
cout<<"Minimum value = "<<minvalue(fnc1(a),fnc2(b)); //Calling inline function
getch();
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 94 P a g e
INHERITANCE
37. Create a class account that stores customer name, account number
and type of account. From this derive the classes cur_acct and
sav_acct to make them more specific to their requirements. Include
necessary member functions in order to achieve the following tasks:
a. Accept deposit from customer
b. Display the balance
c. Compute and deposit interest
d. Permit withdrawal and update the balance Check for the
minimum balance, impose penalty, necessary and update the
balance.
CODING :-
#include<iostream.h> //header file
#include<conio.h>
class account //class definition
{
public: //access specifier
char c_name[50],type[45]; //data member
float balance=0,deposit;
int acc_no;
void withdraw() //Member function defination
{
int a;
cout<<endl<<"Enter the amount to withdraw from "<<c_name<<"'s account = ";
cin>>a;
if (balance>=a) //if statement
{
balance -= a;
cout<<"Wihtdraw Successful!!!"<<endl<<"Your current balacne is
"<<balance<<endl;
}
else
{
cout<<endl<<"Not enough balance";
}
}
void checkANDFine() //Function to check minimum balance
{
cout<<"Minimum balance is Rs. 2000, below that penalty of 200 will be fined.";
if (balance < 2000) //if else statement
{
balance -= 200;
cout<<endl<<"So after fine "<<c_name<<"'s current balance is = "<<balance;
}
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 95 P a g e
else
{
cout<<endl<<"No penalty imposed.";
}
}
void deposite() //Function to deposit money
{
float a;
cout<<"Enter amount to deposit for "<<c_name<<" = ";
cin>>a;
balance += a;
}
void disp()
{
cout<<"Customer Name = "<<c_name<<"nType = "<<type<<"tBalance =
"<<balance;
}
};
class cur_acct:public account //Class declaration for CURRENT account
{
public:
cur_acct();
cur_acct(char a[50],int b,char c[45])
{
c_name=a;
acc_no=b;
type=c;
}
};
class sav_acct:public account //Class declaration for SAVINGS account
{
public:
sav_acct(char a[50],int b,int intrst,char[45] c="Savings")
{
c_name=a;
acc_no=b;
type=c;
interest = intrst;
}
int interest;
void disp()
{
cout<<"Customer Name = "<<c_name<<"nType = "<<type<<"tBalance =
"<<balance<<"tInterest = "<<interest;
}
void dispInterest()
{
float a = (balance*interest)/100;
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 96 P a g e
balance += a;
cout<<endl<<"Interest of "<<interest<<"% "<<" on "<<c_name<<"'s balance is =
"<<a<<"tBalance = "<<balance;
}
};
int main() //main function
{
cur_acct c1("Yashwant",101,"Current");
c1.deposite();
c1.disp();
cout<<endl<<endl;
sav_acct c2("Yamini",102,3);
c2.deposite();
c2.disp();
c2.dispInterest();
cout<<endl;
c1.withdraw();
cout<<endl;
c2.checkANDFine();
cout << endl;
getch();
return 0;
}
OUTPUT :-
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 97 P a g e
38.Create a class circle with data member radius; provide member
function to calculate area. Derive a class sphere from class circle;
provide member function to calculate volume. Derive class cylinder
from class sphere with additional data member for height and
member function to calculate volume.
CODING :-
#include <iostream.h> //header file
#include <conio.h>
class circle //Base class definition
{
protected: //access specifier
int radius; //data member
public: //access specifier
void area() //Member function to calculate area of circle
{
cout<<"Area of circle = "<<(float)(3.14*radius*radius);
}
void get() //member function
{
cout<<"Enter the radius = ";
cin>>radius;
}
};
class sphere:public circle //intermediate class definition
{
public: //access specifier
void sp_volume() //Function to calculate volume of sphere
{
cout<<endl<<"Volume of sphere = "<<(float)((4/3)*3.14*radius*radius*radius);
}
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 98 P a g e
};
class cylinder:public sphere //child class definition
{
int height;
public: //access specifier
void cy_volume() //Function to calculate volume of cylinder
{
cout<<"Volume of cylinder = "<<(float)(3.14*radius*radius*height);
}
void cy_get()
{
cout<<endl<<"Enter the height = ";
cin>>height;
}
};
int main() //main function
{
cylinder obj; //object declaration
obj.get(); //calling function through object
obj.area();
obj.sp_volume();
obj.cy_get();
obj.cy_volume();
getch();
return 0;
}
P.T.O.
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 99 P a g e
OUTPUT :-
39.Consider an example of declaring the examination result. Design
three classes:- student, exam and result. The student class has data
members such as that representing roll number, name of student.
Create the class exam, which contains data members representing
name of subject, minimum marks, maximum marks, obtained marks
for three subjects. Derive class result from both student and exam
classes. Test the result class in main function.
CODING :-
#include<iostream.h> //header file
#include<conio.h>
class Student //base class definition
{
private: //access specifier
int rollNumber; //data member
char name[50];
public: //access specifier
void inputSData() //member function to store student data
{
cout<<"Enter roll number : ";
cin>>rollNumber;
cout<<"Enter student name : ";
cin.getline(name, 50);
}
void showSData() //member function to show student data
{
cout<<"Roll Number - "<<rollNumber<<endl;
cout<<"Student Name - "<<name<<endl;
}
};
class Exam //base class definition
{
private: //access specifier
char subjectName[50]; //data member
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 100 P a g e
int minMarks;
int maxMarks;
int obtMarks[3];
public: //access specifier
void inputsubData() //member function to input subject data
{
cout<<"Enter subject name : ";
cin.getline(subjectName, 50);
cout<<"Enter minimum marks: ";
cin>>minMarks;
cout<<"Enter maximum marks : ";
cin >> maxMarks;
cout<<"Enter obtained marks for three subjects : ";
for (int i = 0; i < 3; i++) //for loop execution
{
cin>>obtMarks[i];
}
}
void showsubData() //member function to show
subject data
{
cout << "Subject Name - " << subjectName << endl;
cout << "Minimum Marks - " << minMarks << endl;
cout << "Maximum Marks - " << maxMarks << endl;
cout << "Obtained Marks - ";
for (int i = 0; i < 3; i++)
{
cout << obtMarks[i] << " ";
}
cout << endl;
}
};
class Result : public Student, public Exam //multiple inheritance used here
{
private:
double totalMarks;
double averageMarks;
char grade;
public:
void calculateResult()
{
totalMarks = 0;
for (int i = 0; i < 3; i++)
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 101 P a g e
{
totalMarks += obtainedMarks[i];
}
averageMarks = totalMarks / 3;
if (averageMarks >= 90)
{
grade = 'A';
}
else if (averageMarks >= 80)
{
grade = 'B';
}
else if (averageMarks >= 70)
{
grade = 'C';
}
else if (averageMarks >= 60)
{
grade = 'D';
}
else
{
grade = 'F';
}
}
void displayResult()
{
showSData();
showsubData();
cout << "Total Marks: " << totalMarks << endl;
cout << "Average Marks: " << averageMarks << endl;
cout << "Grade: " << grade << endl;
}
};
int main() //main function
{
clrscr();
Result studentResult; //object initialization
studentResult.inputSData();
studentResult.inputsubData();
studentResult.calculateResult();
cout<<”t -: Student Result :- “<<endl;
studentResult.displayResult();
getch();
return 0;
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 102 P a g e
}
OUTPUT :-
P.T.O.
yashwant
yashwant
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 103 P a g e
VIRTUAL AND PURE VIRTUAL FUNCTION
40.Create a base class shape having two data members with two
member function getdata (pure virtual function) and printarea (not
pure virtual function). Derive classes triangle and rectangle from
class shape and redefine member functioning of classes using
pointer to base class objects and normal objects.
CODING :-
#include <iostream.h> //header file
#include<conio.h>
class shape // Class Definition
{
protected: //access specifier
int a,b; //data member
public: //access specifier
virtual void getdata()=0; //Pure virtual function
virtual void printarea() //Virtual function
{
cout<<"Area = "<<a*b;
}
};
class triangle : public shape // hierarchical inheritance used here
{
public: //access specifier
void getdata() //Overriding Pure Virtual Function
{
cout<<"Enter two values triangle - "<<endl;
cin>>a>>b;
}
void printarea() //Function overriding
{
cout<<"Area = "<<(float)a*b*0.5;
}
};
class rectangle:public shape // hierarchical inheritance used
here
{
public: //access specifier
void getdata()
{
Cout<<endl<<"Enter two values for rectangle - "<<endl;
cin>>a>>b;
}
};
int main() //main function
{
PROGRAMMING IN C++ 2023
YASHWANT KUMAR TANDEKAR (BCA 3rd
SEM) 104 P a g e
triangle t1; //object declaration of class
shape *bptr = &t1; //Base class pointer
bptr->getdata(); // function call using base class
pointer
bptr->printarea();
rectangle r1; //object declaration
bptr = &r1;
(*bptr).getdata(); //Dereferencing base class pointer
(*bptr).printarea();
getch();
return 0;
}
OUTPUT :-

More Related Content

Similar to c++ practical Digvajiya collage Rajnandgaon

Pads lab manual final
Pads lab manual finalPads lab manual final
Pads lab manual finalAhalyaR
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfyamew16788
 
Assignement of programming & problem solving ass.(3)
Assignement of programming & problem solving ass.(3)Assignement of programming & problem solving ass.(3)
Assignement of programming & problem solving ass.(3)Syed Umair
 
Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output)Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output)Aman Deep
 
Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output) Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output) Aman Deep
 
Practical basics on c++
Practical basics on c++Practical basics on c++
Practical basics on c++Marco Izzotti
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptsbhargavi804095
 
54602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee0108310154602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee01083101premrings
 

Similar to c++ practical Digvajiya collage Rajnandgaon (20)

Pads lab manual final
Pads lab manual finalPads lab manual final
Pads lab manual final
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdf
 
C++ Programs
C++ ProgramsC++ Programs
C++ Programs
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
 
Assignement of programming & problem solving ass.(3)
Assignement of programming & problem solving ass.(3)Assignement of programming & problem solving ass.(3)
Assignement of programming & problem solving ass.(3)
 
Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output)Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output)
 
Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output) Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output)
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
Practical basics on c++
Practical basics on c++Practical basics on c++
Practical basics on c++
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
C++ file
C++ fileC++ file
C++ file
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions concepts
 
C++
C++C++
C++
 
Functions
FunctionsFunctions
Functions
 
Computer Practical XII
Computer Practical XIIComputer Practical XII
Computer Practical XII
 
C++ file
C++ fileC++ file
C++ file
 
C++ file
C++ fileC++ file
C++ file
 
54602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee0108310154602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee01083101
 

Recently uploaded

Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersPedroFerreira53928
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfjoachimlavalley1
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptSourabh Kumar
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsCol Mukteshwar Prasad
 
Morse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptxMorse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptxjmorse8
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...Nguyen Thanh Tu Collection
 
[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online PresentationGDSCYCCE
 
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxJose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxricssacare
 
Open Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPointOpen Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPointELaRue0
 
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...Sayali Powar
 
size separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticssize separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticspragatimahajan3
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfVivekanand Anglo Vedic Academy
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonSteve Thomason
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXMIRIAMSALINAS13
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringDenish Jangid
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPCeline George
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
 

Recently uploaded (20)

Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
Morse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptxMorse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptx
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
 
[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation
 
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxJose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
 
Open Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPointOpen Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPoint
 
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
 
size separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticssize separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceutics
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
B.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdfB.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdf
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
NCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdfNCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdf
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 

c++ practical Digvajiya collage Rajnandgaon

  • 1. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 1 P a g e 1. write a program to generate following pattern:- (a) A B C D E F G A B C E F G A B F G A G CODING :- #include<iostream.h> //header file #include<conio.h> int main() //main function { clrscr(); char i,j,k,l,n='D'; //variable declaration k = n; //assigning value of k in "n" l = n; for(i='A';i<='D';i++) //Outer for loop execution { for(j='A';j<='G';j++) //inner for loop execution { if(j>k && j<l) //If statement cout<<" "; else cout<<j; } k --; l ++; cout<<endl; } getch(); return 0 ; } OUTPUT :-
  • 2. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 2 P a g e (b) 1 1 2 1 2 3 CODING :- #include<iostream.h> //header file #include<conio.h> int main() //main function { clrscr(); int i,j; //variable declaration for(i=1;i<=3;i++) //Outer for loop execution { for(j=1;j<=i;j++) //inner for loop execution { cout<<j; //Printing value of “j” } cout<<endl; } getch() ; return 0; }
  • 3. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 3 P a g e OUTPUT :- (c) * * * * * * CODING :- #include<iostream.h> //header file #include<conio.h> //header file int main () //main function { int i ,j , k ; //variable declaration and initialization clrscr (); //clear the screen funtion for(i=1;i<=3;i++) //for loop execution { for(int k=3-i;k>0;k--) { cout<<" " ; } for(int j=1;j<=i;j++) { cout<<" * " ;
  • 4. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 4 P a g e } cout<<endl; } getch(); return 0; } OUTPUT :- (d) 1 121 1331 14641 CODING :- #include<iostream.h> //header file #include<conio.h> #include<math.h> int main() //main function { clrscr(); int i , p=1; //variable declaration cout<<endl<<p; for(i=2;i<=4;i++) //For loop execution
  • 5. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 5 P a g e { p = pow(11,i); //liberary function cout<<endl<<p; } getch(); return 0; } OUTPUT :- 2. Write member functions which when called ask pattern type: if user enters 11 then a member function is called which generates first pattern using for loop. If user enters 12 then a member function is called which generates first pattern using while loop. If user enters 13 then a member function is called which generates second pattern using for loop and so on. CODING :- #include<iostream.h> //header file #include<conio.h> class PatternGenerator //class definition { public: //visibility mode void generatePattern() //member function
  • 6. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 6 P a g e { int patternType; //variable declaration clrscr(); cout << "Enter pattern type 11, 12, 13 : "; cin >> patternType; switch (patternType) //switch statement { case 11: generatePatternUsingForLoop(0); break; case 12: generatePatternUsingWhileLoop(1); break; case 13: generatePatternUsingForLoop(2); break; default: cout << "Invalid pattern type." << endl; } getch(); // Wait for a key press before exiting } private: //visibility mode void generatePatternUsingForLoop(int patternNumber) //member function definition { char i,j,k,l,n='D'; //variable declaration
  • 7. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 7 P a g e k = n; //assigning value of k in "n" l = n; for(i='A';i<='D';i++) //Outer for loop execution { for(j='A';j<='G';j++) //inner for loop execution { if(j>k && j<l) //If statemnet cout<<" "; else cout<<j; } k --; l ++; cout<<endl; } } void generatePatternUsingWhileLoop(int patternNumber) //member function definition { int i,j; //variable declaration for(i=1;i<=4;i++) //Outer for loop execution { for(j=1;j<=i;j++) //inner for loop execution { cout<<j; }
  • 8. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 8 P a g e cout<<endl; } } }; int main() //main function { PatternGenerator patternGen; //declaration of class object patternGen.generatePattern(); //calling function of class through object getch(); return 0; } OUTPUT :- 3. Write a program to display number 1 to 10 in octal, decimal and hexa- decimal system. CODING :- #include <iostream.h> //header file #include <conio.h> //header file #include <iomanip.h> int main() //main function
  • 9. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 9 P a g e { clrscr(); //clear the screen function cout << "DecimaltOctaltHexadecimal" << endl; //printing statement for (int i = 1; i <= 10; i++) //for loop execution { cout << dec << i << "t" << oct << i << "t" << hex << i << endl; } getch(); //holding the screen return 0; } OUTPUT :- P.T.O.
  • 10. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 10 P a g e 4. Write program to display number from one number system to another number system. The program must ask for the number system in which you will input integer value then the program must ask the number system in which you will want output of the input number after that you have to input the number in specified number system and program will give the output according to number system for output you mentioned earlier. CODING :- #include <iostream.h> //header file #include <conio.h> //header file #include <iomanip.h> //header file #include <math.h> long decimalToBinary(long decimalNum) // Function to convert from decimal to binary { long binaryNum = 0, remainder, base = 1; //variable declaration while (decimalNum > 0) //while loop execution { remainder = decimalNum % 2; binaryNum = binaryNum + remainder * base; decimalNum = decimalNum / 2; base = base * 10; } return binaryNum; } char* decimalToHexadecimal(long decimalNum) //Function to convert decimal to hexadecimal { char hexadecimalNum[20]; //variable declaration int index = 0; while (decimalNum > 0) //while loop execution { int remainder = decimalNum % 16; if (remainder < 10) //if statement { hexadecimalNum[index++] = remainder + '0'; } else
  • 11. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 11 P a g e { hexadecimalNum[index++] = remainder - 10 + 'A'; } decimalNum = decimalNum / 16; } hexadecimalNum[index] = '0'; int start = 0; int end = index - 1; while (start < end) //while loop execution { char temp = hexadecimalNum[start]; hexadecimalNum[start] = hexadecimalNum[end]; hexadecimalNum[end] = temp; start++; end--; } return hexadecimalNum; } int main() //main function { clrscr(); //clear the screen function int inputBase, outputBase; //variable declaration long inputNumber, outputNumber; cout << "Enter the input number system (2 for binary, 10 for decimal, 16 for hexadecimal): "; cin >> inputBase; cout << "Enter the output number system (2 for binary, 10 for decimal, 16 for hexadecimal): "; cin >> outputBase; if (inputBase != 2 && inputBase != 10 && inputBase != 16) //if statement { cout << "Invalid input number system." << endl; } else if (outputBase != 2 && outputBase != 10 && outputBase != 16)
  • 12. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 12 P a g e { cout << "Invalid output number system." << endl; } else { cout << "Enter the number in the input number system: "; cin >> inputNumber; if (inputBase == 2 && outputBase == 10) //if statement { outputNumber = 0; int bitPosition = 0; while (inputNumber > 0) //while loop execution { int digit = inputNumber % 10; outputNumber += digit * pow(2, bitPosition); inputNumber /= 10; bitPosition++; } cout << "Output in decimal: " << outputNumber << endl; } else if (inputBase == 10 && outputBase == 2) { outputNumber = decimalToBinary(inputNumber); cout << "Output in binary: " << outputNumber << endl; } else if (inputBase == 16 && outputBase == 10) { outputNumber = 0; int hexLength = 0; char hexChar; while (inputNumber > 0) //while loop execution { hexChar = inputNumber % 10; if (hexChar >= '0' && hexChar <= '9') //if statement { outputNumber += (hexChar - '0') * pow(16, hexLength); } else if (hexChar >= 'A' && hexChar <= 'F') {
  • 13. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 13 P a g e outputNumber += (hexChar - 'A' + 10) * pow(16, hexLength); } else { cout << "Invalid hexadecimal digit." << endl; return 1; } inputNumber /= 10; hexLength++; } cout << "Output in decimal: " << outputNumber << endl; } else if (inputBase == 10 && outputBase == 16) { char* hexadecimalNum = decimalToHexadecimal(inputNumber); cout << "Output in hexadecimal: " << hexadecimalNum << endl; } else { cout << "Conversion between these number systems is not supported." << endl; } } getch(); // Wait for a key press before exiting return 0; } OUTPUT :-
  • 14. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 14 P a g e P.T.O. B
  • 15. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 15 P a g e ARRAY 5. Write a program using function to add, subtract and multiply two matrices of order 3*3. You have to create one function for addition, which accepts three array arguments. First two array arguments are matrices to add and third matrix is destination where the resultant of addition of first two matrices is stored. In similar way create functions for matrix subtraction and multiplication. CODING :- #include <iostream.h> //header file #include<conio.h> void add(int arr1[3][3], int arr2[3][3]) //Function to add arrays. { int arr3[3][3]; //array variable declaration cout <<"Sum of array -n"; for (int i = 0; i < 3; i++) //outer for loop execution { for (int j = 0; j < 3; j++) //inner for loop { arr3[i][j] = arr1[i][j] + arr2[i][j]; //performing addition operation cout << arr3[i][j] << "t"; //printing addition of 2 arrays cout << endl; } } void subt(int arr1[][3], int arr2[][3]) //Function for subtracting arrays. { int arr3[3][3]; //array variable declaration cout << "Subtraction of array -n"; for (int i = 0; i < 3; i++) //outer for loop execution { for (int j = 0; j < 3; j++) //inner for loop { arr3[i][j] = arr1[i][j] - arr2[i][j]; //performing subtraction operation
  • 16. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 16 P a g e cout << arr3[i][j] << "t"; //printing subtraction of 2 arrays } cout << endl; } } void multi(int arr1[][3], int arr2[][3]) //Function to multiply arrays. { int arr3[3][3]; cout << "Multiplication of array -n"; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { arr3[i][j] = arr1[i][j] * arr2[i][j]; cout << arr3[i][j] << "t"; } cout << endl; } } int main() //main function { clrscr(); int i,j; int arr1[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; //Array declaration & initialization int arr2[3][3] = {9, 8, 7, 6, 5, 4, 3, 2, 1}; cout<<"First Array is - "<<endl; for(i=0;i<3;i++) //outer for loop { for(j=0;j<3;j++) //inner for loop { cout<<"t"<<arr1[i][j]; //printing array 1 elements } cout<<endl; } cout<<"Second Array is - "<<endl; for(i=0;i<3;i++) //outer for loop { for(j=0;j<3;j++) //inner for loop
  • 17. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 17 P a g e { cout<<"t"<<arr2[i][j]; //printing array 2 elements } cout<<endl; } add(arr1, arr2); //add function call cout << endl; subt(arr2, arr1); //subt function call cout << endl; multi(arr1, arr2); //multi function call getch(); return 0; } OUTPUT :- 6. create a single program to perform following tasks without using library functions: a) To reverse the string accepted as argument :- CODING :- #include <iostream.h> //header file #include <conio.h>
  • 18. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 18 P a g e int main() //main function { clrscr(); char str[100]; //variable declaration cout << "Enter a string: "; cin>>str; //read the value entered by the user int length = 0; //variable declaration while (str[length] != '0') // Calculate the length of the string using while loop { length++; } for (int i = 0, j = length - 1; i < j; i++, j--) // Reverse the string using for loop { char temp = str[i]; str[i] = str[j]; str[j] = temp; } cout << "Reversed string: " << str << endl; getch(); // hold the screen return 0; } OUTPUT :-
  • 19. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 19 P a g e b) To count the number of characters in string passed as argument in form of character array. CODING :- #include <iostream.h> //header file #include <conio.h> int main() //main function { clrscr(); char str[100]; //variable declaration cout << "Enter a string: "; cin>>str; //read input by the user int count = 0; // Count characters in the string while (str[count] != '0') //while loop execution { count++; } cout << "Number of characters in the string: " << count << endl; getch(); return 0; } OUTPUT :-
  • 20. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 20 P a g e c) To copy the one string to other string passed as arguments in form of source character array and destination character array without using library function. CODING :- #include <iostream.h> //header file #include <conio.h> int main() //main function { clrscr(); char source[100], copy[100]; //variable declaration cout << "Enter a string: "; cin>>source; // Copy the source string to the destination string without using library functions int i = 0; while (source[i] != '0') //while loop execution { copy[i] = source[i]; i++; } copy[i] = '0'; cout << "Source string: " << source << endl; cout << "Copied string: " <<copy<< endl; getch(); return 0; }
  • 21. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 21 P a g e OUTPUT :- d) To count no. of vowels, consonants in each word of a sentence passed as argument in form of character array. CODING :- #include <iostream.h> //header file #include<conio.h> int main() //main function { clrscr(); char line[150]; //variable declaration int vowels, consonants, digits, spaces; //variable declaration vowels = consonants = digits = spaces = 0; cout << "Enter a line of string: "; cin.getline(line, 150); //read line or sentence given by the user for(int i = 0; line[i]!='0'; ++i) //for loop execution { if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u' || line[i]=='A' || line[i]=='E' || line[i]=='I' || line[i]=='O' || line[i]=='U') //if statement {
  • 22. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 22 P a g e ++vowels; } else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z')) { ++consonants; } else if(line[i]>='0' && line[i]<='9') { ++digits; } else if (line[i]==' ') { ++spaces; } } cout << "Vowels: " << vowels << endl; cout << "Consonants: " << consonants << endl; cout << "Digits: " << digits << endl; cout << "White spaces: " << spaces << endl; getch(); return 0; } OUTPUT :-
  • 23. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 23 P a g e CLASS, OBJECT, ARRAY OF OBJECT, OBJECT USING ARRAY 7. Create a class student having data members to store roll number, name of student, name of three subjects, max marks, min marks, obtained marks. Declare an object of class student. Provide facilities to input data in data members and show result of student. CODING :- #include <iostream.h> //header file #include <conio.h> #include <stdio.h> class Student //Class Definition { private: //Access specifier int rollNumber; //variable Declaration char name[50]; char subjects[3][50]; int maxMarks[3]; int minMarks[3]; int obtainedMarks[3]; public: //Access Specifier void input() //Member function Definition inside the class { cout << "Enter Roll Number: "; cin >> rollNumber; cout << "Enter Student Name: "; gets(name);
  • 24. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 24 P a g e for (int i = 0; i < 3; i++) //For Loop Execution { cout << "Enter Name of Subject " << i + 1 << " - "; gets(subjects[i]); cout << "Enter Max Marks for Subject " << i + 1 << " - "; cin >> maxMarks[i]; cout << "Enter Min Marks for Subject " << i + 1 << " - "; cin >> minMarks[i]; cout << "Enter Obtained Marks for Subject " << i + 1 << " - "; cin >> obtainedMarks[i]; } } void show(); //member function declaration }; void Student::show() //Function Definion outside the Class { clrscr(); // Clear the screen cout << "ttt -: Student Details :- "<<endl; cout << "Roll Number: " << rollNumber << endl; cout << "Student Name: " << name << endl; for (int i = 0; i < 3; i++) //For Loop Execution { cout << "Subject " << i + 1 << " Name: " << subjects[i] << endl; cout << "Max Marks for Subject " << i + 1 << " = " << maxMarks[i] << endl; cout << "Min Marks for Subject " << i + 1 << " = " << minMarks[i] << endl; cout << "Obtained Marks for Subject " << i + 1 << " = " << obtainedMarks[i] << endl; } } int main() //Main Function { clrscr(); // Clear the screen Student s1; //object Declaration of "Student" class s1.input(); //Accessing Class's member function through object s1.show(); // Show data getch(); return 0; }
  • 25. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 25 P a g e OUTPUT :- P.T.O.
  • 26. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 26 P a g e 8. Create a class student having data members to store roll number, name of student, name of three subjects, max marks, min marks, obtained marks. Declare array of object to hold data of 3 students. Provide facilities to show result of all students. Provide also facility to show result of specific student whose roll number is given. CODING :- #include <iostream.h> //header file #include <conio.h> class student //class definition { int rollno, maxm, minm, obtm; //data member char name[50], subnm[3]; public : //access specifier void get() //member function { cout <<endl<< "Enter Roll Number = "; cin >> rollno; cout << "Enter student Name = "; cin.getline(name,50); cin.ignore(); cout <<endl<< "Enter name of subjects - "; for (int i = 0; i < 3; i++) //for loop execution { cin.ignore(); cout << "Subject " << i + 1 << " = "; getline(cin, subnm[i]); } cout <<endl<< "Enter maximum marks = "; cin >> maxm; cout <<endl<< "Enter minimum marks = ";
  • 27. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 27 P a g e cin >> minm; cout <<endl<< "Enter obtained marks = "; cin >> obtm; } void disp() { cout << endl<< "Student Details!!!nn"; cout << "Roll Number = " << rollno << endl; cout << "Student Name = " << name << endl; cout << "Subject details - "<<endl; for (int i = 0; i < 3; i++) { cout << "Subject " << i + 1 << " : " << subnm[i] << endl; } cout << "Result - "<<endl<<endl; cout << "Maximum marks = " << maxm <<endl<< “Max marks = " << minm <<endl<< "Obtainde marks = " << obtm; } }; int main() //main function { int a = 1; student s1[3]; //Initializing array of objects do { cout << "Enter 1 - To see all student's result "<<endl; cout << "Enter 2 - To see any specific student's result”<<endl<<”Enter 0 - To exit”<<end<<”Value here = "; cin >> a;
  • 28. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 28 P a g e if (a == 1) { cout << "nEnter details of the students -n"; for (int i = 0; i < 3; i++) { s1[i].get(); s1[i].disp(); } } else if (a == 2) { int rln; cout << "Enter the roll number from 100 to 102 = "; cout <<endl<< "Enter details of the students -"<<endl; cin >> rln; switch (rln) //Using switch case { case 100: s1[0].get(); s1[0].disp(); break; case 101: s1[1].get(); s1[1].disp(); break; case 102: s1[2].get(); s1[2].disp();
  • 29. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 29 P a g e break; default: cout << "Invalid Roll number..."; break; } } } while (a!= 0); cout << endl; getch(); return 0; } OUTPUT :-
  • 30. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 30 P a g e 9. Create a class Sarray having an array of integers having 5 elements as data member provide following facilities: a) Constructor to get number in array elements b) Sort the elements c) Find largest element CODING :- #include<iostream.h> //header file #include<conio.h> class Sarray //Class Definition { private: //Access Specifier int arr[5]; //Data Member public: Sarray() // Constructor to initialize the array elements { for (int i = 0; i < 5; i++) //For Loop Execution { cout << "Enter element " << i + 1 << ": "; cin >> arr[i]; cout<<endl; } } void sort() // sort the array elements { for (int i = 0; i < 4; i++) //Outer For loop Execution { for (int j = i + 1; j < 5; j++) //inner For Loop { if (arr[i] > arr[j]) //If Statement
  • 31. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 31 P a g e { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } } int findlrg() // find the largest element { int largest = arr[0]; for (int i = 1; i < 5; i++) //For loop Execution { if (arr[i] > largest) //if Statement { largest = arr[i]; } } return largest; } void show() // show the array elements { for (int i = 0; i < 5; i++) //For loop { cout << arr[i] << " "; } cout << endl; } };
  • 32. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 32 P a g e int main() //Main Function { Sarray sarr ; //Object Declaration of Class Sarray cout << "Unsorted array: "; sarr.show(); //Calling class member function through Object sarr.sort(); cout << "Sorted array: "; sarr.show(); int largest = sarr.findlrg(); //Variable initialization through Object cout << "Largest element: " << largest << endl; getch(); return 0; } OUTPUT :- STATIC MEMBER FUNCTION 10.Create a class Simple with static member functions for following tasks :-
  • 33. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 33 P a g e a) To find fact by recursive member function. CODING :- #include <iostream.h> //header file #include<conio.h> class Simple //Class Definition { public : //Access Specifier static int fact(int n) //Static Member Function definition { if (n == 0 || n == 1) //if else statement { return 1; } else { return n * fact(n - 1); } } }; int main() //Main Function { clrscr(); int num; //variable declaration cout<<"Enter a number : "; cin >> num; int factValue = Simple::fact(num); //assigns the value returned by the fact() cout<<"Factorial of " << num << " is - " << factValue << endl; getch(); return 0;
  • 34. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 34 P a g e } OUTPUT :- b) To check whether a no. is prime or not. CODING :- #include<iostream.h> //header file #include<conio.h> class findprime //Class Definition { public : //Access Specifier static void prime(int a) //Static Member function { int b = 0; for (int i = 2; i < a; i++) //For Loop Execution { if (a%i==0) //if else statement { b++; } } if (b==0) {
  • 35. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 35 P a g e cout<<a<<" is a prime number"<<endl; } else //else statement { cout<<a<<" is not a prime number"<<endl; } } }; int main() //main function { clrscr(); int l; //variable initialization cout<<"enter any number"; cin>>l; findprime::prime(l); //calling Static member function getch(); return 0; } OUTPUT :- c) To generate Fibonacci series up to requested terms. CODING :- #include <iostream.h> //header file #include<conio.h> class fibonacci //class definition
  • 36. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 36 P a g e { public: //Access Specifier static void fibo() //Static Member Function { int n,a=0,b=1,c,i=0; //variable initialization cout<<"Enter number of terms = "; cin>>n; cout<<"Fibonaci series of "<<n<<" term are :- "<<endl<<a<<" "<<b<<" "; while (i<n-2) //While Loop execution { c = a+b; cout<<c<<" "; a = b; b = c; i++; //Increment Operator } } }; int main() //Main Function { clrscr(); fibonacci::fibo(); //Calling static member-function cout << endl; getch(); return 0; } OUTPUT :-
  • 37. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 37 P a g e OBJECT AS ARGUMENT TO FUNCTION , FUNCTION RETURNING OBJECT 11. Write program using class having class name Darray. Darray has pointer to pointer to integer as data member to implement double dimension dynamic array and provide following facilities: a) Constructor to input values in array elements b) Input member function to get input in array element c) Output member function to print element value d) Add member function to perform matrix addition using objects e) Subtract member function to perform matrix subtraction using objects f) Multiply member function to perform matrix multiplication using objects . CODING :- #include<iostream.h> //header file #include<conio.h> class Darray //Class definition { protected: //access specifier int a,*ptr = &a,**ptr1 = &ptr; //Pointers declaration & initialization int *arr,*arr1; public: //Access Specifier Darray() //Default Constructor Definition { cout<<"Enter the number of rows = "; cin>>**(ptr1); arr = new int[a * 3]; cout<<"Enter the values in array - "<<endl; for (int i = 0; i < a; i++) //outer for loop execution
  • 38. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 38 P a g e { for (int j = 0; j < 3; j++) //Inner for loop execution { cin>>*(arr + i*3 + j); } } } void input() //Input member function { cout<<"Enter the number of rows = "; cin>>**(ptr1); arr1 = new int[a * 3]; //Dynamic memory allocation cout<<"Enter the values in array - "<<endl; for (int i = 0; i < a; i++) //outer for loop execution { for (int j = 0; j < 3; j++) //inner for loop execution { cin>>*(arr1 + i*3 + j); } } } void output() //Output member function { cout<<"Elements in first array -”<<endl; for (int i = 0; i < a; i++) //outer for loop { for (int j = 0; j < 3; j++) //inner for loop { cout<<*(arr + i*3 + j)<<"t";
  • 39. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 39 P a g e } cout<<endl; } cout<<"Elemnets in second array -”<<endl; for (int i = 0; i < a; i++) //outer for loop { for (int j = 0; j < 3; j++) //inner for loop { cout<<*(arr1 + i*3 + j)<<"t"; } cout<<endl; } } void add() //add member function { cout<<"Sum of first & second matrix -”<<endl; for (int i = 0; i < a; i++) //outer for loop { for (int j = 0; j < 3; j++) //inner for loop { cout<<(*(arr + i*3 + j) + *(arr1 + i*3 + j))<<"t"; } cout<<endl; } } void subtract() //subtract member function { cout<<"Subtraction of first matrix from second matrix -”<<endl;
  • 40. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 40 P a g e for (int i = 0; i < a; i++) //outer for loop { for (int j = 0; j < 3; j++) //inner for loop { cout<<(*(arr + i*3 + j) - *(arr1 + i*3 + j))<<"t"; } cout<<endl; } } void multiply() //multiply member function { int res[3][3] = 0; cout<<"Multiplication of first & second matrix -”<<endl; for (int i = 0; i < a; i++) //outer for loop { for (int j = 0; j < 3; j++) //inner for loop { res[i][j]=0; for (int k = 0; k < 3; k++) { res[i][j] += (*(arr + i*3 + k)) * (*(arr1 + k*3 + j)); } cout<<res[i][j]<<"t"; } cout<<endl; } } }; int main() //main function
  • 41. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 41 P a g e { Darray D1; //Object declaration of class “Darray” D1.input(); //calling member function through object D1.output(); //calling member function through object D1.add(); //calling member function through object D1.subtract(); //calling member function through object D1.multiply(); //calling member function through object cout << endl; getch(); //Hold the Console return 0; } OUTPUT :-
  • 42. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 42 P a g e 12.Write a program to create class complex having data members to store real and imaginary part. provide following facilities: a. Add two complex no. using objects b. Subtract two complex no. using objects c. Multiply two complexes no. using objects d. Divide two complex no. using objects CODING :- #include<iostream.h> //header file #include<conio.h> //header file class Complex //class Definition { private: //Access specifier float real; //Data member float imgn; //Data Member public: //access specifier Complex(float r = 0, float i = 0) : real(r), imgn(i) //Constructor to initialize the complex number { } Complex add(const Complex& c) // Function to add two complex numbers { return Complex(real + c.real, imgn + c.imgn); } Complex subtract(const Complex& c) // Function to subtract two complex numbers { return Complex(real - c.real, imgn - c.imgn); } Complex multiply(const Complex& c) // Function to multiply two complex numbers {
  • 43. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 43 P a g e return Complex((real * c.real) - (imgn * c.imgn), (real * c.imgn) + (imgn * c.real)); } Complex divide(const Complex& c) // Function to divide two complex numbers { float denominator = (c.real * c.real) + (c.imgn * c.imgn); if (denominator == 0) //if statement { cout << "Division by zero is undefined." << endl; return Complex(); } return Complex(((real * c.real) + (imgn * c.imgn)) / denominator, ((imgn * c.real) - (real * c.imgn)) / denominator); } void display() //display member Function { cout << "Complex number: " << real << " + " << imgn << "i" << endl; } }; int main() //main function { clrscr(); //clear screen function Complex c1(1, 3); //class object declaration and initialization Complex c2(2, 4); Complex sum = c1.add(c2); //calling member function of class through object Complex difference = c1.subtract(c2); Complex product = c1.multiply(c2);
  • 44. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 44 P a g e Complex quotient = c1.divide(c2); cout <<" Sum :- "<<endl; // Displaying results sum.display(); cout <<endl<<" Difference :- "<<endl; difference.display(); cout <<endl<<" Multiplication :- "<<endl; product.display(); cout <<endl<<" Division :- "<<endl; quotient.display(); getch(); return 0; } OUTPUT :-
  • 45. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 45 P a g e Friend Function 13. Create class Polar having data member radius and angle. It contains member functions taking input in data members and member function for displaying value of data members. Class Polar contains declaration or friend function add which accepts two objects of class Polar and returns object of class Polar after addition. Test the class using main function and objects of class Polar. CODING :- #include <iostream.h> //header file #include<conio.h> //header file class polar //class definition { int radius , angle; //Data members public: //Access Specifier void get() //member function { cout<<"Enter radius = " ; cin>>radius ; cout<<"Enter angle = " ; cin>>angle ; } void put() //member function { cout<<endl<<"Radius = "<<radius; cout<<endl<<"Angle = "<<angle<<endl; } friend polar add(polar , polar); //Friend function declaration }; polar add(polar a , polar b) //Friend Function definition {
  • 46. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 46 P a g e polar c; //variable Declaration c.radius = a.radius + b.radius; c.angle = a.angle + b.angle; return c; } int main() //Main Function { polar a , b , c; // Object Declaration of class “Polar” clrscr(); cout<<"Enter 1 st object -"<<endl; a.get(); //Accessing member function of class through object cout<<endl<<"Enter 2 nd object -"<<endl; b.get(); //Accessing member function of class through object cout<<endl<<"Object's values are :-"<<endl; cout<<"1st obj :-"; a.put(); //Accessing member function of class through object cout<<endl<<"2nd obj :-"; b.put(); //Accessing member function of class through object cout<<endl<<"-: Additon of objects :- "; c = add(a,b); //Adding two objects c.put(); getch(); return 0; }
  • 47. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 47 P a g e OUTPUT :- 14.Write program to create class distance having data members feet and inch (A single object will store distance in form such as 5 feet 3 inch). It contains member functions for taking input in data members and member function for displaying value of data members. Class Distance contains declaration of friend function add which accepts two objects of class Distance and returns object of class Distance after addition. Class Distance contains declaration of another friend function. Subtract that accepts two objects of class Distance and returns object of class Distance after subtraction. Test the class using main function and objects of class Distance. CODING :- #include <iostream.h> //header file #include<conio.h> class Distance //class definition { int feet; //data member int inch; public: //access specifier void inputData() //member function { cout << "Enter feet: "; cin >> feet;
  • 48. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 48 P a g e cout << "Enter inches: "; cin >> inch; } void displayData() //member function definition { cout << "Distance: " << feet << " feet, " << inch << " inches" << endl; } friend Distance add(Distance d1, Distance d2); //friend function declaration friend Distance subtract(Distance d1, Distance d2); }; Distance add(Distance d1, Distance d2) //friend function definition { Distance d3; d3.feet = d1.feet + d2.feet; d3.inch = d1.inch + d2.inch; if (d3.inch >= 12) //if statement { d3.feet++; d3.inch -= 12; } return d3; } Distance subtract(Distance d1, Distance d2) //friend function definition { Distance d3; d3.feet = d1.feet - d2.feet; if (d1.inch < d2.inch) //if statement { d3.feet--; d3.inch = 12 + d1.inch - d2.inch; } else { d3.inch = d1.inch - d2.inch; } return d3;
  • 49. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 49 P a g e } int main() //main function { Distance d1, d2, d3, d4; /object declaration cout << "Enter data for first distance:" << endl; d1.inputData(); //calling member function through object cout << "Enter data for second distance:" << endl; d2.inputData(); cout << "First distance: "; d1.displayData(); cout << "Second distance: "; d2.displayData(); d3 = add(d1, d2); cout << "Sum of distances: "; d3.displayData(); d4 = subtract(d1, d2); cout << "Difference of distances: "; d4.displayData(); getch(); return 0; } OUTPUT :- 15.Write a program to create class Mother having data member to store salary of Mother, create another class Father having data member to store salary of Father. Write a friend function, which accepts objects
  • 50. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 50 P a g e of class Mother, and Father and prints Sum of Salary of Mother and Father objects. CODING :- #include <iostream.h> //header file #include<conio.h> class father; //Forward declaration class mother //class definition { int sal; //data member friend int sum(mother,father); //Friend function declaration }; class father { int sal; friend int sum(mother,father); }; int sum(mother a,father b) //friend Function to sum & print salary { a.sal = 100000; b.sal = 200000; cout<<"Sum of salary of mother and father = "<<a.sal + b.sal; } int main() //main function { mother m; //object declaration father f; sum(m,f); //Sum function called getch(); return 0; } OUTPUT :-
  • 51. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 51 P a g e Friend Class 16. Write a Program to create class Mother having data member to store salary of Mother, create another class Father having data member to store salary of Father. Declare class Father to be friend class of Mother. Write a member function in Father, which accepts object of class Mother and Father Objects. Create member function in each class to get input in data member and to display the value of data member. CODING :- #include <iostream.h> //header file #include<conio.h> class mother //class definition { int slry; //data member friend class father; //Friend class declaration public: //access specifier void get() //member function { cout<<"Enter the salary - "; cin>>slry; cout<<"Salary of Mother = "<<slry; } }; class father //friend class Definition { int slry; public: //access specifier void get() //member function
  • 52. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 52 P a g e { cout<<endl<<endl<<”Father -”<<endl<<"Enter the salary - "; cin>>slry; cout<<"Salary of father = "<<slry; } int sum(mother a,father b) //sum member function { cout<<endl<<endl<<"Sum of salary of mother and father = "<<a.slry + b.slry; return 0; } }; int main() //main function { clrscr(); mother mtr; //declaration of class “mother” object “mtr” father ftr; //declaration of class “mother” object “mtr” mtr.get(); //calling member function through object ftr.get(); //calling member function through object ftr.sum(mtr,ftr); //calling member function through object getch(); return 0; } OUTPUT :-
  • 53. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 53 P a g e STATIC DATA MEMBER 17. Create a class Counter having a static data member, which keeps track of no. of objects created of type Counter. One static member function must be created to increase value of static data member as the object is created. One static member function must be created to decrease value of static data member as the object is destroyed. One static member function must be created to display the current value of static data member. Use main function to test the class Counter. CODING :- #include<iostream.h> //header file #include<conio.h> //header file class Counter //class defition { public: //access specifier static int count; //static member function declaration Counter() //Default constructor definition { count++; cout<<" tCreated Object - " << count<<endl; } ~Counter() //Destructor Difinition { count--; cout<<" tDestroyed Object - "<<count<<endl; } static void displayCount() //static member function {
  • 54. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 54 P a g e cout<<" Current count - "<<count<<endl; } }; int Counter::count = 0; int main() //main function { clrscr(); cout<<" Constructor called :- "<<endl; Counter *c1 = new Counter(); //new operator used and assigns the address of class object Counter *c2 = new Counter(); Counter *c3 = new Counter(); Counter::displayCount(); //calls the static member function cout<<" Destructor called :- "<<endl; delete c1; //delete operator used to delete the allocated memory by class object delete c2; Counter::displayCount(); getch(); //hold the console return 0; } OUTPUT :- P.T.O.
  • 55. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 55 P a g e STRUCTURE AND CLASS 18.Define structure student. Structure student has data members for storing name, roll no, name of three subjects and marks. Write member function to store and print data. CODING :- #include <iostream.h> //header file #include<conio.h> //header file struct student //structure definition { char name[50]; //data member of structure int rollNo; char subjects[3][50]; float marks[3]; void getdata() //member function of structure { cout<<"Enter student's name : "; cin.getline(name, 50); cout<<"Enter roll number : "; cin>>rollNo; for (int i = 0; i < 3; i++) //for loop execution { cout<<"Enter subject "<< i + 1 <<" name : "; cin.ignore(); cin.getline(subjects[i], 50); cout<<"Enter marks for "<<subjects[i]<<" : "; cin>>marks[i]; } } void putdata() //member function of structure { cout<<endl<<"Student Information :-" <<endl; cout<<"Name - " << name <<endl; cout<<"Roll Number - " <<rollNo<<endl; for (int i = 0; i < 3; i++) //for loop execution { cout<<"Subject " << i + 1 << " - " << subjects[i] << endl; cout<<"Marks - " << marks[i] << endl; }
  • 56. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 56 P a g e } }; int main() //main function { clrscr(); //clear the screen function student s1; //structure variable declaration by explicit method s1.getdata(); //accessing structure member function through variable s1.putdata(); getch (); //hold the consol return 0; } OUTPUT :- P.T.O.
  • 57. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 57 P a g e COPY CONSTRUCTOR , CONSTRUCTOR OVERLOADING , THIS POINTER , CONSTRUCTOR WITH DEFAULT ARGUMENT 19.write program to create a class Polar which has data member radius and angle, define overloaded constructor to initialize object and copy constructor to initialize one object by another existing object keep name of parameter of parameterized constructor same as data members. Test function of the program in main function. CODING :- #include<iostream.h> //header file #include<conio.h> //header file class Polar //class difinition { public: //access specifier int radius, angle; //data member Polar(int radius, int angle) //Parameterized constructor { Polar::radius = radius; Polar::angle = angle; } Polar(Polar &p1) //Copy constructor { radius = p1.radius; angle = p1.angle; } void display() //member function { cout<<"Radius = "<<radius<<"tAngle = "<<angle; } };
  • 58. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 58 P a g e int main() //main function { clrscr(); Polar p1(10,20); //object declaration of class Polar p2(p1); p2.display(); //calling member function through object cout << endl; getch(); return 0; } OUTPUT :- 20.write program to create a class Polar which has data member radius and angle, use constructor with default arguments to avoid constructor overloading and copy constructor to initialize one object by another existing object keep name of parameter of parameterized constructor same as data members. Test functioning of the program in main function CODING :- #include <iostream.h> //header file #include<conio.h> //header file class Polar //class definition { public: //access specifier int radius, angle; //data member
  • 59. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 59 P a g e Polar(int radius=15, int angle=30) //Parameterized constructor with default arguments { Polar::radius = radius; Polar::angle = angle; } Polar(Polar &p1) //Copy constructor { radius = p1.radius; angle = p1.angle; } void disp() //display member function { cout<<"nRadius = "<<radius<<"tAngle = "<<angle; } }; int main() //main function { clrscr(); Polar p1; //object declaration of class Polar p2(p1); p2.disp(); //calling function through object getch(); return 0; } OUTPUT :-
  • 60. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 60 P a g e FUNCTION OVERLOAD, REFERENCE VARIABLE, PARAMETER PASSING BY ADDRESS, STATIC FUNCTION 21.Write a class having name Calculate that uses static overloaded function to calculate area of circle, area of rectangle and area of triangle. CODING :- #include <iostream.h> //header file #include<conio.h> //header file class Calculate //class definition { public: //access specifier static int area(int a) //static member function { float area = a*a*3.14; cout<<"Area of circle (radius * radius * 3.14)= "<<area; } static int area(int l,int b) //static overloaded function { float area = l*b; cout<<endl<<"Area of rectangle (length * width)= "<<area; } static int area(int b,int h,float c) { float area = c*h*b; cout<<endl<<"Area of triangle = "<<area; } }; int main() //min function
  • 61. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 61 P a g e { clrscr(); Calculate::area(5); //static member function calling Calculate::area(5,10); //static member function calling Calculate::area(5,10,1.5); //static member function calling cout << endl; getch(); return 0; } OUTPUT :- 22.write a class ArraySort that uses static overloaded function to sort an array of floats, an array of integers. CODING :- #include <iostream.h> //header file #include<conio.h> class ArraySort //class definition { public: //access specifier static void sort(float arr[], int n) //static member function { for(i = 0; i < n - 1; i++) //outer for loop execution { for (int j = 0; j < n - i - 1; j++) //inner for loop execution
  • 62. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 62 P a g e { if (arr[j] > arr[j + 1]) //if statement { float temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } static void sort(int arr[], int n) //static member function { for (i = 0; i < n - 1; i++) //outer for loop execution { for (int j = 0; j < n - i - 1; j++) //inner for loop { if (arr[j] > arr[j + 1]) //if statment { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } }; int main() //main function { clrscr();
  • 63. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 63 P a g e int i; float floatArr[] = {5.6, 3.2, 1.4, 7.8, 9.0};//variable initialization int intArr[] = {23, 12, 45, 38, 19}; int n1 = sizeof(floatArr) / sizeof(floatArr[0]); int n2 = sizeof(intArr) / sizeof(intArr[0]); ArraySort::sort(floatArr, n1); //calling static member function ArraySort::sort(intArr, n2); cout << "Sorted float array :- "; for (i = 0; i < n1; i++) //for loop { cout<<floatArr[i]<< " "; } cout<<endl<<"Sorted integer array :- "; for (i = 0; i < n2; i++) //for loop { cout<<intArr[i] << " "; } getch(); return 0; } OUTPUT :-
  • 64. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 64 P a g e 23.Write a program using class, which uses static overloaded function to swap two integers, two floats methods use reference variable. CODING :- #include <iostream.h> //header file #include<conio.h> class Swap //class difinition { public: //access specifier static int swp(float &a,float &b) //Swapping through reference variable { float t = a; a = b; b = t; } static int swp(int &a,int &b) //static member function { int t = a; a = b; b = t; } }; int main() //main function { int a = 10,b = 20; //variable initialization float c = 10.5,d =19.01; cout<<"Before swap :-"<<endl; cout<<"a = "<<a<<"tb = "<<b<<endl<<"c = "<<c<<"td = "<<d<<endl; Swap::swp(a,b); //Calling static function by reference Swap::swp(c,d); cout<<"After swap :-"<<endl; cout<<"a = "<<a<<"tb = "<<b<<endl<<"c = "<<c<<"td = "<<d; getch(); return 0; } OUTPUT :-
  • 65. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 65 P a g e 24.Write a program using class, which uses static overloaded function to swap two integers, two floats methods use parameter passing by address. CODING :- #include <iostream.h> //header file #include<conio.h> class Swap //class difinition { public: //ACCESS SPECIFIER static int swp(float *a,float *b) //Swapping by address { float t = *a; *a = *b; *b = t; } static int swp(int *a,int *b) //static member function { int t = *a; *a = *b; *b = t; } }; int main() //main function { int a = 5,b = 50; //variable initialization float c = 1.414,d =3.14; cout<<"Before swap - n"; cout<<"a = "<<a<<"tb = "<<b<<endl<<"c = "<<c<<"td = "<<d<<endl; Swap::swp(&a,&b); //calling statc member function ans Passing address of variables Swap::swp(&c,&d); cout<<"After swap -"<<endl; cout<<"a = "<<a<<"tb = "<<b<<endl<<"c = "<<c<<"td = "<<d; getch(); return 0; }
  • 66. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 66 P a g e OUTPUT :- STRING, POINTER, AND OPERATOR OVERLOADING 25.Create class String having pointer to character as data member and provide following facilities: a. Constructor for initialization and memory allocation b. Destructor for memory release c. Overloaded operators + to add two string object d. Overloaded operator = to assign one string object to other string object e. Overloaded operator = = to compare whether the two string objects are equal or not f. Overloaded operator < to compare whether first string object is less than second string object g. Overloaded operator > to compare whether first string object is greater than second string object or not h. Overloaded operator <= to compare whether first string object is less than of equal to second string object or not i. Overloaded operator >= to compare whether first string object is greater than or equal to second string object j. Overloaded operator !=to compare whether first string object is not equal to second string object or not k. Overloaded insertion and extraction operators for input in data member and display output of data members. CODING :- #include<iostream> #include<cstring> class String { private:
  • 67. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 67 P a g e char *str; public: // Constructor String(const char* s = nullptr) { if (s != nullptr) { str = new char[strlen(s) + 1]; strcpy(str, s); } else { str = new char[1]; *str = '0'; } } // Destructor ~String() { delete[] str; } // Overloaded + operator String operator+(const String& rhs) const { String result; result.str = new char[strlen(str) + strlen(rhs.str) + 1]; strcpy(result.str, str); strcat(result.str, rhs.str); return result; } // Overloaded = operator
  • 68. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 68 P a g e String& operator=(const String& rhs) { if (this != &rhs) { delete[] str; str = new char[strlen(rhs.str) + 1]; strcpy(str, rhs.str); } return *this; } // Overloaded == operator bool operator==(const String& rhs) const { return strcmp(str, rhs.str) == 0; } // Overloaded < operator bool operator<(const String& rhs) const { return strcmp(str, rhs.str) < 0; } // Overloaded > operator bool operator>(const String& rhs) const { return strcmp(str, rhs.str) > 0; } // Overloaded <= operator bool operator<=(const String& rhs) const { return strcmp(str, rhs.str) <= 0; }
  • 69. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 69 P a g e // Overloaded >= operator bool operator>=(const String& rhs) const { return strcmp(str, rhs.str) >= 0; } // Overloaded != operator bool operator!=(const String& rhs) const { return strcmp(str, rhs.str) != 0; } // Overloaded << operator for output friend std::ostream& operator<<(std::ostream& os, const String& s) { os << s.str; return os; } // Overloaded >> operator for input friend std::istream& operator>>(std::istream& is, String& s) { char buffer[1000]; is >> buffer; delete[] s.str; s.str = new char[strlen(buffer) + 1]; strcpy(s.str, buffer); return is; } }; int main() { String s1("Hello");
  • 70. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 70 P a g e String s2("World"); // Testing various operators String s3 = s1 + s2; std::cout << "Concatenation: " << s3 << std::endl; String s4; s4 = s1; std::cout << "Assignment: " << s4 << std::endl; std::cout << "Comparison: " << (s1 == s2 ? "Equal" : "Not Equal") << std::endl; std::cout << "Comparison: " << (s1 < s2 ? "Less" : "Not Less") << std::endl; // Testing input and output operators std::cout << "Enter a string: "; String s5; std::cin >> s5; std::cout << "You entered: " << s5 << std::endl; return 0; } OUTPUT :-
  • 71. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 71 P a g e 26. Create a class Matrix having data member double dimension array of floats of size 3*3. Provide following facilities: a. Overloaded extraction operator for data input b. Overloaded insertion operator for data output c. Overloaded operator + for adding two matrix using objects d. Overloaded operator – for subtracting two matrix using objects e. Overloaded operator * for multiply two matrix using objects CODING :- #include <iostream.h> //header file #include<conio.h> class Matrix //class definition { float arr[3][3]; // Array variable declaration public: //access specifier void operator >>(float objarr[3][3]) //Overloaded Extraction operator { for (int i = 0; i < 3; i++) //outer for loop { for (int j = 0; j < 3; j++) //inner for loop { arr[i][j] = objarr[i][j]; } } } void operator<<(ostream& c) //Insertion Operator { for (int i = 0; i < 3; i++) //outer for loop { for (int j = 0; j < 3; j++) //inner for loop { c<<arr[i][j]<<"t"; } c<<endl; } } void operator +(Matrix m) //Addition Operator { for (int i = 0; i < 3; i++) //outer for loop { for (int j = 0; j < 3; j++) //inner for loop { cout<<(arr[i][j] + m.arr[i][j])<<"t"; }
  • 72. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 72 P a g e cout<<endl; } } void operator -(Matrix m) //Subtraction Operator { for (int i = 0; i < 3; i++) //outer for loop { for (int j = 0; j < 3; j++) //inner for loop { cout<<(arr[i][j] - m.arr[i][j])<<"t"; } cout<<endl; } } void operator *(Matrix m) //Multiplication Operator { for (int i = 0; i < 3; i++) //outer for loop { for (int j = 0; j < 3; j++) //inner for loop { int k = 0; float a = 0; for (k = 0; k < 3; k++) { a += (arr[i][k] * m.arr[k][j]); } cout<<a<<"t"; } cout<<endl; } } }; int main() //main function { float arr[3][3]={{3.1, 4.03, 5.7},{1.2, 2.5, 3.9},{6.6, 7.5, 8.2}}; //variable initialization float arr2[3][3]={{4.3, 8.4, 9.9},{4.56, 2.01, 1.1},{9.9, 0.0, 7.6}}; Matrix m1,m2; //object declaration of class m1>>arr; //Calling Overloaded Operators m2>>arr2; m1<<cout; cout<<"Second Matrix - "<<endl; m2<<cout; cout<<"Sum of array - "<<endl; m1+m2;
  • 73. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 73 P a g e cout<<"Subtraction of array - "<<endl; m1-m2; cout<<"Multiplication of array -"<<endl; m1*m2; cout << endl; getch(); return 0; } OUTPUT :-
  • 74. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 74 P a g e OPEARATOR OVERLOADING WITH FRIEND FUNCTION 27.Create a class Polar having radius and angle as data members. Provide following facilities: a) Overloaded insertion and extraction operators for data input and display b) Overloaded constructor for initialization of data members c) Overloaded operator + to add two polar co-ordinates using objects of class Polar CODING :- #include <iostream.h> //header file #include<conio.h> class Polar //class definition { int radius,angle,i=0,k=0; public: //access specifier Polar() //default constructor {} Polar(int a,int b) //Constructor for initializing values { radius = a; angle = b; } Polar& operator >>(int a) //Overloaded operator for data input { if (i==0) //IF STATMENT { radius = a; i++; return *this; } if (i==1) { angle = a; } } Polar& operator <<(int a) { if (a==1) { cout<<endl<<radius; return *this; } if (a==2) { cout<<"t"<<angle;
  • 75. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 75 P a g e return *this; } } Polar operator+(Polar p2) //Operator to add two objects { cout<<endl<<"Sum of polar co-ordinates is- "<<endl; cout<<"Radius = "<<radius+p2.radius; cout<<"tAngel = "<<angle+p2.angle; } }; int main() //main function { Polar p1,p2(15,12); //object declaration of class p1>>10>>20; cout<<"First object -"<<endl; p1<<1<<2; //1 for radius & 2 for angle. cout<<endl<<"Second object -"<<endl; p2<<1<<2; p1+p2; getch(); return 0; } OUTPUT :- 28.Create class DegreeCelsius having a single data member to hold value of temperature in degree Celsius. Provide following facilities: a. Overloaded operator ++ which will increase value of dta member by !(consider postfix and prefix operator overloading). b. Overloaded operator – which will decrease value of data member by1 (consider postfix and prefix operator overloading) c. Overloaded insertion and extraction operators for input in data member and display value of data member. CODING :- #include <iostream.h> //header file #include<conio.h> class DegreeCelsius //class definition {
  • 76. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 76 P a g e private: //access specifier float temp; //data member public: DegreeCelsius() //constructor definition { temp = 0.0; } DegreeCelsius(float t) //parameterized constructure { temp = t; } float getTemp() const { return temp; } void setTemp(float t) { temp = t; } DegreeCelsius operator++() //overloaded operator ++ { temp++; return *this; } DegreeCelsius operator++(int) { DegreeCelsius tempC = *this; temp++; return tempC; } DegreeCelsius operator--() //overloaded operator -- { temp--; return *this; } DegreeCelsius operator--(int) { DegreeCelsius tempC = *this; temp--; return tempC; }
  • 77. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 77 P a g e friend ostream& operator<<(ostream& out, const DegreeCelsius& obj) //insertion operator overloading { out << obj.temp << " degrees Celsius"; return out; } friend istream& operator>>(istream& in, DegreeCelsius& obj) //extraction operator overloading { in >> obj.temp; return in; } }; int main() //main function { clrscr(); DegreeCelsius temp1, temp2; //object declaration of class cout << "Enter temperature in degrees Celsius : "; cin >> temp1; cout << "Temperature 1: " << temp1 << endl; temp2 = temp1++; cout << "Temperature 1: " << temp1 << endl; cout << "Temperature 2: " << temp2 << endl; temp2 = ++temp1; cout << "Temperature 1: " << temp1 << endl; cout << "Temperature 2: " << temp2 << endl; temp2 = temp1--; cout << "Temperature 1: " << temp1 << endl; cout << "Temperature 2: " << temp2 << endl; temp2 = --temp1; cout << "Temperature 1: " << temp1 << endl; cout << "Temperature 2: " << temp2 << endl; getch(); return 0; } P.T.O.
  • 78. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 78 P a g e OUTPUT :-
  • 79. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 79 P a g e OPERATOR OVERLOADING AND DATA TYPE CONVERSION 29.Create a class Polar that contains data member radius and angle. Create another class Cartesian in the same program and provide following facilities: a. It should be possible to assign object of polar class to object of Cartesian class b. It should be possible to assign object of Cartesian class to object of polar class CODING :- #include <iostream.h> //header file #include <cmath.h> //header file #include<conio.h> class Polar //class definition { private: //access specifier double radius; //data member double angle; public: //ACCESS SPECIFIER Polar(double r, double a) //parameterized constructor { radius = r; angle = a; } double getRadius() const { return radius; } double getAngle() const {
  • 80. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 80 P a g e return angle; } void setRadius(double r) { radius = r; } void setAngle(double a) { angle = a; } class Cartesian //class definiton { private: //access specifier double x; //data member double y; public: //access specifier Cartesian(double r, double a) //parameterized constructor { x = r * cos(a); y = r * sin(a); } double getX() const { return x; }
  • 81. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 81 P a g e double getY() const { return y; } void setX(double x) { this->x = x; } void setY(double y) { this->y = y; } }; Cartesian toCartesian() { return Cartesian(radius, angle); } }; class Cartesian { private: double x; double y; public:
  • 82. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 82 P a g e Cartesian(double x, double y) { this->x = x; this->y = y; } double getX() const { return x; } double getY() const { return y; } void setX(double x) { this->x = x; } void setY(double y) { this->y = y; } Polar toPolar() { double radius = sqrt(x * x + y * y);
  • 83. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 83 P a g e double angle = atan2(y, x); return Polar(radius, angle); } }; int main() //main function { Polar polar(2.0, 0.5); //object initialization of class Cartesian cartesian = polar.toCartesian(); cout << "Polar coordinates: (radius, angle) = (" << polar.getRadius() << ", " << polar.getAngle() << ")" << endl; cout << "Cartesian coordinates: (x, y) = (" << cartesian.getX() << ", " << cartesian.getY() << ")" << endl; Cartesian cartesian2(1.0, 1.0); Polar polar2 = cartesian2.toPolar(); cout << "Polar coordinates: (radius, angle) = (" << polar2.getRadius() << ", " << polar2.getAngle() << ")" << endl; cout << "Cartesian coordinates: (x, y) = (" << cartesian2.getX() << ", " << cartesian2.getY() << ")" << endl; getch(); return 0; } OUTPUT :-
  • 84. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 84 P a g e 30. Create a class Fahrenheit that contains a data member to hold temperature in Fahrenheit . Create another class Celsius that contains a data member to hold temperature in Degree Celsius; in the same program and provide following facilities: a. It should be possible to assign object of Fahrenheit class to object of Celsius class b. It should be possible to assign object of Celsius class to object of Fahrenheit class c. It should be possible to compare objects of class Fahrenheit and Celsius to find out which object contains higher temperature. CODING :- #include <iostream.h> #include<conio.h> class Fahrenheit { private: double temp; public: Fahrenheit(double t) { temp = t; } double getTemp() const { return temp; } void setTemp(double t) { temp = t; } Celsius toCelsius() const { double tempC = (temp - 32) * 5 / 9; return Celsius(tempC); } operator Celsius() const { return toCelsius(); } bool operator>(const Fahrenheit& f2) const { return temp > f2.temp; } bool operator<(const Fahrenheit& f2) const {
  • 85. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 85 P a g e return temp < f2.temp; } }; class Celsius { private: double temp; public: Celsius(double t) { temp = t; } double getTemp() const { return temp; } void setTemp(double t) { temp = t; } Fahrenheit toFahrenheit() const { double tempF = temp * 9 / 5 + 32; return Fahrenheit(tempF); } operator Fahrenheit() const { return toFahrenheit(); } bool operator>(const Celsius& c2) const { return temp > c2.temp; } bool operator<(const Celsius& c2) const { return temp < c2.temp; } }; int main() { Fahrenheit f1(72); Celsius c1 = f1; // Implicit conversion from Fahrenheit to Celsius using operator() cout << "Temperature in Fahrenheit: " << f1.getTemp() << endl; cout << "Temperature in Celsius: " << c1.getTemp() << endl; Celsius c2(30); Fahrenheit f2 = c2; // Explicit conversion from Celsius to Fahrenheit using constructor
  • 86. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 86 P a g e cout << "Temperature in Celsius: " << c2.getTemp() << endl; cout << "Temperature in Fahrenheit: " << f2.getTemp() << endl; Fahrenheit f3(80); Celsius c3(26.67); if (f3 > c3) { cout << "Fahrenheit object f3 is equal to Celsius object c3" << endl; } else { cout << "Celsius object c3 has higher temperature than Fahrenheit object f3" << endl; } getch(); return 0; } OUTPUT :-
  • 87. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 87 P a g e VOID POINTER , POINTER AND POINTER TO OBJECT 31.Create a program having pointer to void to store address of integer variable then print value of integer variable using pointer to void. Perform the same operation for float variable. CODING :- #include <iostream.h> //header file #include<conio.h> int main() //main function { int num1 = 10; //Declare an integer variable and a void pointer void* ptr1 = &num1; //void pointer declaration and initialiazation cout << "Value of integer variable: " << *(int*)ptr1 << endl; // Print the value of the integer variable using the void pointer float num2 = 5.2; // Declare a float variable void* ptr2 = &num2; //void pointer declaration and initialization cout << "Value of float variable: " << *(float*)ptr2 << endl; getch(); return 0; } OUTPUT :-
  • 88. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 88 P a g e 32.Write program to find biggest number among three numbers using pointer and function. CODING :- #include<iostream.h> //header file #include<conio.h> //header file int findBiggest(int* num1, int* num2, int* num3) // Function using pointers { int biggest = *num1; if (*num2 > biggest) //if statement { biggest = *num2; } if (*num3 > biggest) //if statement { biggest = *num3; } return biggest; } int main() //main function { int num1 = 10, num2 = 15, num3 = 20; // Declare three integer variables int biggestNumber = findBiggest(&num1, &num2, &num3); // Find the biggest number using pointers and function cout<<" Biggest number :- "<<biggestNumber<<endl; // Print the biggest number getch(); return 0; } OUTPUT :- 33.Write swapping program to demonstrate cal by value, call by address and call by reference in a single program. CODING :- #include<iostream.h> //header file #include<conio.h> void value(int a,int b) //Call by value
  • 89. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 89 P a g e { int t = a; a = b; b = t; } void address(int *a,int *b) //Call by address { int t = *a; *a = *b; *b = t; } void reference(int &a,int &b) //Call by reference { int t = a; a = b; b = t; } int main() //main function { int a = 40,b = 50; //Variable Initialization cout<<"Before Swapping :- "<<endl; cout<<"a = "<<a<<"tb = "<<b<<endl; value(a,b); //calling function by Value cout<<"After call by value :- "<<endl; cout<<"a = "<<a<<"tb = "<<b<<endl; address(&a,&b); //calling function by address cout<<"After call by address :- "<<endl; cout<<"a = "<<a<<"tb = "<<b<<endl; reference(a,b); //calling function by reference cout<<"After call by Reference :-"<<endl; cout<<"a = "<<a<<"tb = "<<b; getch(); return 0; } P.T.O.
  • 90. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 90 P a g e OUTPUT :- 34.Write a program to create a class Employee having data members to store name of employee, employee id, salary. Provide member function for data input, output. Use Pointer to object to simulate array of object to store information of 3 employees and test the program in function main. CODING :- #include<iostream.h> //header file #include<conio.h> //header file class Employee //class definition { private: //access specifier char name[50]; //data member int Id; float salary; public: //access specifier void inputData() //member function for input data { cout<<"Enter employee name : "; cin.getline(name, 50); cout<<"Enter employee ID: "; cin >>Id; cout<<"Enter employee salary: "; cin>>salary; } void displayData() //member function to output data { cout<<"Employee Name - "<<name<<endl; cout<<"Employee ID - "<<Id<<endl; cout<<"Employee Salary - "<<salary<<endl;
  • 91. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 91 P a g e } }; int main() //main function { clrscr(); int i; Employee* employees = new Employee[3];//Create an array of Employee objects for (i = 0; i < 3; i++) //For loop for Input data { employees[i].inputData(); } for (i = 0; i < 3; i++) //For loop for Display data { employees[i].displayData(); cout << endl; } delete[] employees; // Delete the dynamically allocated array getch(); return 0; } OUTPUT :-
  • 92. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 92 P a g e INLINE FUNCTION 35.Write a program using inline function to calculate area of circle. CODING :- #include<iostream.h> //header file #include<conio.h> inline int area(int r) //Inline function declaration { return (3.14*r*r); } int main() //main function { clrscr(); int r; cout<<"Enter radius = "; cin>>r; cout<<endl<<"Area = "<<area(r); //Calling inline function getch(); return 0; } OUTPUT :- 36.Write a program using inline function to find minimum of two functions. The inline function should take two arguments and should return the minimum value. CODING :- #include <iostream.h> //header file
  • 93. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 93 P a g e #include<conio.h> inline int minvalue(int x,int y) //Inline function declaration { if (x<y) //if else statement { return x; } else { return y; } } int fnc1(int a) //function definition { return a; } int fnc2(int a) //function definition { return a; } int main() //main function { clrscr(); int a,b; //variable declaration cout<<"Enter two number - "; cin>>a>>b; cout<<"Minimum value = "<<minvalue(fnc1(a),fnc2(b)); //Calling inline function getch(); return 0; } OUTPUT :-
  • 94. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 94 P a g e INHERITANCE 37. Create a class account that stores customer name, account number and type of account. From this derive the classes cur_acct and sav_acct to make them more specific to their requirements. Include necessary member functions in order to achieve the following tasks: a. Accept deposit from customer b. Display the balance c. Compute and deposit interest d. Permit withdrawal and update the balance Check for the minimum balance, impose penalty, necessary and update the balance. CODING :- #include<iostream.h> //header file #include<conio.h> class account //class definition { public: //access specifier char c_name[50],type[45]; //data member float balance=0,deposit; int acc_no; void withdraw() //Member function defination { int a; cout<<endl<<"Enter the amount to withdraw from "<<c_name<<"'s account = "; cin>>a; if (balance>=a) //if statement { balance -= a; cout<<"Wihtdraw Successful!!!"<<endl<<"Your current balacne is "<<balance<<endl; } else { cout<<endl<<"Not enough balance"; } } void checkANDFine() //Function to check minimum balance { cout<<"Minimum balance is Rs. 2000, below that penalty of 200 will be fined."; if (balance < 2000) //if else statement { balance -= 200; cout<<endl<<"So after fine "<<c_name<<"'s current balance is = "<<balance; }
  • 95. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 95 P a g e else { cout<<endl<<"No penalty imposed."; } } void deposite() //Function to deposit money { float a; cout<<"Enter amount to deposit for "<<c_name<<" = "; cin>>a; balance += a; } void disp() { cout<<"Customer Name = "<<c_name<<"nType = "<<type<<"tBalance = "<<balance; } }; class cur_acct:public account //Class declaration for CURRENT account { public: cur_acct(); cur_acct(char a[50],int b,char c[45]) { c_name=a; acc_no=b; type=c; } }; class sav_acct:public account //Class declaration for SAVINGS account { public: sav_acct(char a[50],int b,int intrst,char[45] c="Savings") { c_name=a; acc_no=b; type=c; interest = intrst; } int interest; void disp() { cout<<"Customer Name = "<<c_name<<"nType = "<<type<<"tBalance = "<<balance<<"tInterest = "<<interest; } void dispInterest() { float a = (balance*interest)/100;
  • 96. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 96 P a g e balance += a; cout<<endl<<"Interest of "<<interest<<"% "<<" on "<<c_name<<"'s balance is = "<<a<<"tBalance = "<<balance; } }; int main() //main function { cur_acct c1("Yashwant",101,"Current"); c1.deposite(); c1.disp(); cout<<endl<<endl; sav_acct c2("Yamini",102,3); c2.deposite(); c2.disp(); c2.dispInterest(); cout<<endl; c1.withdraw(); cout<<endl; c2.checkANDFine(); cout << endl; getch(); return 0; } OUTPUT :-
  • 97. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 97 P a g e 38.Create a class circle with data member radius; provide member function to calculate area. Derive a class sphere from class circle; provide member function to calculate volume. Derive class cylinder from class sphere with additional data member for height and member function to calculate volume. CODING :- #include <iostream.h> //header file #include <conio.h> class circle //Base class definition { protected: //access specifier int radius; //data member public: //access specifier void area() //Member function to calculate area of circle { cout<<"Area of circle = "<<(float)(3.14*radius*radius); } void get() //member function { cout<<"Enter the radius = "; cin>>radius; } }; class sphere:public circle //intermediate class definition { public: //access specifier void sp_volume() //Function to calculate volume of sphere { cout<<endl<<"Volume of sphere = "<<(float)((4/3)*3.14*radius*radius*radius); }
  • 98. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 98 P a g e }; class cylinder:public sphere //child class definition { int height; public: //access specifier void cy_volume() //Function to calculate volume of cylinder { cout<<"Volume of cylinder = "<<(float)(3.14*radius*radius*height); } void cy_get() { cout<<endl<<"Enter the height = "; cin>>height; } }; int main() //main function { cylinder obj; //object declaration obj.get(); //calling function through object obj.area(); obj.sp_volume(); obj.cy_get(); obj.cy_volume(); getch(); return 0; } P.T.O.
  • 99. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 99 P a g e OUTPUT :- 39.Consider an example of declaring the examination result. Design three classes:- student, exam and result. The student class has data members such as that representing roll number, name of student. Create the class exam, which contains data members representing name of subject, minimum marks, maximum marks, obtained marks for three subjects. Derive class result from both student and exam classes. Test the result class in main function. CODING :- #include<iostream.h> //header file #include<conio.h> class Student //base class definition { private: //access specifier int rollNumber; //data member char name[50]; public: //access specifier void inputSData() //member function to store student data { cout<<"Enter roll number : "; cin>>rollNumber; cout<<"Enter student name : "; cin.getline(name, 50); } void showSData() //member function to show student data { cout<<"Roll Number - "<<rollNumber<<endl; cout<<"Student Name - "<<name<<endl; } }; class Exam //base class definition { private: //access specifier char subjectName[50]; //data member
  • 100. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 100 P a g e int minMarks; int maxMarks; int obtMarks[3]; public: //access specifier void inputsubData() //member function to input subject data { cout<<"Enter subject name : "; cin.getline(subjectName, 50); cout<<"Enter minimum marks: "; cin>>minMarks; cout<<"Enter maximum marks : "; cin >> maxMarks; cout<<"Enter obtained marks for three subjects : "; for (int i = 0; i < 3; i++) //for loop execution { cin>>obtMarks[i]; } } void showsubData() //member function to show subject data { cout << "Subject Name - " << subjectName << endl; cout << "Minimum Marks - " << minMarks << endl; cout << "Maximum Marks - " << maxMarks << endl; cout << "Obtained Marks - "; for (int i = 0; i < 3; i++) { cout << obtMarks[i] << " "; } cout << endl; } }; class Result : public Student, public Exam //multiple inheritance used here { private: double totalMarks; double averageMarks; char grade; public: void calculateResult() { totalMarks = 0; for (int i = 0; i < 3; i++)
  • 101. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 101 P a g e { totalMarks += obtainedMarks[i]; } averageMarks = totalMarks / 3; if (averageMarks >= 90) { grade = 'A'; } else if (averageMarks >= 80) { grade = 'B'; } else if (averageMarks >= 70) { grade = 'C'; } else if (averageMarks >= 60) { grade = 'D'; } else { grade = 'F'; } } void displayResult() { showSData(); showsubData(); cout << "Total Marks: " << totalMarks << endl; cout << "Average Marks: " << averageMarks << endl; cout << "Grade: " << grade << endl; } }; int main() //main function { clrscr(); Result studentResult; //object initialization studentResult.inputSData(); studentResult.inputsubData(); studentResult.calculateResult(); cout<<”t -: Student Result :- “<<endl; studentResult.displayResult(); getch(); return 0;
  • 102. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 102 P a g e } OUTPUT :- P.T.O. yashwant yashwant
  • 103. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 103 P a g e VIRTUAL AND PURE VIRTUAL FUNCTION 40.Create a base class shape having two data members with two member function getdata (pure virtual function) and printarea (not pure virtual function). Derive classes triangle and rectangle from class shape and redefine member functioning of classes using pointer to base class objects and normal objects. CODING :- #include <iostream.h> //header file #include<conio.h> class shape // Class Definition { protected: //access specifier int a,b; //data member public: //access specifier virtual void getdata()=0; //Pure virtual function virtual void printarea() //Virtual function { cout<<"Area = "<<a*b; } }; class triangle : public shape // hierarchical inheritance used here { public: //access specifier void getdata() //Overriding Pure Virtual Function { cout<<"Enter two values triangle - "<<endl; cin>>a>>b; } void printarea() //Function overriding { cout<<"Area = "<<(float)a*b*0.5; } }; class rectangle:public shape // hierarchical inheritance used here { public: //access specifier void getdata() { Cout<<endl<<"Enter two values for rectangle - "<<endl; cin>>a>>b; } }; int main() //main function {
  • 104. PROGRAMMING IN C++ 2023 YASHWANT KUMAR TANDEKAR (BCA 3rd SEM) 104 P a g e triangle t1; //object declaration of class shape *bptr = &t1; //Base class pointer bptr->getdata(); // function call using base class pointer bptr->printarea(); rectangle r1; //object declaration bptr = &r1; (*bptr).getdata(); //Dereferencing base class pointer (*bptr).printarea(); getch(); return 0; } OUTPUT :-