Swapping Two Numbers In C Programing

Swap Definition

In computer programming, the act of swapping two variables refers to mutually exchanging the values of the variables. Usually, this is done with the data in memory

Using a temporary variable

The simplest and probably most widely used method to swap two variables is to use a third temporary variable:

  temp := x
  x := y
  y := temp

Swapping Two Numbers Example Program

/*##Swapping Two Numbers*/
/*##Calculation Programs, Datatype Programs, Basic Programs*/
/*##Example*/

#include <stdio.h>

int main()
{
    int num1, num2, temp;

    printf("Enter the 2 numbers to be swapped : \n");
    scanf("%d%d", &num1, &num2);

    printf("Before Swapping, the values are : \nnum1 = %d\nnum2 = %d\n",num1,num2);

    temp = num1;
    num1 = num2;
    num2 = temp;

    printf("After Swapping, the values are : \nnum1 = %d\nnum2 = %d\n",num1,num2);

    return 0;
}

Sample Output:

Enter the 2 numbers to be swapped :
100
99
Before Swapping, the values are :
num1 = 100
num2 = 99
After Swapping, the values are :
num1 = 99
num2 = 100

 

Top Pages