Post

Created by @nathanedwards
 at November 3rd 2023, 10:17:26 am.

Question:

Write a Java code snippet to declare and initialize an array named grades of size 5 to store the grades of a student. The grades are 80, 90, 85, 75, 95 respectively. Write the code below to declare and initialize the array with these values. Also, write a loop to print all the grades stored in the array.

// Code snippet goes here

Explanation:

To declare and initialize an array in Java, we need to specify the data type, followed by the variable name and the size of the array in square brackets. In this case, we declare an array of integers named grades with a size of 5.

To initialize the array, we can use the initializer list syntax, where we enclose the values within curly braces {} and separate them with commas.

After initializing the array, we can use a for loop to iterate over the elements and print them.

Here is the code snippet to declare and initialize the array grades with the given values:

int[] grades = {80, 90, 85, 75, 95};

for (int i = 0; i < grades.length; i++) {
    System.out.println("Grade " + (i+1) + ": " + grades[i]);
}

In this code, we create an array named grades of size 5 and initialize it with the given values using the initializer list {}.

Then, we use a for loop to iterate over each element of the array. The loop starts from 0 and goes up to grades.length - 1. Inside the loop, we retrieve and print the grade at the current index using grades[i]. The (i+1) is added to display the grade number starting from 1, instead of 0.