211: Programming For IS 1 --- Lecture Sept. 29

Topics:

A Simple C++ Program: Coding the Hypotenuse Program

In this lecture we continue with our discussion of writing a program to compute the hypotenuse of a right triangle. Last lecture we planned the solution using top-down design. Below is the conversion of the refined tasks to actually C++ code.

//*************************************************************************
//Programmer: Ken Berman 
//Last update: 09/30/98 
//Program purpose: This program inputs the two right-angled sides of a
//right triangle and computes the hypotenuse
//*************************************************************************


//PREPROCESSOR DIRECTIVES
#include
#include

int main()
{
//VARIABLE DECLARATIONS
   float A,       // ONE RIGHT-ANGLED SIDE OF A RIGHT TRIANGLE
   B,             // THE OTHER RIGHT-ANGLED SIDE OF THE RIGHT TRIANGLE
   HypotSquared,  // SQUARE OF HYPOTENUSE OF THE RIGHT TRIANGLE
   Hypotenuse;    // HYPOTENUSE OF THE RIGHT TRIANGLE

//DESCRIPTION OF PROGRAM
   cout << "This program computes the hypotenuse of a right traingle,";
   cout << "\ngiven the lengths of its two right-angled sides A and B.";
  
//INPUT TWO SIDES OF RIGHT TRIANGLE  
   cout << "\n\nEnter length of side A: ";
   cin >> A;
   cout << "\nEnter length of side B: ";
   cin >> B;

//CALCULATE HYPOTENUSE BASED ON THE PYTHAGOREAN THEOREM
   HypotSquared = A*A + B*B;
   Hypotenuse = sqrt(HypotSquared);

//OUTPUT RESULTS
   cout << "\nA triangle with right-angle sides " << SideA << " and " << SideB
        << " has hypotenuse " << Hypotenuse << "." << endl;

   return 0;
} //END main()
Note the extensive use of commenting in this program. The two forward slashes // indicates that the line is a comment line to be ignored by the C++ compiler. It is not executable.

It is very important that your programs are well-commented, so that they are easy to read.

Avoid over-commenting and redundant comments, since these could actually make your program less readable.