Printing array elements with a for loop

This is a challenge question from my online textbook I can only get the numbers to prin forward… 🙁

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]).

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;

  /* Your solution goes here  */

  for(i=0; i<NUM_VALS; i++){
     System.out.print(courseGrades[i] + " ");
  }

  for(i=NUM_VALS -1; i>3; i++){
     System.out.print(courseGrades[i]+ " ");
     }

  return;
}
}

Leave a Comment