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:

  1. Declare three variables of the same data type. Let's call them a, b, and temp. a and b are the variables whose values you want to swap, and temp is the temporary variable used for swapping.

  2. Assign the values of a and b to temp and a, respectively. This step ensures that the value of a is stored in temp before it gets overwritten.

  3. Assign the value of temp to b. This step assigns the original value of a (stored in temp) to b, effectively swapping the values of a and b.

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.