Cover Image for Add two numbers using Pointer in C

Add two numbers using Pointer in C

To add two numbers using pointers in C, you can create two integer variables, obtain their addresses, and then perform the addition through pointer arithmetic. Here’s a simple example:

#include <stdio.h>

int main() {
    int num1, num2, sum;
    int *ptr1, *ptr2;

    // Input two numbers
    printf("Enter the first number: ");
    scanf("%d", &num1);

    printf("Enter the second number: ");
    scanf("%d", &num2);

    // Obtain addresses of the numbers
    ptr1 = &num1;
    ptr2 = &num2;

    // Add the numbers using pointers
    sum = *ptr1 + *ptr2;

    // Display the result
    printf("Sum of %d and %d is %d\n", *ptr1, *ptr2, sum);

    return 0;

In this program:

  1. We declare two integer variables, num1 and num2, to store the two numbers.
  2. We declare two integer pointers, ptr1 and ptr2, which will hold the addresses of num1 and num2, respectively.
  3. We use scanf to input the two numbers.
  4. We obtain the addresses of the numbers using the address-of operator (&) and assign them to the pointers ptr1 and ptr2.
  5. We add the numbers using pointer dereferencing (*ptr1 and *ptr2) and store the result in the sum variable.
  6. Finally, we display the sum of the two numbers.

This program demonstrates the use of pointers to perform addition. The values of num1 and num2 are accessed through the pointers ptr1 and ptr2, and their sum is calculated and displayed.


The Tech Thunder

The Tech Thunder

The Tech Thunder