WAP to calculate sum of two number using Pointer
Objective
Write a C++ program to calculate the sum of two numbers using Pointers.
Algorithm / Approach
- Declare two integers
aandb, and two integer pointers*pand*q. - Assign the memory addresses of the variables to the pointers:
p = &aandq = &b. - Add the values stored at those memory addresses using the dereference operator:
sum = *p + *q.
main.cpp
#include<iostream>
using namespace std;
int main( ) {
int a, b, *p, *q, sum;
cout<<"Enter two number : ";
cin>>a>>b;
p = & a;
q = & b;
sum = *p + *q;
cout<<"SUM = "<< sum<< endl;
return 0;
}
Expected Output
Enter two number : 10 20 SUM = 30
Explanation of the Program
- Pointers are variables that store the literal RAM memory addresses of other variables.
- The Address-Of operator (
&) gets the memory address of a variable. The Dereference operator (*) goes to a memory address and interacts with the actual data stored there.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)