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 printParity in SectionΒ 4.3 and isSingleDigit in SectionΒ 5.8.
void printMultiples(int n) {
int i = 1;
while (i <= 6) {
cout << n * i << " ";
i = i + 1;
}
cout << endl;
}
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.
By now you can probably guess how we are going to print a multiplication table: weβll call printMultiples repeatedly with different arguments. In fact, we are going to use another loop to iterate through the rows.
Now letβs generalize the function to print out the powers of a parameter n up to \(n^{5}\text{.}\) Create a function called powersOfn which takes an int n as a parameter.