Sovi.AI - AI Math Tutor

Scan to solve math questions

QUESTION IMAGE

program to print sum of even and odd elements in an array prerequisite …

Question

program to print sum of even and odd elements in an array

prerequisite - array basics
given an array, write a program to find the sum of values of even and odd index positions separately.

examples:

input: arr = {1, 2, 3, 4, 5, 6}
output: even index positions sum 9
odd index positions sum 12
explanation: here, n = 6 so there will be 3 even index positions and 3 odd index positions in an array
even = 1 + 3 + 5 = 9
odd = 2 + 4 + 6 = 12

input: arr = {10, 20, 30, 40, 50, 60, 70}
output: even index positions sum 160
odd index positions sum 120
explanation: here, n = 7 so there will be 3 odd index positions and 4 even index positions in an array
even = 10 + 30 + 50 + 70 = 160
odd = 20 + 40 + 60 = 120

Explanation:

🆕 New Concept Discovered: Array Index Traversal
Iterating through arrays using index parity (even vs. odd)

Step 1: Understand 0-Based Indexing

In most programming languages (like Python, C++, Java, and JavaScript), arrays use 0-based indexing. This means the first element is at index 0, the second is at index 1, and so on.

For the array arr = {1, 2, 3, 4, 5, 6}:

  • Index 0: 1 (Even index)
  • Index 1: 2 (Odd index)
  • Index 2: 3 (Even index)
  • Index 3: 4 (Odd index)
  • Index 4: 5 (Even index)
  • Index 5: 6 (Odd index)

Step 2: Design the Algorithm

To solve this problem, we need to:

  1. Initialize two variables to store the sums: even_sum = 0 and odd_sum = 0.
  2. Loop through the array from index i = 0 to n - 1.
  3. For each index i, check if it is even or odd using the modulo operator %:
  • If i % 2 == 0, add the element arr[i] to even_sum.
  • Otherwise, add arr[i] to odd_sum.
  1. Print both sums.

Step 3: Implement the Code

Here is the implementation of the algorithm in Python:

def sum_even_odd_indexed_elements(arr):
    even_sum = 0
    odd_sum = 0

    for i in range(len(arr)):
        if i % 2 == 0:
            even_sum += arr[i]
        else:
            odd_sum += arr[i]

    print("Even index positions sum", even_sum)
    print("Odd index positions sum", odd_sum)

# Example Test Case
arr = [1, 2, 3, 4, 5, 6]
sum_even_odd_indexed_elements(arr)

Answer:

def sum_even_odd_indices(arr):
    even_sum = 0
    odd_sum = 0
    for i in range(len(arr)):
        if i % 2 == 0:
            even_sum += arr[i]
        else:
            odd_sum += arr[i]
    return even_sum, odd_sum