C++ Examples
- Write a C++ Program to print a welcome text in a separate line.
Write a program to swap private data members of two classes using friend function.
#include<iostream>
using namespace std;
class a1
{
private:
int x,y;
public:
//function to take input from the user
void input()
{
cout<<"Enter first number to swap ";
cin>>x;
cout<<"Enter second number to swap ";
cin>>y;
cout<<"Before swapping numbers are "<<x<<" "<<y<<endl;
}
//function for swapping of two numbers
friend void swapTwoNumbers(a1 &obj);
//function to display two swapped numbers
void display()
{
cout<<"The numbers after swapping are "<<x<<" "<<y;
}
};
void swapTwoNumbers(a1 &obj)
{
//Swapping of numbers using inbuilt swap funtion
swap(obj.x,obj.y);
}
int main()
{
a1 obj1;
obj1.input();
swapTwoNumbers(obj1);
obj1.display();
return 0;
}
Output
Enter first number to swap 25
Enter second number to swap 46
Before swapping numbers are 25 46
The numbers after swapping are 46 25
Another method: Without inbuild swap function
#include<iostream>
using namespace std;
class a1
{
private:
int x,y,z;
public:
//function to take input from the user
void input()
{
cout<<"Enter first number to swap ";
cin>>x;
cout<<"Enter second number to swap ";
cin>>y;
cout<<"Before swapping numbers are "<<x<<" "<<y<<endl;
}
//function for swapping of two numbers
friend void swapTwoNumbers(a1 &obj);
//function to display two swapped numbers
void display()
{
cout<<"The numbers after swapping are "<<x<<" "<<y;
}
};
void swapTwoNumbers(a1 &obj)
{
//Swapping of numbers
obj.z = obj.x;
obj.x = obj.y;
obj.y = obj.z;
}
int main()
{
a1 obj1;
obj1.input();
swapTwoNumbers(obj1);
obj1.display();
return 0;
}
Enter first number to swap 23
Enter second number to swap 45
Before swapping numbers are 23 45
The numbers after swapping are 45 23