Member-only story

In C++, create a method to find the hypotenuse using pointers

Marika Lam
1 min readMay 22, 2022

--

Question

Find the hypotenuse by using C++ pointers. The parameters will be both of the lengths of the triangle, leg1 and leg2, and a pointer.

Explanation

‘*’ in the parameter of hypotenuse means that it is the value which the pointer is pointing at. Therfore, within the hypotenuse function, we are setting the value to the element of where the pointer is currently pointing at. Once the value is set with the math function sqrt(), then the program goes back to the main method where *p is printed. Again, * is the value of where value of the pointer is pointing at.

Solution

#include <iostream>#include <cmath>using namespace std;void hypotenuse(double leg1, double leg2, double* resultPtr){*resultPtr = sqrt(leg1*leg1 + leg2*leg2);}int main(){double value;double* p = &value;hypotenuse(1.5, 2.0, p);cout << "The hypotenuse is " << *p << endl;}

--

--

No responses yet