How to calculate the sum of numbers in an array while skipping every even index?
- User
How to calculate the sum of numbers in an array while skipping every even index?
- Assistant
To calculate the sum of numbers in an array while skipping every even index, you can use a loop that increments the index by 2 in each iteration. Here's an example of how you can do it in Python:
pythondef sum_odd_indices(arr): total = 0 for i in range(1, len(arr), 2): total += arr[i] return totalExplanation:
- We define a function called
sum_odd_indicesthat takes an arrayarras input. - We initialize a variable
totalto 0, which will store the sum of the numbers at odd indices. - We start a loop that iterates over the indices of the array, starting from index 1 (the first odd index) and incrementing by 2 in each iteration using
range(1, len(arr), 2). This ensures that we only consider the odd indices. - Inside the loop, we add the element at the current odd index () to the variable.
- We define a function called
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.