Write a method called dangerousDescent that determines whether there is a downhill section in the hiking trail with a gradient of more than -5%. The gradient is calculated by the rise in elevation over the run in distance. For example, the last kilometer section has a gradient of -1% because the rise in elevation is 40 - 50 = -10 meters. The distance covered in 1000 meters. -10 / 1000 = -1%.


Your method should return true if there exists a dangerous descent in the given array, false otherwise.

Answer :

Answer: the explanation gives you the code used

Explanation:

There are several ways to go about this, here is just one way to carry out this computation.

#include <iostream>

using namespace std;

bool dangerousDescent(int* elevationArray , int sizeOfElevationArray)

{

  //we calculate gradient throughout elevationArray and if any one of them is more than -5%

  //then return true else return false

  //gradientOfSectionX = rise in elevation/Distance covered in merters

  //where rise in elevation is (elevationOfX - elevationOfX_previous)

  bool isDangerousDecent = false;

  float gradient = 0;

  int threshold = -5;

  float riseInElevation = 0;

  for (int i = 0; i < sizeOfElevationArray && isDangerousDecent == false; i++)

  {

      if (i > 0)

      {

          //check to avoid array out of bound error

          riseInElevation = (elevationArray[i] - elevationArray[i - 1]);

          gradient = riseInElevation / 1000; //1000 meters = 1km because every marker is at 1 kilometer distance

          gradient = gradient * 100; //percentage

          if (gradient > threshold)

          {

              isDangerousDecent = true;

              cout << "There is a gradient of " << gradient << "% on section " << elevationArray[i] << " of hiking trail " << endl;

          }

      }

      //first section not included because that was starting point with 0% elevatoin

     

  }

  return isDangerousDecent;

}

int main()

{

  int elevationArray[] = { 100,50,20,30,50,40 };

  int size = sizeof elevationArray / sizeof elevationArray[0];

  if (dangerousDescent(elevationArray, size) == true)

  {

      cout << "There is a dangerous decent of gradient more than -5% in hiking trail " << endl;

  }

  else

  {

      cout << "There is no dangerous decent of gradient more than -5% in hiking trail " << endl;

  }

  system("pause");

}

Other Questions