Adding Numbers using pointers
Written by
Adding numbers using pointers:
We can add two numbers by dereferencing the pointers that point to the variables storing those numbers.
The code for adding two numbers using pointers is:
#include <stdio.h>int main()
{
int num1;
int num2;
int * ptrNum1;
int * ptrNum2;
int sum;
printf("Enter first ineteger: ");
scanf("%d", & amp; num1);
printf("Enter second ineteger: ");
scanf("%d", & amp; num2);
ptrNum1 = & amp; num1; //making ptrNum1 point to num1
ptrNum2 = & amp; num2; //making ptrNum2 point to num2
sum = * ptrNum1 + * ptrNum2; //dereferencing the pointers
printf("Sum is: %d\n", sum);
return 0;
}
The input and output for the above code is:
Enter first ineteger: 5Enter second ineteger: 3
Sum is: 8
- We have created two integer variables num1and num2 and two pointers ptr1 and ptr2.
- The sum variable stores the sum of the two integers.
- ptr1and ptr2 point to num1 and num2
- By dereferencing ptr1and ptr2 we stores the addition of the values stored in num1 and num2.