Topics:
Top-Down Design
Step-wise refinement
Algorithm Design
Repitition using For loops
Problem:
Write a program that will compute all Pythagorean triples, such as (3,4,5), (5,12,13), etc. A high-level description might be as follow:
0. Input an integer bound b
1. Generate all possible ints A < b, and for each such A
2. Generate all possible ints B < b, and for each such B
3. Generate all possible ints C < b, and for each such C
4. Test whether A^2 + B^2 = C^2, if so print the triple
Now it makes sense to keep only those solutions in sorted order, since otherwise we would have redundency.
A more refined pseudocode would be:
1. Prompt and input b
2. for each A from 1 to b do
3. for each B from A to b do
4. for each C from B to b do
Here is the final source code solution:
// Example from Class 121 January 25, 2001 // A program to generate all Pythagorean triples. #includeusing std::cout; using std::cin; using std::endl; int main() { cout << " This program generates all Pythogrean triples up to some bound\n"; cout << " Enter a bound: "; int b; cin >> b for (int A=1; A <= b; A++) for (int B=A; B <= b; B++) for (int C=B+1; C <= b; C++) if ((A*A + B*B) == C*C) cout << A << "\t" << B << "\t" << C << " is a Pythagorean triple\n"; cout << "\nHit key to finish\n"; char c; cin >> c; return 0; }