Lab 05
Lab 05
Remarks:
Experiment Name:
Friend Function and Friend Class in C++.
Objectives:
1. Write a C++ Program to display the reverse of a number using the friend
function.
Code:
#include<iostream>
using namespace std;
class Number{
private:
int value;
public:
//constructor
Number(int val):value(val){}
friend void reverseNumber(const Number &num);
};
void reverseNumber(const Number &num){
int reversed = 0, temp = num.value;
while(temp!=0){
int digit = temp % 10;
reversed = reversed * 10 + digit;
temp /= 10;
}
cout << "The reverse of "<< num.value << " is: " << reversed <<endl;
}
int main(){
int num;
cout<<"Enter number: ";
cin>>num;
Number number(num);
reverseNumber(number);
return 0;
}
Output:
2. Write a C++ program to find the number and sum of all integer between 100
and 200 which are divisible by 11 with friend function.
Code:
#include<iostream>
using namespace std;
class Range{
private:
int start,end;
public:
//constructor
Range(int s, int e):start(s),end(e) {}
int main(){
Range range(100,200);
DivisibleBy11(range);
return 0;
}
Output:
class Number{
private:
int value;
public:
Number(int val) : value(val){}
Number number(input);
checkSumOfTwoPrimes(number);
return 0;
}
Output:
Discussion:
1. This experiment introduces the concept of friend functions and friend classes in
C++, demonstrating their role in providing controlled access to private data.