C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

C Program: Swap Two Numbers (Using Third Variable)

Swapping two numbers is a fundamental programming concept in C. It means exchanging the values of two variables so that the first variable holds the value of the second, and the second variable holds the value of the first.

There are multiple ways to swap two numbers in C:

  1. Using a third (temporary) variable → the simplest and most common method.
  2. Without using a third variable → by applying arithmetic operations (+, -, *, /) or the bitwise XOR operator.

In this program, we demonstrate the first method: swapping using a temporary variable. This approach is simple and easy to understand, especially for beginners.

 

C Program: Swap Two Numbers (Using Third Variable)

C

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

 

int main() {

    int a, b, temp;   // variables for two numbers and a temporary variable

 

    // 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 using third variable

    temp = a;   // store value of a in temp

    a = b;      // copy value of b into a

    b = temp;   // copy value of temp (original a) into 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. #include <stdio.h>
    • Includes Standard I/O functions (printf, scanf).
  2. int a, b, temp;
    • Declares three integers:
      • a → first number
      • b → second number
      • temp → temporary variable used for swapping
  1. scanf("%d", &a); scanf("%d", &b);
    • Takes input for a and b from the user.
  2. Before Swapping Output
    • Displays original values of a and b.
  3. Swapping Process
    • temp = a; → temporarily stores a
    • a = b; → assigns value of b to a
    • b = temp; → assigns original value of a (stored in temp) to b
  4. After Swapping Output
    • Displays the new values of a and b.
  5. return 0;
    • Ends the program successfully.