Question:
Create a program that declares and initializes an array named numbers
with 5 integer elements. Each element of the array should have a value that is twice the index position of that element. Finally, print the elements of the numbers
array.
Answer:
public class DeclareInitializeArrayExample {
public static void main(String[] args) {
// Declaring an array named 'numbers' with size 5
int[] numbers = new int[5];
// Initializing the elements of the 'numbers' array
for(int i = 0; i < numbers.length; i++) {
numbers[i] = 2 * i;
}
// Printing the elements of the 'numbers' array
for(int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
Explanation:
In this program, we are declaring and initializing an array named numbers
with 5 integer elements.
int[] numbers = new int[5];
numbers
array. The index i
of the array is used to calculate the element value by multiplying 2
with i
: numbers[i] = 2 * i;
numbers
array, we use another for loop. We iterate through each element using the index i
and print the element value along with the index i
: System.out.println("Element at index " + i + ": " + numbers[i]);
The output of the program will be:
Element at index 0: 0
Element at index 1: 2
Element at index 2: 4
Element at index 3: 6
Element at index 4: 8
This confirms that the array numbers
has been successfully declared, initialized, and printed with the required values.