0

Here is the assignment:

  1. Create an array to store 10 numbers.
  2. Using a loop, prompt the user to enter 10 grades and store them in the array.
  3. Then make another loop that prints the numbers in the array out backwards and adds up the numbers in the array.
  4. Use the sum to calculate the average of the numbers. Print out the average of the numbers.

My code so far:

public static void ar() {

    double[] grades = new double[10];
    Scanner kb = new Scanner(System.in);

    for(int i=0; i < grades.length; i++)
        grades[i]=kb.nextDouble();

    double sum=0;

    for(int j=10; j > grades.length; j--)
        sum=sum+grades[j];

    double ave = sum/10;

    System.out.println(ave);
}

However it only prints 0.0 ten times.

CollinD
  • 7,304
  • 2
  • 22
  • 45
Maria
  • 383
  • 1
  • 5
  • 21
  • Are you trying to write in Javascript? Or in Java? Big difference. Please fix your title if this is Java. – jfriend00 Oct 13 '15 at 03:22

2 Answers2

3

The bounds in your for loop to iterate backwards were wrong. You mean to use for (int j=10; j>=0; j--). Try this code:

public static void ar() {
    double[] grades = new double[10];
    Scanner kb = new Scanner(System.in);
    for (int i=0; i<grades.length; i++)
        grades[i] = kb.nextDouble();

    double sum = 0;

    for (int j=grades.length-1; j>=0; j--)
        sum = sum + grades[j];

    double ave = sum / 10;
    System.out.println(ave);
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Here is an annotated solution indicating what was changed from your initial code. You were definitely on the right track, just a few small issues.

public static void ar() {

    double[] grades = new double[10];
    Scanner kb = new Scanner(System.in);

    for(int i=0; i < grades.length; i++)
        grades[i]=kb.nextDouble();

    double sum=0;

    for(int j=9; j >= 0; j--) //Note here that we've changed our condition. It was running zero times before. Additionally it now runs from 9-0, since the last index is 9
        sum=sum+grades[j];

    //Look out for Integer Arithmetic!
    double ave = sum/10.0;

    System.out.println(ave);
}
CollinD
  • 7,304
  • 2
  • 22
  • 45