cppbeginner10 minutes
Fix the Bug in Counting Even Numbers in an Array
Identify and fix the bug in the given C++ function that is supposed to count the number of even numbers in an integer array.
Challenge prompt
The function countEvens takes an integer array and its size as input and should return the count of even numbers in the array. However, it currently returns incorrect results. Debug the function to make it work correctly.
Guidance
- • Check how the function iterates over the array.
- • Verify the condition used to identify even numbers.
- • Ensure the counter is updated properly within the loop.
Hints
- • Remember that an even number is divisible by 2 with zero remainder.
- • Make sure the loop uses the correct index and does not go out of bounds.
Starter code
int countEvens(int arr[], int size) {
int count = 0;
for (int i = 1; i <= size; i++) {
if (arr[i] % 2 == 1) {
count++;
}
}
return count;
}Expected output
For array {1, 2, 3, 4, 5, 6}, countEvens should return 3.
Core concepts
loopsarraysconditionalsmodulus operator
Challenge a Friend
Send this duel to someone else and see if they can solve it.