228k views
4 votes
Create an array in java of integers and fill it with the numbers 2 -4 6 -8 10 ………. -96 98 -100 then display all these numbers. (hint: a%b==0 means a is divisible by b )

User Milosmns
by
7.8k points

1 Answer

0 votes

Final Answer:

public class Main {

public static void main(String[] args) {

int[] array = new int[50];

int num = 2;

for (int i = 0; i < 50; i++) {

array[i] = num;

if (i % 2 == 0) {

num += 2;

} else {

num *= -1;

}

}

for (int value : array) {

System.out.println(value);

}

}

}

Step-by-step explanation:

To create an array in Java with the given sequence, we initialize an integer array of size 50. We then use a loop to fill the array with the numbers. Starting with 2, we alternate between adding 2 and multiplying by -1 to achieve the sequence. If the index is even, we add 2 to the previous number; if it’s odd, we multiply the previous number by -1. After populating the array, we use another loop to display all the numbers in the array.

The sequence starts with 2 and follows a pattern of adding 2 and then multiplying by -1 alternatively. This pattern is achieved by using a conditional statement within a loop to fill the array with the required numbers. The final step involves iterating through the array and displaying each element using a for-each loop.

This approach ensures that the array is correctly filled with the specified sequence of numbers and then displays them as required.

User Adam Simpson
by
8.2k points