Function Reuse
Compare these two pieces of code that achieve the same result. Take note of how the second piece of code takes less time to analyse and understand.
Implement the functions in the second piece of code:
calculateSum(const std::vector<int>& numbers)calculateProduct(const std::vector<int>& numbers)findMaximum(const std::vector<int>& numbers)
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// Sum of numbers
int sum = 0;
for(int num : numbers) {
sum += num;
}
std::cout << "Sum of numbers: " << sum << std::endl;
// Product of numbers
int product = 1;
for(int num : numbers) {
product *= num;
}
std::cout << "Product of numbers: " << product << std::endl;
// Maximum number
int maxNum = numbers[0];
for(int num : numbers) {
if(num > maxNum) {
maxNum = num;
}
}
std::cout << "Maximum number: " << maxNum << std::endl;
return 0;
}
#include <iostream>
#include <vector>
// Function declarations (implement these functions)
int calculateSum(const std::vector<int>& numbers);
int calculateProduct(const std::vector<int>& numbers);
int findMaximum(const std::vector<int>& numbers);
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
int sum = calculateSum(numbers);
std::cout << "Sum of numbers: " << sum << std::endl;
int product = calculateProduct(numbers);
std::cout << "Product of numbers: " << product << std::endl;
int maxNum = findMaximum(numbers);
std::cout << "Maximum number: " << maxNum << std::endl;
return 0;
}
Answer
Here are the function implementations:
// Function definitions
int calculateSum(const std::vector<int>& numbers) {
int sum = 0;
for(int num : numbers) {
sum += num;
}
return sum;
}
int calculateProduct(const std::vector<int>& numbers) {
int product = 1;
for(int num : numbers) {
product *= num;
}
return product;
}
int findMaximum(const std::vector<int>& numbers) {
int maxNum = numbers[0];
for(int num : numbers) {
if(num > maxNum) {
maxNum = num;
}
}
return maxNum;
}
You can add these functions to the second piece of code to achieve the same result with better readability and reusability.