Program to swap two numbers. In C Language we can swap two numbers with and without third variable. first of all we learn how to swap two numbers without using third variable.

Swap two numbers without using third variable

In the following program we will swap two numbers without using third variable


//Swap two Numbers
#include<stdio.h>
void main()
{
    
    int x,y;
    printf("Enter Two Numbers \n");
    scanf("%d%d",&x,&y);

    printf("Before Swap\n");
    printf("The value of x %d",x);
    printf("\nThe value of y %d",y);

    x=x+y;
    y=x-y;
    x=x-y;

    printf("\nAfter Swap");
    printf("\nThe value of x %d",x);
    printf("\nThe value of y %d",y);

}
		


Swap two numbers using third variable

In the following program we will swap two numbers using third variable. We have declared third variable with the name of z. First of all z will hold the value of x and then we will swap the x and y.


//Swap two Numbers
#include<stdio.h>
void main()
{
   
    int x,y,z;
    printf("Enter Two Numbers \n");
    scanf("%d%d",&x,&y);

    printf("Before Swap\n");
    printf("The value of x %d",x);
    printf("\nThe value of y %d",y);

    z=x;
    x=y;
    y=z;
	
    printf("\nAfter Swap");
    printf("\nThe value of x %d",x);
    printf("\nThe value of y %d",y);

}
		


		
		swap using third variable
		Figure 1
		
		
		
		swap without using third variable
		Figure 2