Hi There, CC Members ..

Today I am Going to Show you How to Use Pointers for Calculations in C++ ..

Ok..
This Calculation Without Using Pointers ..:

Code:
#include <iostream>
using namespace std;
int main()
{
        int x,y,z;

        cout << "\nx: ";
        cin >> x;
        cout << "\ny: ";
        cin >> y;
            
        if (x>y)
       {
           z=x+y;
           
          cout << "\nz="
                 << z;
       }
       else
       {
           z=x-y;
     
           cout << "\nz="
                  << z;
        }
           cout << "\n\n";

           return 0;
}
If We Execute This Part of Code ..It'll Ask Us to Give a Value for "x and y" ..Than It'll Compare the Given Values if "x>y" .. If That Is True, "z" Will be Calculated as "x+y" else "z" Will be Calculated as "x-y" .. Than Finally It Will Display the Value of "z" ..

Now Let's See How We Can Do It Using Pointers:

the First Part of the Program Would be:

Code:
#include <iostream>
using namespace std;
int main()
{
Than After This, We Declare the Variables we Need During the Calculation ..

Code:
#include <iostream>
using namespace std;
int main()
{
       int x,y,z,*a,*b;
As We See .. I've Declared Two Pointers (a,b) .. In Which the Address of "x" and "y" Will Be Saved..

Than ..

Code:
#include <iostream>
using namespace std;
int main()
{
       int x,y,z,*a,*b;
       
       cout << "\nx: ";
       cin >> x;

         a=&x;

         cout << "\ny: ";
       cin >> y;

         b=&y;
Now Using " cin >> x and cin >> y " .. I've Asked From the User to Give Values for "x" and "y" ..

And Then the Address of the Given Values Will be Saved to the Pointers (a,b) Using " a=&x and b=&y " ..

Now the Calculation Part:

Code:
#include <iostream>
using namespace std;
int main()
{
       int x,y,z,*a,*b;
       
       cout << "\nx: ";
       cin >> x;

       a=&x;

       cout << "\ny: ";
       cin >> y;

       b=&y;

       if (x>y)
       {
             z=*a+*b;
          
             cout << "\nz="
                    << z;
        }
       else
       {
             z=*a-*b;

               cout << "\nz="
                    << z;
        }

             cout << "\n\n";

             return 0;
}
Using "x>y" the Computer Will Compare the Two Variables and Will Look If the Value of "x" is Bigger than the Value of "y" .. and If It's True..

Code:
z=*a+*b;
..
*a = the Value Saved in Pointer "a" and
*b = the Value Saved in Pointer "b" ..

else

Code:
z=*a-*b;
..

Finally, the Value of "z" will be Shown .. using:

Code:
 cout << "\nz="
    << z;
..Here's a Screenshot:

Calculations Using Pointers-.jpg


Thanks,

Egz0N ..!!