swap using third variable
Swap using a third variable in C
To swap the values of two variables using a third variable in the C programming language, you can follow these steps:
Declare three variables of the same data type. Let's call them
a
,b
, andtemp
.a
andb
are the variables whose values you want to swap, andtemp
is the temporary variable used for swapping.Assign the values of
a
andb
totemp
anda
, respectively. This step ensures that the value ofa
is stored intemp
before it gets overwritten.Assign the value of
temp
tob
. This step assigns the original value ofa
(stored intemp
) tob
, effectively swapping the values ofa
andb
.
Here's an example code snippet that demonstrates the swap using a third variable:
#include <stdio.h>
int main() {
int a = 5;
int b = 10;
int temp;
printf("Before swapping: a = %d, b = %d\n", a, b);
temp = a;
a = b;
b = temp;
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}
Output:
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5
In the above code, the values of a
and b
are initially set to 5 and 10, respectively. After swapping, the value of a
becomes 10 and the value of b
becomes 5.
Please note that this method of swapping values using a third variable is a common approach in C programming.