Exchanging the Values of Two Variables

Swapping the values of two variables is a basic operation that is frequently used in various algorithms, such as sorting algorithms. This operation involves exchanging the values stored in two different variables.

Algorithm Explanation

To swap the values of two variables, you generally need a temporary variable to hold the value of one of the variables during the exchange process. The steps are as follows:

  1. Store the value of the first variable in a temporary variable.
  2. Assign the value of the second variable to the first variable.
  3. Assign the value stored in the temporary variable to the second variable.

This can be illustrated with the following pseudo-code:

temp = a
a = b
b = temp

C Implementation

Below is a C program that demonstrates how to swap the values of two variables using a function and pointers.

#include <stdio.h>

// Function to swap the values of two variables
void swap(int *a, int *b) {
    int temp = *a;  // Step 1: Store the value of 'a' in 'temp'
    *a = *b;        // Step 2: Assign the value of 'b' to 'a'
    *b = temp;      // Step 3: Assign the value of 'temp' to 'b'
}

int main() {
    int x = 5;   // First variable
    int y = 10;  // Second variable

    // Print initial values
    printf("Before swap: x = %d, y = %d\n", x, y);

    // Call the swap function
    swap(&x, &y);

    // Print values after swapping
    printf("After swap: x = %d, y = %d\n", x, y);

    return 0;
}

Explanation of the C Program

  1. Function Definition:
    • void swap(int *a, int *b):
      • This function takes two pointers to integers as arguments. The use of pointers allows the function to modify the actual values of the variables passed to it.
    • Inside the function:
      • int temp = *a;: The value pointed to by a is stored in the temporary variable temp.
      • *a = *b;: The value pointed to by b is assigned to the location pointed to by a.
      • *b = temp;: The value stored in temp is assigned to the location pointed to by b.
  2. Main Function:
    • Variables x and y are initialized with the values 5 and 10, respectively.
    • The initial values of x and y are printed.
    • The swap function is called with the addresses of x and y (&x and &y).
    • After the swap, the new values of x and y are printed.

Output :

Before swap: x = 5, y = 10
After swap: x = 10, y = 5

Explanation of the output:

  • Before the swap function is called, the initial values of x and y are 5 and 10, respectively.
  • After calling the swap function, the values of x and y are exchanged, resulting in x becoming 10 and y becoming 5.
  • The program then prints these updated values after the swap operation.