C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

C Program: Swap Two Numbers (Without Third Variable)

Swapping two numbers means exchanging their values. Normally, this is done using a third (temporary) variable.
However, C allows us to swap values without using an extra variable by applying arithmetic operations (addition & subtraction or multiplication & division) or the bitwise XOR operator.

In this program, we demonstrate swapping without a third variable using arithmetic operations (+ and -). This method saves memory because no extra variable is needed.

 

C Program: Swap Two Numbers (Without Third Variable)

C

#include <stdio.h>   // Standard I/O header

 

int main() {

    int a, b;

 

    // Input from user

    printf("Enter first number (a): ");

    scanf("%d", &a);

 

    printf("Enter second number (b): ");

    scanf("%d", &b);

 

    // Display before swapping

    printf("\nBefore Swapping:\n");

    printf("a = %d, b = %d\n", a, b);

 

    // Swapping without third variable (using arithmetic operations)

    a = a + b;   // Step 1: Add both numbers and store in a

    b = a - b;   // Step 2: Subtract new b from sum → gives original a

    a = a - b;   // Step 3: Subtract new b from sum → gives original b

 

    // Display after swapping

    printf("\nAfter Swapping:\n");

    printf("a = %d, b = %d\n", a, b);

 

    return 0; // Successful termination

}

Output

 
OUTPUT :
Enter first number (a): 5
Enter second number (b): 10

Before Swapping:
a = 5, b = 10

After Swapping:
a = 10, b = 5

Explanation :

  1. Input: The program takes two integers a and b as input.
  2. Before Swapping: Prints original values of a and b.
  3. Swapping Logic:
    • a = a + b; → now a holds the sum of both numbers.
    • b = a - b; → subtracting b from sum gives the original a.
    • a = a - b; → subtracting new b (old a) from sum gives the original b.
  4. After Swapping: Prints the swapped values of a and b.