theredfox24 theredfox24 - 4 days ago 5
Java Question

How to print out even-numbered indexes for arrays in Java?

I'm supposed to write a program using for loops that print out the even indexes of my array. For example, if I create an array that has 10 numbers, it will have indexes from 0-9 so in that case I would print out the numbers at index 2, 4, 6 and 8. This is what I wrote so far but it doesn't work. Please note that I am not trying to print out the even numbers of the array. All I want are the even indexes.

Example I enter the following array:

3,7,5,5,5,7,7,9,9,3


Program output:

5 // (the number at index 2)
5 // (the number at index 4)
7 // (the number at index 6)
9 // (the number at index 8)


My Code:

public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have

Scanner key = new Scanner(System.in);

System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];

// let the user enter the values of the array.
for (int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for (int index = 0; index < array.length; index ++)
{
if (array[number+1]%2==0)
System.out.print(array[number]);
}
}
}

Answer

You can just change your for loop and get rid of the inner IF...

for( int index = 0; index < array.length; index += 2) {
    System.out.println(array[index]);
}
Comments