Question:
Declare and initialize an array named myArray
of type int
, with 5 elements, that contains the following values: 10, 20, 30, 40, and 50.
Write the code to declare and initialize the array with the given values.
Code Answer:
int[] myArray = {10, 20, 30, 40, 50};
Explanation:
To declare and initialize an array, you first indicate the type of the elements the array will hold, followed by the name of the array. In this case, the array is of type int
and is named myArray
.
The array is then initialized by using curly braces {}
to enclose the values that the array will contain. The values are separated by commas. In this case, we initialize the array myArray
with the values 10, 20, 30, 40, and 50.
The int[]
before the array name indicates that myArray
is an array of integers. It tells the compiler that the variable myArray
will be an integer array that can hold multiple integer values.
So, the code int[] myArray = {10, 20, 30, 40, 50};
declares an array named myArray
of type int
, with 5 elements, containing the values 10, 20, 30, 40, and 50.