// Program: Diagonal of a rectangle
// Programmer: Bob Comer
//
// This program finds the distance across the diagonal of a
// rectangle.
//
// Algorithm:
//   main
//     Get the rectangle length and width
//     Calculate the diagonal (uses sqrt)
//     Print the rectangle diagonal
//
//   sqrt
//     Guess that the square root is the number itself
//     Calculate the quotient of number and the guess
//     Repeat while quess and quotient are too far apart
//        New guess is average of previous guess and quotient
//        Recalculate the quotient
//     Result is the average of guess and quotient
//
//************************************************************

#include <iostream.h>
#include <math.h>
#include <conio.h>

float sqrt( float num );

int main()
{
   float length,     // length of the rectangle
	 width,           // width of the rectangle
	 diagonal;        // diagonal of the rectangle

// Get rectangle length and width
   cout << "Enter length and width of the rectangle: ";
   cin >> length >> width;

// Calculate and print the diagonal
   diagonal = sqrt(length*length + width * width);
   cout << "The diagonal is " << diagonal;

// Signal normal completion
   return 0;
}

//************************************************************
// Function: sqrt
//
// This function calculates the square root of a floating
// point number.
//************************************************************

float sqrt(float num)
{
   float guessSqrt,    // guess for square root of the number
         quotient;     // the quotient of number and quess

// Initially guess square root is the number and
// calculate quotient of the number and the guess
   guessSqrt = num;
   quotient =1;

// Repeat while quess and quotient are too far apart
   while (fabs(guessSqrt - quotient) > .001)
   {
   // Make new guess and recalculate quotient
      guessSqrt = (guessSqrt + quotient) / 2.0;
      quotient = num / guessSqrt;
   }

// Result is average of most recent guess and quotient
   return (guessSqrt + quotient) / 2.0;
}

