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.

  • 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 3:22
up vote 0 down vote accepted

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);
}

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);
}
  • @CollinD Because the variable sum is a double, it is possible to divide by an int and still get a double result. – Tim Biegeleisen Oct 13 '15 at 3:36
  • Good to know! Wasn't quite sure how Java would decide to handle that one. – CollinD Oct 13 '15 at 3:59

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.