Tutorialspoint
Problem
Solution
Submissions

Sum of all even numbers in an array

Certification: Basic Level Accuracy: 51.28% Submissions: 39 Points: 5

Write a C# program to find the sum of all even numbers in a given integer array. The program should iterate through the array, identify even numbers, and compute their sum.

Example 1
  • Input: arr = [1, 2, 3, 4, 5, 6]
  • Output: 12
  • Explanation:
    • Step 1: Initialize a sum variable to 0.
    • Step 2: Iterate through each element in the array.
    • Step 3: Check if each element is even (divisible by 2).
    • Step 4: For even numbers (2, 4, 6), add them to the sum.
    • Step 5: Return the final sum: 2 + 4 + 6 = 12.
Example 2
  • Input: arr = [7, 9, 11, 13]
  • Output: 0
  • Explanation:
    • Step 1: Initialize a sum variable to 0.
    • Step 2: Iterate through each element in the array.
    • Step 3: Check if each element is even (divisible by 2).
    • Step 4: No even numbers are found in the array.
    • Step 5: Return the sum, which remains 0.
Constraints
  • 1 ≤ array length ≤ 10^5
  • -10^9 ≤ array elements ≤ 10^9
  • Time Complexity: O(N)
  • Space Complexity: O(1)
ArraysMathematicalTutorialspointShopify
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Iterate Through Array: Loop through all elements of the array.
  • Check Even Numbers: Use num % 2 == 0 to identify even numbers.
  • Sum Calculation: Add even numbers to a running sum.
  • Edge Case: Handle cases where no even numbers exist (return 0).

Steps to Solve:

The following are the steps to find the sum of all even numbers in an array:

  • Initialize a sum variable to 0.
  • Iterate through each element in the array.
  • Check if each element is even (divisible by 2):
    • Use the modulo operator (%) to check if the number divides evenly by 2.
    • If arr[i] % 2 == 0, the number is even.
  • If the element is even, add it to the sum.
  • After iterating through all elements, return the final sum.

Submitted Code :