C Language Swap Algorithm Using Temporary Variables

C Language Swap Algorithm Using Temporary VariablesC Language Swap AlgorithmThe swap algorithm is one of the basic algorithms in C language, aimed at exchanging the values between variables without losing existing data.Temporary Variable MethodIn C language, there are various methods to swap the values of two or more variables, among which the temporary variable method is one of the easier to understand methods.As the name suggests, this method uses a temporary variable to store the value of a variable, ensuring that the values between variables can be exchanged without data loss. For specifics, refer to the example code below.Example Code for Temporary Variable Swap Method

  • The example defines a function swapThreeNumber with parameters of type int pointer;
  • A value temp_x is defined to temporarily store the value stored at the memory address pointed to by pointer x, ensuring that the original data is not lost after reassigning *x.
#include <stdio.h>
void swapThreeNumber(int *x, int *y, int *z) {
    int temp_x = *x;
    *x = *y;
    *y = *z;
    *z = temp_x;
}
int main() {
    int x = 1;
    int y = 2;
    int z = 3;
    swapThreeNumber(&x, &y, &z);
    printf("After swapping: x = %d, y = %d, z = %d\n", x, y, z);
    return 0;
}

The code compiles and runs, producing the output:

After swapping: x = 2, y = 3, z = 1

Disclaimer: The content is for reference only, does not guarantee correctness, and should not be used as the basis for any decisions!

Leave a Comment