# C program to find sum and difference using pointers in function

CServer Side ProgrammingProgramming

Suppose we have two numbers a and b. We shall have to define a function that can calculate (a + b) and (a - b) both. But using a function in C, we can return at most one value. To find more than one output, we can use output parameters into function arguments using pointers. Here in this problem we shall update a with a+b and b with a-b. When we call the function we shall have to pass the address of these two variables.

So, if the input is like a = 5, b = 8, then the output will be a + b = 13 and a - b = -3

To solve this, we will follow these steps −

• define a function solve(), this will take addresses of a and b

• temp := sum of the values of variable whose addresses are given

• b := difference of the values of variable whose addresses are given

• a = temp

## Example

Let us see the following implementation to get better understanding −

#include <stdio.h>
int solve(int *a, int *b){
int temp = *a + *b;
*b = *a - *b;
*a = temp;
}
int main(){
int a = 5, b = 8;
solve(&a, &b);
printf("a + b = %d and a - b = %d", a, b);
}


## Input

a = 5, b = 8

## Output

a + b = 13 and a - b = -3
Published on 08-Oct-2021 10:55:02