There are two ways to swap numbers using C language, one is with the help of temporary third variable and other is without the third variable. In this article, we will be looking at both of those approaches.
Program to swap two number in C using Third/Temporary variable:
#include<stdio.h> void main(){ int a,b,temp; printf("Enter Two integers: "); scanf("%d%d",&a,&b); temp=a; a=b; b=temp; printf("Swapped: a=%d , b=%d \n",a,b); }
OUTPUT:
Program to Swap two numbers without the help of temporary variable:
#include void main(){ int a,b,temp; printf("\n\n***************Program to Swap Without third variable********************\n\n\n"); printf("Enter Two integers: "); scanf("%d%d",&a,&b); a=a+b; b=a-b; a=a-b; printf("Swapped: %d , %d \n",a,b); }
OUTPUT: