Write a for loop to print all elements in courseGrades, following each element with a space (including the last). Print forwards, then backwards. End each loop with a newline. Ex: If courseGrades = {7, 9, 11, 10}, print:

7 9 11 10
10 11 9 7

Hint: Use two for loops. Second loop starts with i = NUM_VALS - 1.


Note: These activities may test code with different test values. This activity will perform two tests, the first with a 4-element array (int courseGrades[4]), the second with a 2-element array (int courseGrades[2]). See How to Use zyBooks.

Also note: If the submitted code tries to access an invalid array element, such as courseGrades[9] for a 4-element array, the test may generate strange results. Or the test may crash and report "Program end never reached", in which case the system doesn't print the test case that caused the reported message.

code:

import java.util.Scanner;

public class CourseGradePrinter {
public static void main (String [] args) {
final int NUM_VALS = 4;
int[] courseGrades = new int[NUM_VALS];
int i = 0;

courseGrades[0] = 7;
courseGrades[1] = 9;
courseGrades[2] = 11;
courseGrades[3] = 10;


return;
}
}

Respuesta :

Answer:

The code to this question can be described as follows:

Code:

System.out.println("first we simply prints array value, then prints value in reverse order: "); //message

//loop to print array value  

for(i=0; i<NUM_VALS; ++i) //using for loop

{

System.out.print(courseGrades[i]+" "); //print values

}  

System.out.print("\n");

//loop to print array value in reverse order  

for(i=NUM_VALS-1; i>=0; --i) //using for to print value in reverse order  

{

System.out.print(courseGrades[i]+" "); //print value

}

Explanation:

In the above code two for loop is declared, in which first loop it prints array value normally, and in the second loop it prints array value in its reverse order, the working of both loops can be described as follows:

  • In the first for loop, the "i" variable is used that starts from 0 and ends when the value of "i" is less than "NUM_VALS", inside the loop it prints its value.
  • In the second loop, the "i" variable starts from "NUM_VALS-1", and ends when the value of i is greater than equal to 0, and inside the loop, the print method is used that prints array value in reverse order.
ACCESS MORE