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 ..:
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" ..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; }
Now Let's See How We Can Do It Using Pointers:
the First Part of the Program Would be:
Than After This, We Declare the Variables we Need During the Calculation ..Code:#include <iostream> using namespace std; int main() {
As We See .. I've Declared Two Pointers (a,b) .. In Which the Address of "x" and "y" Will Be Saved..Code:#include <iostream> using namespace std; int main() { int x,y,z,*a,*b;
Than ..
Now Using " cin >> x and cin >> y " .. I've Asked From the User to Give Values for "x" and "y" ..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;
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:
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:#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; }
..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:
..Here's a Screenshot:Code:cout << "\nz=" << z;
Thanks,
Egz0N ..!!
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks