Algorithm to add two numbers using pointer
- Firstly, Initialize two variables of integer type.
- Secondly, Initialize two pointers of integer type.
- Thirdly, Reference the pointers to variables with the help of ‘&’ operator.
- With the help of * operator, access the address pointed by pointers.
- Sum the values of variables, and store it on another variable.
- Display the sum after calculations.
C++ Program to add two numbers using pointers
Write a program in C++ to add two numbers using pointers.
#include <iostream>
using namespace std;
int main()
{
int FirstNumber, SecondNumber;
int *FirstPointer,* SecondPointer;
int sum;
cout<<"\n Enter the first number: ";
cin>>FirstNumber;
cout<<"\n Enter the second number: ";
cin>>SecondNumber;
FirstPointer = &FirstNumber; //assigning an address to pointer
SecondPointer = &SecondNumber;
sum = *FirstPointer + * SecondPointer; //values at address stored by pointer
cout<<"\n The Sum is: "<< sum;
return 0;
}
Output
Enter the first number:
4
Enter the second number:
5
The Sum is: 9