C program to find sum and difference using pointers in function

In C programming, functions can return only one value at a time. However, when we need to calculate multiple results like sum and difference of two numbers, we can use pointers as function parameters. This technique allows us to modify the original variables directly through their memory addresses.

Syntax

void functionName(int *ptr1, int *ptr2);
// Call the function
functionName(&variable1, &variable2);

Algorithm

To solve this problem, we will follow these steps −

  • Define a function that takes addresses of two variables as parameters
  • Store the sum in a temporary variable
  • Calculate the difference and store it in the second variable
  • Assign the sum to the first variable

Example

Let us see the implementation to calculate sum and difference using pointers −

#include <stdio.h>

void solve(int *a, int *b) {
    int temp = *a + *b;  /* Store sum in temporary variable */
    *b = *a - *b;        /* Calculate difference and store in b */
    *a = temp;           /* Assign sum to a */
}

int main() {
    int a = 5, b = 8;
    
    printf("Before function call: a = %d, b = %d<br>", a, b);
    
    solve(&a, &b);  /* Pass addresses of a and b */
    
    printf("After function call: a + b = %d and a - b = %d<br>", a, b);
    
    return 0;
}
Before function call: a = 5, b = 8
After function call: a + b = 13 and a - b = -3

How It Works

The function solve() receives pointers to variables a and b. Using the dereference operator *, we can access and modify the actual values stored at those memory locations. The original variables are updated directly, allowing us to return multiple results without using the return statement.

Conclusion

Using pointers as function parameters is an effective way to obtain multiple outputs from a single function call. This technique modifies the original variables directly through their memory addresses, eliminating the limitation of returning only one value.

Updated on: 2026-03-15T14:22:35+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements