Swapping numbers

Swapping numbers means exchanging the values between two or more variables. In this program we are going to see how we can swap two user given number with the help of one temporary variable.

Logic

  1. Assign variable a’s value to variable temp, so now temp is holding a’s original value.
  2. Assign b’s value to a.
  3. Assign temp’s (holding a) value to b.

Program

#include <stdio.h>

int main() {

    int a, b, temp;

    printf("Enter number a : ");
    scanf("%d", &a);

    printf("Enter number b : ");
    scanf("%d", &b);

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

    //Swapping number
    temp = a;
    a = b;
    b = temp;

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

    return 0;
}

Output

Enter number a : 10
Enter number b : 200

Before swapping a = 10 b = 200
After swapping a = 200 b = 10