Program to Add two numbers using pointers in C++
Written by
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:
- Declare two integer pointers,
ptr1
andptr2
, and initialize them toNULL
. - Assign the address of
x
andy
toptr1
andptr2
, respectively, using the&
operator. - To access the values stored at the addresses pointed by
ptr1
andptr2
, use the*
operator. - Calculate the sum of the values pointed by
ptr1
andptr2
, and store the result in a new variable,sum
. - 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