143k views
3 votes
Write a method that returns the sum of all the elements of an array of ints that have an odd index.

1 Answer

7 votes

Answer:

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<n;i++)

{

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

}

for(int i=0;i<arr.length;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

Step-by-step 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.

User Nkaenzig
by
6.0k points