Ask Question
14 April, 01:39

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. 14 April, 02:03
    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?
Get 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 there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers