Program to Swap Two Numbers without Using a Temporary Variable

Description:
This program swaps two numbers without using a temporary variable. It uses basic arithmetic operations to swap values, showcasing how arithmetic manipulation can be used to exchange values without needing extra memory.

Usage:
The user inputs two numbers, and the program swaps their values and displays the result.

Code:

C
#include <stdio.h>

int main() {
    int a, b;

    // Asking user to input two integers
    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);

    // Swapping the numbers
    a = a + b;
    b = a - b;
    a = a - b;

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

    return 0;
}

Explanation:

  • Instead of using a temporary variable, the two numbers are swapped using arithmetic operations.

Test here:

Leave a Reply

Your email address will not be published. Required fields are marked *