Illustrate the use of pointers in swapping two numbers.
Write 2 swap functions, for swapping two integers.
void swap(int,int);
void swap(int*,int*);
#include <iostream>
using namespace std;
void swap(int*,int*);
int main(){
int num1, num2;
cout<<"Swap two numbers\n";
cout<<"Enter first number: \n";
cin>>num1;
cout<<"Enter second number: \n";
cin>>num2;
cout<<"Before swapping \n"<<"first number= "<<num1<<" Second number: "<<num2;
swap(&num1,&num2);
cout<<"\nAfter swapping \n"<<"first number= "<<num1<<" Second number: "<<num2;
return 0;
}
void swap(int*a, int*b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Comments
Leave a comment