In this example of swapping two numbers, the user will be requested to enter two numbers. These numbers will be then swapped by using a temporary variable “temp“.
#include <stdio.h> #include <math.h> int main() { int x, y, temp; printf("Please enter the first number: "); scanf("%d", &x); printf("Please enter the second number: "); scanf("%d", &y); printf("\nBefore swap:\n"); // Values before swapping printf("x: %d\n", x); printf("y: %d\n", y); temp = x; // Assigning the values of x to "temp" x = y; // Assigning the value of y to x y = temp; // Assigning the value of the temp variable to y printf("\n"); printf("After swap:\n"); // Values after swapping printf("x: %d\n", x); printf("y: %d\n", y); return 0; }
First, three variables namely x , y and temp will be declared. Next, the user will be asked to enter two numbers which will be stored in x and y respectively. The values of x and y will be displayed on the screen as they are before swapping.
printf("\nBefore swap:\n"); // Values before swapping printf("x: %d\n", x); printf("y: %d\n", y); temp = x; // Assigning the values of x to "temp" x = y; // Assigning the value of y to x y = temp; // Assigning the value of the temp variable to y
The swapping algorithm works in the following manner. First, the value of x will be assigned to the temp variable which currently was empty. Then the value of y will be assigned to x because we already have stored the value of x in temp. Finally, the value stored in temp will be assigned to y and this is how easily we can swap the values of two numbers stored in two different variables. Next, the values of both x and y will be displayed on the screen after swapping.
Output
Before swap: x: 7 y: 3 After swap: x: 3 y: 7