How to Swap two numbers without using third variable in c++ using pointers

Category:

//C++ Program Swap two numbers(integer) using pointers
#include
#include
using namespace std;
void swap(short *number1, short *number2);
void main()
{
short number1,number2;
char input;
cout<<"Enter you first Number A = "; cin>>number1; //User giving first number to swap
cout<< endl<<"Enter you first Number B = "; cin>>number2; //User giving second number to swap
cout<< endl<<"Want to Swap y/n "; cin>>input; //Promt user to swap or Not
switch(input)
{
case 'y':
//calling swap function
swap(&number1,&number2);
break;
case 'n':
//User cancelled swapping
cout<<"Dont Swap"<< endl;
break;
default:
//User enterd wrong keyword
cout<<"Wrong keyword try Again"<< endl;
}

system("pause");
}
void swap(short *a, short *b)
{
short temp;
//stroring number1 in temperory variable
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
cout<<"Numbers swapped";
cout<< endl <<"After Swapping to given numbers Result is A= "<<*a<<" and" << endl;
cout<<"B= "<<*b<< endl;
}

Comments (0)

Post a Comment