Even Numbers From Array: Buggy Code in C++ (Time Complexity: O(n))


Inside the code editor we've tried to write a function that takes an array nums as argument and prints to the console the even numbers from that array.

So when we called printEvenNumbers({2, 1, 0, 4, 3}), we expected our code to print:

2
0
4

but it seems like we made some mistakes because when we run our code, it prints:

even
even

Assignment:

Your task is to fix our function such that it prints the even numbers from the array.

Understanding the Problem

The core challenge of this problem is to correctly identify and print the even numbers from a given array. This is a common task in programming, often used in filtering data based on specific criteria. A potential pitfall is misunderstanding the condition for even numbers or incorrectly handling the array iteration.

Approach

To solve this problem, we need to iterate through the array and check each number to see if it is even. A number is even if it is divisible by 2 (i.e., num % 2 == 0). The initial naive solution might involve checking each number and printing "even" instead of the actual number, which is incorrect.

Naive Solution

The naive solution might look like this:

void printEvenNumbers(std::vector<int> nums) {
    for (int num : nums) {
        if (num % 2 == 0) {
            std::cout << "even" << std::endl;
        }
    }
}

This solution is incorrect because it prints the string "even" instead of the actual even numbers.

Optimized Solution

The optimized solution involves printing the actual even numbers. Here is the corrected approach:

void printEvenNumbers(std::vector<int> nums) {
    for (int num : nums) {
        if (num % 2 == 0) {
            std::cout << num << std::endl;
        }
    }
}

This solution correctly prints each even number from the array.

Algorithm

Here is a step-by-step breakdown of the algorithm:

  1. Iterate through each element in the array.
  2. Check if the current element is even by using the modulus operator (%).
  3. If the element is even, print it to the console.

Code Implementation

Below is the well-commented C++ code for the solution:

#include <iostream>
#include <vector>

// Function to print even numbers from an array
void printEvenNumbers(std::vector<int> nums) {
    // Iterate through each number in the array
    for (int num : nums) {
        // Check if the number is even
        if (num % 2 == 0) {
            // Print the even number
            std::cout << num << std::endl;
        }
    }
}

int main() {
    // Test the function with a sample array
    std::vector<int> nums = {2, 1, 0, 4, 3};
    printEvenNumbers(nums);
    return 0;
}

Complexity Analysis

The time complexity of this solution is O(n), where n is the number of elements in the array. This is because we iterate through each element once. The space complexity is O(1) as we are not using any extra space that scales with the input size.

Edge Cases

Potential edge cases include:

  • An empty array: The function should handle this gracefully without any output.
  • An array with no even numbers: The function should not print anything.
  • An array with all even numbers: The function should print all the numbers.

Examples:

printEvenNumbers({}); // No output
printEvenNumbers({1, 3, 5}); // No output
printEvenNumbers({2, 4, 6}); // Output: 2 4 6

Testing

To test the solution comprehensively, consider the following test cases:

  • Simple cases with a mix of even and odd numbers.
  • Edge cases as mentioned above.
  • Large arrays to test performance.

Using a testing framework like Google Test can help automate and manage these tests.

Thinking and Problem-Solving Tips

When approaching such problems:

  • Understand the problem requirements and constraints clearly.
  • Start with a simple solution and then optimize.
  • Consider edge cases and test your solution thoroughly.
  • Practice similar problems to improve your problem-solving skills.

Conclusion

In this blog post, we discussed how to fix a function that prints even numbers from an array. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is crucial for developing strong programming skills.

Additional Resources

For further reading and practice, consider the following resources: