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:

  1. Initialize two integer variables.
  2. Initialize two integer pointers.
  3. Reference the pointers to variables using ‘&’ operator.
  4. Now, using * operator, access the address pointed by pointers.
  5. Add the values, and store it.
  6. 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

Related Posts:

[yuzo_views]











CopyRight © 2019

CopyRight © 2019