C Swap Function: Exchange Two Numbers

In C language, you can swap the values of two numbers by using the swap function. Here is an example code:

#include <stdio.h>

void swap(int *a, int *b){
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int num1 = 10;
    int num2 = 20;

    printf("交换前的值:num1 = %d,num2 = %d\n", num1, num2);

    swap(&num1, &num2);

    printf("交换后的值:num1 = %d,num2 = %d\n", num1, num2);

    return 0;
}

In the code above, we have defined a function called swap that takes two pointer parameters to exchange the values of two numbers. In the main function, we declare two variables num1 and num2, and initialize them to 10 and 20 respectively. Then, we call the swap function and pass the addresses of num1 and num2 as parameters to the function. In the swap function, we use a temporary variable temp to store the value of num1, then assign the value of num2 to num1, and finally assign the value of temp to num2, thereby achieving the exchange of values for the two numbers. Finally, we print out the values before and after the swap using the printf function. When running the program, the output will be as follows:

交换前的值:num1 = 10,num2 = 20
交换后的值:num1 = 20,num2 = 10

By using the swap function, we were able to successfully exchange the values of two numbers.

bannerAds