DRY Refactor
Refactor the following code to eliminate redundancy by using functions and loops with arrays/vectors. The original code calculates the squares and cubes of three numbers and prints them.
#include <iostream>
int main() {
int num1 = 2;
int num2 = 3;
int num3 = 4;
// Calculating squares
int square1 = num1 * num1;
int square2 = num2 * num2;
int square3 = num3 * num3;
// Calculating cubes
int cube1 = num1 * num1 * num1;
int cube2 = num2 * num2 * num2;
int cube3 = num3 * num3 * num3;
// Printing results
std::cout << "Square of " << num1 << " is " << square1 << std::endl;
std::cout << "Square of " << num2 << " is " << square2 << std::endl;
std::cout << "Square of " << num3 << " is " << square3 << std::endl;
std::cout << "Cube of " << num1 << " is " << cube1 << std::endl;
std::cout << "Cube of " << num2 << " is " << cube2 << std::endl;
std::cout << "Cube of " << num3 << " is " << cube3 << std::endl;
return 0;
}
Answer
#include <iostream>
#include <vector>
// Function to calculate the square of a number
int calculateSquare(int number) {
return number * number;
}
// Function to calculate the cube of a number
int calculateCube(int number) {
return number * number * number;
}
int main() {
// Vector of numbers
std::vector<int> numbers = {2, 3, 4};
// Loop through each number and print the square and cube
for(int number : numbers) {
std::cout << "Square of " << number << " is " << calculateSquare(number) << std::endl;
std::cout << "Cube of " << number << " is " << calculateCube(number) << std::endl;
}
return 0;
}
Key Improvements:
Functions: Created calculateSquare and calculateCube functions to encapsulate the logic for calculating squares and cubes. Loops: Used a loop to iterate through the list of numbers, reducing repetition in the code. Vectors: Stored numbers in a vector to easily manage and iterate over them.