Ask Question
11 January, 10:08

Write a method that returns the sum of all the elements of an array of ints that have an odd index.

+3
Answers (1)
  1. 11 January, 10:36
    0
    import java. io.*;

    import java. util. Scanner;

    class Odd {

    public static void main (String[] args) {

    Scanner ele=new Scanner (System. in); //creating a scanner object.

    int n, sum=0; //declaring n and sum and initializing sum with 0.

    n=ele. nextInt (); //taking input of the n.

    int [] arr = new int[n]; //declaring an array arr.

    for (int i=0; i
    {

    arr[i]=ele. nextInt (); //taking input of the array.

    }

    for (int i=0; i
    {

    if (i%2!=0) / /adding to the if index is odd.

    {

    sum+=arr[i];

    }

    }

    System. out. println (sum);

    }

    }

    Input:-

    6

    1 2 3 4 5 6

    Output:-

    12

    Explanation:

    First I have created an a scanner object ele. I have taken two integers n and sum, n for number of array elements and sum for calculating the sum of odd indexed elements hence initializing it with 0. Then I have created an array named arr. Then taking the input of the n and array elements. Then looping over the array and calculating the sum.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write a method that returns the sum of all the elements of an array of ints that have an odd index. ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers