Program to swap two numbers without using third variable in C

Source Code

// 8.ii. Program to swap two numbers without using third variable
// Arpan Das - CST 2nd Year (VOCLET)

#include <stdio.h>
//#include <conio.h>
//#include <stdlib.h>

void main () {
	int a, b;
	//clrscr();
	//system("cls");
	
	printf("\t\t..:: swap two numbers without using third variable ::..\n\n");
	printf("Please enter values for a and b respectively: ");
	scanf("%d%d", &a, &b);
	printf("\nNow a = %d and b = %d\nPress any key to swap...", a, b);
	//getch();
	
	/*a = a+b;
	b = a-b;
	a = a-b;*/
	
	a = (a+b) - (b=a);
	
	printf("\n\nSwapped...\n\nNow a = %d and b = %d", a, b);
	
	//getch();
}

Output

		..:: swap two numbers without using third variable ::..

Please enter values for a and b respectively: 5 6

Now a = 5 and b = 6
Press any key to swap...

Swapped...

Now a = 6 and b = 5

Leave a Reply

Note: Your email address will not be published. Required fields are marked *