C++ Program to Add Two Numbers using Pointer

« Previous Program Next Program »

Add two Numbers using Pointer in C++

To add two numbers using pointer in C++ Programming, you have to ask from the user to enter the two numbers. Then make two pointer type variable of same type say *ptr1 and *ptr2 to initialize the address of both the variable (that holds numbers) and using another variable say sum, store the addition of the two number, i.e., sum = *ptr1 + *ptr2 and display the value of sum on the screen.

Here * is called as value at operator and & is called as address of operator.

Following C++ program asks from user to enter the two number to sum it up using pointer. And display the addition result on the screen:

// C++ Program to Add Two Numbers using Pointer

using namespace std;
int main()
    int num1, num2, *ptr1, *ptr2, sum=0;
    cout<<"Enter Two Numbers: ";
    ptr1 = &num1;
    ptr2 = &num2;
    sum = *ptr1 + *ptr2;
    cout<<"\nSum of Two Numbers = "<<sum;
    return 0;

This program was build and run under Code::Blocks IDE. Here is its sample run:

C++ program to add two numbers using pointer

Now supply any two numbers say 10 and 30 as input. Press ENTER key to see the addition of two given number using pointer as shown in the final snapshot of the sample run given below:

add two numbers using pointer c++

Here the address of first number (stored in num1) gets initialized to ptr1, whereas the address of second number gets initialized to ptr2 using & (address of) operator.

And using * (value at address) operator, we've added the two numbers and initialized it to sum. Finally just print the value of it as output.

To learn about pointer in detail, then you can follow the separate tutorial on it.

What if Number(s) contains Decimal ?

To handle with real number, just replace the data type from int to float. That is, the following statement:

int num1, num2, *ptr1, *ptr2, sum=0;

gets replaced with:

float num1, num2, *ptr1, *ptr2, sum=0;

Rest of the things will be same. And here is its sample run on real number input:

two number addition using pointer c++

Same Program in Other Languages

« Previous Program Next Program »