C Program to Add Two Numbers using Pointers

In this tutorial, we will write a program to find the sum of numbers using pointers in C program. Before that, you should have knowledge on the following topic in C:


C Program to Add Two Numbers using Pointers

The program takes the two numbers from the user and finds the sum of those numbers in C.

#include <stdio.h>

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

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

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

  ptr1 = &num1;
  ptr2 = &num2;

  sum = *ptr1 + *ptr2;

  printf("\nSum of two numbers: %d", sum);

  return 0;
}

Output:

Enter the first number: 10
Enter the Second number: 20

Sum of two numbers: 30


C program to add two numbers using call by reference

The program takes the two numbers from the user and passes the reference to the function where the sum is calculated. You may go through the topic below.

#include <stdio.h>

//user-defined function
float addFunc(float *a, float *b)
{
  float sum;

  sum = *a + *b;

  return sum;
}

int main()
{
  float num1, num2, result;

  printf("Enter the first number: ");
  scanf("%f", &num1);

  printf("Enter the Second number: ");
  scanf("%f", &num2);

  result = addFunc(&num1, &num2);

  printf("Sum of the result: %f", result);

  return 0;
}

Output:

Enter the first number: 15.5
Enter the Second number: 20.5
Sum of the result: 36.000000