Calculate the sum of two numbers using pointers in the C programming language.

In C language, we can use pointers to find the sum of two numbers. Below is an example program:

#include <stdio.h>

void add(int *a, int *b, int *result){
    *result = *a + *b;
}

int main(){
    int num1, num2, sum;
    
    printf("请输入第一个数:");
    scanf("%d", &num1);
    
    printf("请输入第二个数:");
    scanf("%d", &num2);
    
    add(&num1, &num2, &sum);
    
    printf("两个数的和为:%d\n", sum);
    
    return 0;
}

In this example, the add function takes two integer pointers a and b, adds them together, and stores the result in the variable pointed to by the pointer result. In the main function, we declare three integer variables num1, num2, and sum, then use the scanf function to get the values of two numbers from user input. Afterwards, we call the add function and pass the addresses of num1, num2, and sum to the function. Finally, we print the sum of the two numbers using the printf function.

After running the program, the user will be prompted to input two numbers, and then the program will print out the sum of these two numbers.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds