|
Imagine that we are given the problem of computing 2 to the power of 10. Our first attempt might be something like - #include <iostream>
- int main()
{ std::cout << "2 raised to the power of 10: "; std::cout << 2*2*2*2*2*2*2*2*2*2; std::cout << std::endl; return 0; }
This program solves the problem, although we might double- or triple-check to make sure that exactly 10 literal instances of 2 are being multiplied. Otherwise, we’re satisfied. Our program correctly generates the answer 1,024.
We’re next asked to compute 2 raised to the power of 17 and then to the power of 23. Changing our program each time is a nuisance. Worse, it proves to be remarkably error-prone. Too often, the modified program produces an answer with one too few or too many instances of 2.
An alternative to the explicit brute force power-of-2 computation is twofold:
1. Use named objects to perform and print each computation.
2. Use flow-of-control constructs to provide for the repeated execution of a sequence of program statements while a condition is true.
Here, then, is an alternative way to compute 2 raised to the power of 10: - #include <iostream>
- int main()
- {
-
- int value = 2;
- int pow = 10;
- int result = 1;
-
- for (int cnt = 0; cnt != pow; ++cnt)
- result *= value;
- std::cout << value
- << " raised to the power of "
- << pow << ": \t"
- << result << std::endl;
- return 0;
- }
value, pow, result, and cnt are variables that allow for the storage, modification, and retrieva l of values. The for loop allows for the repeated execution of our calculation until it’s been executed pow times.
|