Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Sum of Even Elements

Sum even-valued entries in a list. Students filter by a value's remainder and keep repeated contributions instead of counting matches or selecting even indexes.

IntermediatePhase 4 - Level 2: Searching & Counting LogicExample 6 of 10
sum-of-even-elements.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Sum even elements
8sum_even = 0
9for element in arr:
10 if element % 2 == 0:
11 sum_even += element
12
13print(f"Sum of even elements: {sum_even}")

Output

Enter array size: 5
Element 1: 2
Element 2: 3
Element 3: 4
Element 4: 5
Element 5: 6
Sum of even elements: 12

In this one

  • Filter by value parity
  • Sum repeated contributions
  • Include negative evens

How it works

  1. 1

    Initialize sum_even zero.

  2. 2

    Add each element whose remainder modulo two is zero.

  3. 3

    Print the resulting total.

Edge cases

Are even indexes selected?

Are even indexes selected?

No. The parity of each value is tested.

What if no values are even?

What if no values are even?

The sum remains zero.

What's going on

sum_even starts at zero. Every element divisible by two is added with its full value.

For 2, 3, 2, the result is four because both twos contribute. The filter concerns values, not positions. Negative even values are also added, and zero qualifies without changing the total. The original list remains unchanged.

Are even indexes selected? No. The parity of each value is tested.

What if no values are even? The sum remains zero.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is added for a matching value six?

Pick an answer to check it.

Question 2

Are even indexes selected?

Pick an answer to check it.

Questions people ask

Are even indexes selected?

No. The parity of each value is tested.

What if no values are even?

The sum remains zero.

What is added for a matching value six?

Six.