Next: Example Program: Area and Up: The if-else Statement Previous: Example Program: Wages Calculation

Example Program: Pythagorean Triples

In exercise 7 of Lesson 7 it was required to write a program to input two integer values $m$ and $n$, where $m > n$ and to output the corresponding Pythagorean triple $m^2-n^2$, $2mn$ and $m^2+n^2$. This is now extended so that the values of $m$ and $n$ entered by the user are validated to ensure that $m$ is greater than $n$. A suitable algorithmic description is:

enter values for m and n.
if m is greater than m
   then
       {
        calculate the pythagorean numbers
                             from m and n.
        output the pythagorean numbers.
       }
   otherwise output a warning message.

This algorithmic description is now easily converted into the following C++ program:

// IEA 1996
// Program to produce pythagorean triples
// with input validation.

#include <iostream.h>

void main()
{
  int m, n;       // entered by user to generate triple
  int t1, t2, t3; // The values of the triple
     // input from user
  cout << "Input values for m and n, m > n : ";
  cin >> m >> n;
     // now validate m and n
  if (m > n)
    {
      t1 = m*m-n*n;
      t2 = 2*m*n;
      t3 = m*m+n*n;
      cout << "The triple corresponding to "
           << m << " and " << n << " is "
           << t1 << " " << t2 << " " << t3
           << endl;
    }
  else
    cout << "m must be greater than n!"
         << endl
         << "you entered m as " << m
         << " and n as " << n
         << endl;
}
Download program.

Note that the values of m and n entered by the user are printed as part of the output. This is good practice. Programs should not only display results but should give some indication of the data that produced the results. In this case the input data set was produced in full since it was small. In situations where the input data set was large it might not be realistic to reproduce it all but an indication such as

Results produced from Data Set No 23
might be output. This is vital if a listing of results is to mean anything at a future date.



Next: Example Program: Area and Up: The if-else Statement Previous: Example Program: Wages Calculation