C program to swap two numbers

The below program is to swap two numbers with and without using third variable. The C printf statement is used to output the result on the screen. Swapping two numbers simply means interchanging the values of two numeric variables.

Before Swapping, A = n1 B = n2

After Swapping, A = n2 B = n1

C program to swap two numbers

#include <stdio.h>
 
void main()
{
 
int a=1, b=2;
int temp;
 
printf ("Before Swapping:");  
printf ("\n");
printf ("a = %d",a);
printf ("\n");
printf ("b = %d",b);  
printf ("\n");
 
temp = a;  
a = b;  
b = temp;  
 
printf ("After Swapping:");
printf ("\n");
printf ("a = %d",a);
printf ("\n");
printf ("b = %d",b);  
}

Output

Before Swapping:
a = 1
b = 2
After Swapping:
a = 2
b = 1
Please follow and like us:
Content Protection by DMCA.com