Interchange value of variables with and without using third variable - C/C++

Interchanging value of two variables with or without using third variable is kind of popular programmer for beginners.
Sometimes even it may be asked to a fresher in job interview.
I have created a simple C/C++ program to interchange the value of variables in both ways.
The program is divided in two part.
One is interchange value of variables using third variable and
other is to interchange value of variables without using third variable.


Interchange value of variables with and without using third variable


#include<stdio.h>
#include<conio.h>
 
void main()
{
	int a, b, c;
	clrscr();
 
	printf("\n \t \t ==== Program to interchange values of variable ==== ");
	printf("\n \t \t =================================================== ");
	printf("\n \t \t Enter A. : ");
	scanf("%d", &a);
	printf("\n \t \t Enter B. : ");
	scanf("%d", &b);
	printf("\n \t \t ==== Using third variable ====");
	printf("\n \n \t \t Value of A : %d", a);
	printf("\n \t \t Value of B : %d", b);
 
	c = b;
	b = a;
	a = c;
 
	printf("\n \t \t New Value of A : %d", a);
	printf("\n \t \t New Value of B : %d", b);
	printf("\n \n \t \t ==== Without using third variable ====");
	printf("\n \n \t \t Value of A : %d", a);
	printf("\n \t \t Value of B : %d", b);
 
	a = a + b;
	b = a - b;
	a = a - b;
 
	printf("\n \t \t New Value of A : %d", a);
	printf("\n \t \t New Value of B : %d", b);
 
	getch();
}

Post a Comment