View All C Programs

 Previews Example  View All C Programs Next Example 

Program to swap without using third in C

C program to swap two numbers using third variable. Without using third variable swapping needs some tricks.

Here are the set of expressions to make swap variables , let us have a variable 'a' and 'b', then execute the code in sequence as:
a=a+b;
b=a-b;
a=a-b
#include <stdio.h>
#include <conio.h>
 main()
{
    int a,b,temp; 
    printf("Enter two values\n");
    scanf("%d",&a);
    scanf("%d",&b);
    printf("\na = ");
    printf("\nb = ");
    a=a+b; // swapping without using third variable
    b=a-b;
    a=a-b;
    printf("\na = %d \n b = %d ", a, b);
    getch();
}   
Result
Enter two values
10
20
a = 10
b = 20

a = 20
b = 10