AP® Computer Science A

Free Version

Upgrade subject to access all content

Moderate

Optimize Method That Adds Elements From Array

APCSA-LVFLD4

Consider the following method. You are told that it is not optimized and can be improved to run faster.

Of the choices below, which is the BEST replacement for this method to better optimize it?

// Preconditions: Scores contains AP scores 1-5 or zero if not filled.
//                Scores values are filled sequentially from beginning of array. 
//                Scores may not be full of valid AP scores.
public static double averageAPScore(int[] scores)
{
    double sum = 0;
    for (int i=0; i < scores.length; i++)
    {
        sum += scores[i];
    }

    int count=0;
    for (int j=0; j < scores.length; j++)
    {
        if (scores[j] > 0)
            count++;
    }
    return sum / count;
}
A
public static double averageAPScore(int[] scores)
{
    double sum = 0;
    for (int i=0; i < scores.length || scores[i] != 0; i++)
    {
        sum += scores[i];
        count++;
    }
    return sum / count;
}
B
public static double averageAPScore(int[] scores)
{
    double sum = 0;
    for (int i=0; i < scores.length; i++)
    {
        if (scores[i] == 0)
            break;
        sum += scores[i];
    }

    int count = 0;
    for (int j=0; j < scores.length; j++)
    {
        if (scores[j] == 0)
            break;
        count++;
    }
    return sum / count;
}
C
public static double averageAPScore(int[] scores)
{
    double sum = 0;
    for (int i=0; i < scores.length && scores[i] > 0; i++)
    {
        sum += scores[i];
        count++;
    }
    return sum / count;
}
D
public static double averageAPScore(int[] scores)
{
    double sum = 0;
    for (int i=0; i < scores.length; i++)
    {
        if (scores[i] > 0)
        {
            sum += scores[i];
            count++;
        }
    }
    return sum / count;
}
E
public static double averageAPScore(int[] scores)
{
    double sum = 0;
    for (int i=0; i < scores.length; i++)
    {
        sum += scores[i];
    }

    int count = 0;
    for (int i=0; i < scores.length; i++)
    {
        if (scores[i] > 0)
            count++;
    }
    return sum / count;
}