Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

C program addition of numbers using pointer

#include <stdio.h>

int main() {
   int num1, num2, sum;
   int *ptr1, *ptr2;
   
   printf("Enter two numbers: ");
   scanf("%d %d", &num1, &num2);

   ptr1 = &num1;
   ptr2 = &num2;

   sum = *ptr1 + *ptr2;

   printf("Sum of %d and %d is %d", *ptr1, *ptr2, sum);
   
   return 0;
}

Explanation:

In this program, we declare two integer variables num1 and num2 to store the numbers entered by the user, and a variable sum to store their sum. We also declare two integer pointers ptr1 and ptr2, which will be used to point to the memory locations of num1 and num2.

After prompting the user to enter two numbers, we use the scanf() function to read in the values of num1 and num2. We then assign the memory addresses of num1 and num2 to ptr1 and ptr2, respectively, using the address-of operator &.

Next, we use the dereference operator * to access the values stored at the memory locations pointed to by ptr1 and ptr2, and add them together to calculate the sum. Finally, we use printf() to display the sum of the two numbers.