Add two numbers using pointer

We will see some C programs to add two numbers using pointers. Pointers are variable which can store the address of any other variables. We have discussed about pointer in our pointer chapter of C tutorial.

We will take two integer as input and then assign their address in other two pointer variable. Then add these numbers using the pointer variables. Let’s go the the code now.

C program to add two numbers by pointer

// c program to add two number using pointers

#include <stdio.h>

int main(){
   int fNum, sNum, *ptr1, *ptr2, sum;

   printf("Enter first integer here : ");
   scanf("%d", &fNum);
   printf("Enter second integer here : ");
   scanf("%d", &sNum);

   ptr1 = &fNum;
   ptr2 = &sNum;
   sum = *ptr1 + *ptr2;   // addition using pointers

   printf("\nSum is = %d\n", sum);

   return 0;
}

Output of adding program :

add-two-number-using-pointers-program-c-program-to-add-numbers-using-pointers

Add numbers by pointers using function

In this add numbers program we will call function by reference to add the given numbers.

// c program to add two number using function

#include <stdio.h>

long add_function(long *p, long *q){   // function for adding
  long result;

  result = *p + *q;

  return result;
}

int main(){
  long fNum, sNum, *fPtr, *sPtr, sum;

  printf("Enter the first integer : ");
  scanf("%ld", &fNum);
  printf("Enter the second integer : ");
  scanf("%ld", &sNum);

  sum = add_function(&fNum, &sNum);

  printf("\nSum is = %ld\n", sum);

  return 0;
}

Output of add numbers program

Enter the first integer : 200
Enter the second integer : 400

Sum is = 600

Previous pageOctal to binary

Next pageBubble sort