0

Reversing an array with 2 for loops (second loop uses a constant)

There's this problem I've been trying to crack but the answer hasn't come to me: /*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]). 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. */ 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; courseGrades[0] = 7; courseGrades[1] = 9; courseGrades[2] = 11; courseGrades[3] = 10; //code above this comment must not be changed. for(i = 0; i < courseGrades.length; ++i){ System.out.print(courseGrades[i] + " "); } System.out.println(""); for(i = NUM_VALS - 1; i <= courseGrades.length; ?){ //Must find a way to reverse the array without changing i = NUM_VALS - 1. System.out.print(courseGrades[i] + " "); } System.out.println(""); } } There is a way to make the 2nd for loop work, but...how?

15th May 2018, 1:31 AM
Thomas Stevenson
Thomas Stevenson - avatar
2 Respostas
+ 1
You have infinite loop. In your "for" statement "i" never breaks the condition of the loop. "i" will always will be less than NUM_VALS because you decrease it with "--i". You should change it to: for(i = NUM_VALS - 1; i >=0 ; --i)
15th May 2018, 3:47 AM
Jack
Jack - avatar
0
Made a tweak: for(i = NUM_VALS - 1; i <= NUM_VALS; --i){ System.out.print(courseGrades[i] + " "); } Problem with this is it gives me this along with the result i was hoping for: 7 9 11 10 10 11 9 7 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at CourseGradePrinter.main(CourseGradePrinter.java:18).
15th May 2018, 1:49 AM
Thomas Stevenson
Thomas Stevenson - avatar