5.7. Encapsulation and generalization¶
Encapsulation usually means taking a piece of code and wrapping it up in
a function, allowing you to take advantage of all the things functions
are good for. We have seen two examples of encapsulation, when we wrote
print_parity in section Alternative Execution and
is_digit in section Bool Functions.
Generalization means taking something specific, like printing multiples of 2, and making it more general, like printing the multiples of any integer.
Here’s a function that encapsulates the loop from the previous section
and generalizes it to print multiples of n.
void print_multiples (int n) {
int i = 1;
while (i <= 6) {
cout << n*i << " ";
i = i + 1;
}
cout << '\n';
}
To encapsulate, all I had to do was add the first line, which declares
the name, parameter, and return type. To generalize, all I had to do was
replace the value 2 with the parameter n.
If we call this function with the argument 2, we get the same output as before. With argument 3, the output is:
3 6 9 12 15 18
and with argument 4, the output is
4 8 12 16 20 24
By now you can probably guess how we are going to print a multiplication
table: we’ll call print_multiples repeatedly with different
arguments. In fact, we are going to use another loop to iterate through
the rows.
int i = 1;
while (i <= 6) {
print_multiples (i);
i = i + 1;
}
First of all, notice how similar this loop is to the one inside
print_multiples. All I did was replace the print statement with a
function call.
Try running the active code below, which uses print_multiples.
1#include <iostream>
2
3void print_multiples (int n) {
4 int i = 1;
5 while (i <= 6) {
6 std::cout << n*i << " ";
7 i = i + 1;
8 }
9 std::cout << '\n';
10}
11
12int main() {
13 int i = 1;
14 while (i <= 6) {
15 print_multiples (i);
16 i = i + 1;
17 }
18}
Note the output is a (slightly sloppy) multiplication table. If the sloppiness bothers you, you can also use tab characters, like below.
The active code below uses tab characters to make the table neater.
1#include <iostream>
2
3void print_multiples (int n) {
4 int i = 1;
5 while (i <= 6) {
6 std::cout << n*i << '\t';
7 i = i + 1;
8 }
9 std::cout << '\n';
10}
11
12int main() {
13 int i = 1;
14 while (i <= 6) {
15 print_multiples (i);
16 i = i + 1;
17 }
18}
Q1
What is the purpose of generalization?
Q2
Create a function called powers_of_two which prints out a table
with the powers of two up to \(2^{5}\).
-
x++; } } -
cout << x << '\t' << pow(2, x) << '\n'; -
cout << x << '\t' << pow(x, 2) << '\n'; -
int x = 1; -
void powers_of_two () { -
while (x <= 5) {
Q3
Now let's generalize the function to print out the powers of
a parameter n up to \(n^{5}\).
Create a function called powers_of_n
which takes an int n as a parameter.
-
x++; } } -
cout << x << '\t' << pow(5, x) << '\n'; -
cout << x << '\t' << pow(n, x) << '\n'; -
int x = 1; -
void powers_of_n (int n) { -
void powers_of_n (string n) { -
while (x <= 5) {
More to Explore
From cppreference.com