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:
- Initialize two integer variables.
- Initialize two integer pointers.
- Reference the pointers to variables using ‘&’ operator.
- Now, using * operator, access the address pointed by pointers.
- Add the values, and store it.
- Print the 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
Report Error/ Suggestion