Next: Summary Up: The for statement Previous: Example Program: Student Mark

Example Program: Generation of Pythagorean Triples

In exercise 7 at the end of Lesson 7 Pythagorean triples were introduced. A Pythagorean triple is a set of three integers $a$, $b$ and $c$ such that $a^2+b^2=c^2$. Such a triple can be produced from two integers $m$ and $n$, $m > n$ as follows:

\begin{eqnarray*}
a & = & m^2-n^2 \\
b & = & 2mn \\
c & = & m^2+n^2
\end{eqnarray*}



To generate a list of Pythagorean triples m could be allowed to take values from its minimum possible value (2) up to some maximum value entered by the user. For each value of n from 1 up to m-1 the corresponding triple could then be evaluated and output. An algorithmic description for this is:

enter and validate a maximum value for m.
for each value of m from 2 to maximum do
   {
    for each value of n from 1 to m-1 do
       {
        evaluate and print a triple.
       }
   }

This description uses a for loop, a looping construct that repeats the loop statement as some control variable takes a sequence of values. Also note that one for loop is nested inside another, this is very common. From this description the following C++ program is easily produced:

void main()
{
  int max,        // maximum value of m to be used
      m, n,       // control variables for loops
      t1, t2, t3; // pythagorean triple
    // enter and validate max
  do {
      cout << "Enter a maximum value for m ( >1 ): ";
      cin >> max;
     }
  while (max < 2);
    // loop on m from 2 to max
  for (m=2; m <= max; m++)
    {
        // now loop on n from 1 to m-1
      for (n=1; n < m; n++)
        {
            // evaluate and print triple
          t1 = m*m-n*n;
          t2 = 2*m*n;
          t3 = m*m+n*n;
          cout << t1
               << " "  << t2
               << " "  << t3
               << endl;
        }
     }
}
Download program.



Next: Summary Up: The for statement Previous: Example Program: Student Mark