Introduction
In this blog, we will learn about one of the most basic Programming problems in which we will learn to swap two variables. We will first start with the problem statement then learn about the various methods we can use to solve this problem. We will begin with the first method, in which we will be using a temporary variable, and then the. Let'smethod, in which we use mathematical operators to achieve the task. So, let's discuss both approaches one by one in detail.
Also see: C Static Function, Short int in C Programming and Tribonacci Series
Using temporary variable
The first approach to this problem uses another variable to swap the two numbers. This third variable is known as the temporary variable. The basic idea behind this approach is to preserve one of the variables using the temporary variable while its value is updated with the second variable. Then we use this temp variable to update the value of the first variable into the second variable.
The above approach can be broken down into three steps-
- Storing the first variable's value into a temporary variable.
- Copy the value of the second variable into the first variable.
- Update the value of the second variable from the temporary variable.
Since you have developed an understanding of the approach, let's look at implementing the above approach.
Implementation
#include <stdio.h>
int main()
{
int X, Y;
printf("Enter X- ");
scanf("%d", &X);
printf("\nEnter Y- ");
scanf("%d", &Y);
int temp=X;
X = Y;
Y = temp;
printf("\nAfter swapping both the numbers: X = %d, Y = %d", X,Y);
return 0;
}
Output
Enter X- 8 Enter Y- 9 After swapping both the numbers: X = 9, Y = 8, |
You can also read about dynamic array in c and, Unary operator overloading in c++.