# Program to Add two numbers using pointers in C++

Written by

Juhi Kamdar

Here, we’ll write a program to print the sum of two numbers using a pointer in C++. A pointer in programming holds the address of a variable.

Logic:

We will first initialize two numbers and two pointers. Then reference the pointers to the numbers. Then, using the ‘*’ operator, we will dereference them and store the sum in a variable.

Algorithm:

1. Declare two integer pointers, `ptr1` and `ptr2`, and initialize them to `NULL`.
2. Assign the address of `x` and `y` to `ptr1` and `ptr2`, respectively, using the `&` operator.
3. To access the values stored at the addresses pointed by `ptr1` and `ptr2`, use the `*` operator.
4. Calculate the sum of the values pointed by `ptr1` and `ptr2`, and store the result in a new variable, `sum`.
5. Print the value of `sum` .

Code:

``````#include <iostream>
using namespace std;
int main()
{
int num1, num2;
int *ptr1, *ptr2;
int sum;
cout << "\n Enter first number: ";
cin >> num1;
cout << "\n Enter second number: ";
cin >> num2;
ptr1 = &num1; //assigning an address to pointer
ptr2 = &num2;
sum = *ptr1 + *ptr2; //values at address stored by pointer
cout << "\n Sum is: " << sum;
return 0;
}
``````

Output:

``````Enter first number: 3
Enter second number: 4
Sum is: 7
``````