cppbeginner10 minutes
Refactor a Function to Calculate Sum of Array Elements
Improve the clarity and quality of a simple C++ function that sums elements in an integer array, while keeping its behavior unchanged.
Challenge prompt
You are given a C++ function that calculates the sum of the elements in an integer array. The function works correctly but the code style and structure can be improved to make it more readable and maintainable. Refactor the function without changing its output or functionality. Focus on simplifying the loop, improving variable naming, and removing any redundant code.
Guidance
- • Keep the function signature the same for compatibility.
- • Focus on improving variable names and removing unnecessary parts.
- • Make loops and code structure cleaner and easier to understand.
Hints
- • Consider using descriptive variable names for better readability.
- • Check the loop syntax and see if it can be simplified or modernized.
Starter code
int sumArray(int arr[], int size) {
int s = 0;
for (int i = 0; i < size; i++) {
s = s + arr[i];
}
return s;
}Expected output
sumArray({1, 2, 3, 4, 5}, 5) should return 15
Core concepts
loopsfunctionsvariable naming
Challenge a Friend
Send this duel to someone else and see if they can solve it.