How to swap the values of variables a and b in C language?

One way to swap the values of a and b is by using a temporary variable. The specific code is as follows:

#include <stdio.h>

int main() {
    int a = 10;
    int b = 20;
    int temp;

    printf("Before swapping: a = %d, b = %d\n", a, b);

    temp = a; // 将a的值保存到temp变量中
    a = b;    // 将b的值赋给a
    b = temp; // 将temp的值赋给b

    printf("After swapping: a = %d, b = %d\n", a, b);

    return 0;

The program begins by defining two integer variables, a and b, and initializing them to 10 and 20. Then it uses a temporary variable, temp, to save the value of a. Next, it assigns the value of b to a, and finally assigns the value of temp to b. Finally, it prints out the values of a and b after the swap.

The output result is:

Before swapping: a = 10, b = 20
After swapping: a = 20, b = 10
Leave a Reply 0

Your email address will not be published. Required fields are marked *