Object Oriented Programming Practical 7
Question 1
WAP to declare a class calculation. Display addition, subtraction, multiplication, division of two numbers. Use friend function.
operations.cpp
C
#include <iostream.h>
#include <conio.h>
class Number
{
private:
int n1, n2;
public:
friend int add(int a,int b);
friend int subtract(int a,int b);
friend int multiply(int a,int b);
friend float divide(int a,int b);
};
int add(int n1,int n2)
{
return n1 + n2;
}
int subtract(int n1,int n2)
{
return n1 - n2;
}
int multiply(int n1,int n2)
{
return n1 * n2;
}
float divide(int n1,int n2)
{
if (n2 != 0)
{
return (float)n1/n2;
}
else
{
cout << "Error: Division by zero is not allowed." << endl;
return 0;
}
}
int main() {
int num1, num2;
Number num;
cout << "Enter number 1: ";
cin >> num1;
cout << "Enter number 2: ";
cin >> num2;
cout << "Addition: " << add(num1,num2) << endl;
cout << "Subtraction: " << subtract(num1,num2) << endl;
cout << "Multiplication: " << multiply(num1,num2) << endl;
cout << "Division: " << divide(num1,num2) << endl;
getch();
return 0;
}
Output

Question 2
Write a C++ program to exchange the values of two variables using friend function.
swap.cpp
C
#include <iostream.h>
#include <conio.h>
class Number
{
private:
int value;
public:
void accept(int x)
{
value=x;
}
void display()
{
cout << value << endl;
}
friend void swap(Number &num1, Number &num2);
};
void swap(Number &num1, Number &num2)
{
int temp = num1.value;
num1.value = num2.value;
num2.value = temp;
}
int main()
{
int val1, val2;
cout << "Enter the first value: ";
cin >> val1;
cout << "Enter the second value: ";
cin >> val2;
Number num1,num2;
num1.accept(val1);
num2.accept(val2);
swap(num1, num2);
cout << "Values after swapping:" << endl;
cout << "num1: ";
num1.display();
cout << "num2: ";
num2.display();
getch();
return 0;
}
Output

Question 3
WAP to create two classes test1 and test2 which stores marks of a student. Read value for class objects and calculate average of two tests using friend function.
test.cpp
C
#include <iostream.h>
#include <conio.h>
class Test2;
class Test1
{
private:
int marks1;
public:
friend float average(Test1 t1,Test2 t2);
void setMarks(int m1)
{
marks1 = m1;
}
};
class Test2
{
private:
int marks2;
public:
friend float average(Test1 t1,Test2 t2);
void setMarks(int m2)
{
marks2 = m2;
}
};
float average(Test1 t1,Test2 t2)
{
return (t1.marks1 + t2.marks2) / 2.0;
}
int main() {
int m1, m2;
cout << "Enter the marks for Test1: ";
cin >> m1;
cout << "Enter the marks for Test2: ";
cin >> m2;
Test1 test1;
test1.setMarks(m1);
Test2 test2;
test2.setMarks(m2);
float avg = average(test1, test2);
cout << "The average of the two tests is: " << avg << endl;
getch();
return 0;
}
Output
