In this article, you will learn a C++ program to add two numbers using pointers. The pointers concept in C++ is very simple. They are the special type of variable in C++ that are used to store memory addresses of other variables.
We can get the memory address of any variable by simply placing the “&” operator at the beginning of the variable. It is called a reference operator. Check the example below.
ptr1 = &number1;
ptr2 = &number2;
Now initialize two pointer variables named “ptr1” and “ptr2” and store the above-extracted address. Declare a third variable named“sum” and store the sum=*ptr1+*ptr2 where the “*” operator is used to get the values of addresses. It is called dereference operator. Check the example below
Example: C++ program to add two numbers using pointers
//C++ program to add two numbers using pointer
#include<iostream>
using namespace std;
int main()
{
int number1, number2, *ptr1, *ptr2, sum=0;
cout<<"***addition of two numbers using pointer***"<<endl;
cout<<"Enter first number: ";
cin>>number1;
cout<<"Enter second number: ";
cin>>number2;
ptr1 = &number1;
ptr2 = &number2;
sum = *ptr1 + *ptr2;
cout<<"\n"<<"Sum of numbers will be: "<<sum;
return 0;
}