C Program to Swap Two Numbers

C Program to Swap Two Numbers

Write C code to swap two numbers using different methods

//Write a C program to swap 2 numbers

#include<stdio.h>

int main()
{
	int a = 45 , b = 54, temp;


	printf("Before swapping a = %d and b = %d", a, b);

	// METHOD - 1
	temp = a;
	a = b;
	b = temp;

	printf("\nAfter swapping a = %d and b = %d" , a, b);


	// METHOD - 2
	a = 44;
	b = 55;

     printf("\n\nBefore swapping a = %d and b = %d", a, b);
	a = a + b;
	b = a - b;
	a = a - b;

	printf("\nAfter swapping a = %d and b = %d" , a, b);

	return 0;
}

Output:

Before swapping a = 45 and b = 54
After swapping a = 54 and b = 45

Before swapping a = 44 and b = 55
After swapping a = 55 and b = 44