Search This Blog

Monday, 11 June 2012

Swapping two integer no.

//This program swaps the values in the variable using function containing reference arguments

#include<iostream.h>
void swap(int &iNum1, int &iNum2);
void main()
{
int iVar1, iVar2;
cout<<"Enter two numbers "<<endl;
cin>>iVar1;
cin>>iVar2;
swap(iVar1, iVar2);
cout<<"In main "<<iVar1<<" "<<iVar2<<endl;
}
void swap(int &iNum1, int &iNum2)
{
int iTemp;
iTemp = iNum1;
iNum1 = iNum2;
iNum2 = iTemp;
cout<<"In swap "<<iNum1<<" "<<iNum2<<endl;
}
Reference arguments are indicated by an ampersand (&) preceding the argument:
int &iNUm1;
the ampersand (&) indicates that iNum1 is an alias for iVar1 which is passed as an argument.
The function declaration must have an ampersand following the data type of the argument:
void swap(int &iNum1, int &iNum2)
The ampersand sign is not used during the function call:
swap(iVar1, iVar2);
The sample output is
Enter two numbers
2
3
In swap 3 2
In main 3 2

No comments:

Post a Comment