Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to calculate sum of two number using Pointer

C++ Code Example — Function Programs

ADVERTISEMENT

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

  1. Declare two integers a and b, and two integer pointers *p and *q.
  2. Assign the memory addresses of the variables to the pointers: p = &a and q = &b.
  3. 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)
ADVERTISEMENT