C and C++ Program for Swapping Two Numbers Without Third Variable

This post contains C and C ++ programs for swapping two given numbers without using any temporary variable. Only the two variables are required, not a third.

C Program
#include<stdio.h>
void main()
{

int a,b;
printf("Enter first number, a:");
scanf("%d",&a);
printf("Enter second number, b:");
scanf("%d",&b);
printf("values of a and b before swapping is a=%d,b=%d",a,b);
/*swapping*/
a=a+b;
b=a-b;
a=a-b;
printf("value of a and b after swapping is a=%d,b=%d"a,b);
}


C++ Program
#include<iostream.h>
void main()
{
int a,b;
cout<<"Enter first number, a:";
cin>>a;
cout<<"Enter second number, b:";
cin>>b;
cout<<"Values of a and b before swapping is a= "<<a<<" and b= "<<b;
/*swapping*/
a=a+b;
b=a-b;
a=a-b;
cout<<"value of a and b after swapping is a= "<<a<<" and b= "<<b;
}

No comments :

Post a Comment