swapping of two numbers in C++
#include <iostream>
using namespace std;
int main()
{
int a,b,c;
cout<<"enter value for a";
cin>>a;
cout<<"enter value for b";
cin>>b;
c=a;
a=b;
b=c;
cout<<"after swapping\n";
cout<<"a="<<a<<"b="<<b;
return 0;
}
Output:
enter value for a 12
enter value for b 22
after swapping
a=22 b=12
swapping of two numbers by reference
#include<iostream>
using namespace std;
void swap(int &x, int &y)
{
int temp;
temp=x;
x=y;
y=temp;
return ;
}
int main()
{
int a,b;
cout<<"before swapping ";
cout<<"value for a is ";
cin>>a;
cout<<"value of b is ";
cin>>b;
swap(a,b);
cout<<" after swapping ";
cout<<"\nthe value of a : "<<a;
cout<<"\nvalue of b is "<<b;
return 0;
}
output:
before swapping value for a is 12
value of b is 22
after swapping
the value of a : 22
value of b is 12
Swapping of two numbers using pointers and functions:
#include<iostream>
using namespace std;
int swap(int*,int*);
int main()
{
int a,b;
cout<<"enter value for a: ";
cin>>a;
cout<<"enter value for b: ";
cin>>b;
swap(&a,&b);
cout<<"value fo a is: "<<a;
cout<<"\nvalue for b is: "<<b;
}
int swap(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
output:
enter value for a: 12
enter value for b: 22
value fo a is: 22
value for b is: 12
Comments
Post a Comment