cppbeginner10 minutes
Refactor Messy C++ Function to Improve Readability and Efficiency
Given a function with redundant variables and unclear naming, refactor it to improve code quality without changing its behavior.
Challenge prompt
You are given a C++ function that calculates the sum of all integers from 1 to n but contains unnecessary variables and verbose logic. Refactor this function to make the code cleaner, more readable, and efficient, while maintaining the same functionality.
Guidance
- • Remove any redundant variables that do not contribute to the logic.
- • Rename variables to have more meaningful and concise names.
- • Simplify the loop or logic if possible, keeping the result unchanged.
Hints
- • Consider if all declared variables are necessary.
- • Think about meaningful variable names that explain their role clearly.
- • Check if the loop or summing logic can be expressed more cleanly.
Starter code
int calculateSum(int n) {
int totalSum = 0;
int temp = 0;
for(int i = 1; i <= n; i++) {
temp = i;
totalSum = totalSum + temp;
}
return totalSum;
}Expected output
For input n=5, the function should return 15 (1+2+3+4+5).
Core concepts
variablesloopsfunctionscode readability
Challenge a Friend
Send this duel to someone else and see if they can solve it.