Array question

May 18, 2013 at 3:10am
I need to write a code that calculates the average score based on the number of scores the user inputs and it has to be between 1 and 20. What am i doing wrong?
Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

using namespace std;

int main()
{
    int size,count,sum;
    double average;
    cout << "Enter class size <1-20>" << endl;
    cin >> size;
    int numbers [size];
    if (size>=1 && size<=20)
    {
        for (count=0;count<size;count++)
            {cout << "Enter Score" << endl;
            cin >> size;
            sum=sum+size;
            average = sum / size;
            }
        cout << "Original Scores"<< endl;
        cout << size;
        cout << "Average Score"<<endl;
        cout << average;
    }

    cout << "Class size is NOT within required range. The required range is 1 to 20 ";

    return 0;
}
May 18, 2013 at 4:16am
Well, your array numbers has a problem- you are defining its size using a variable. While that may be allowed in some compilers, it isn't in others. Also... you're altering size in your for loop. Size is also a parameter in the for loop for when it exits... you see the issue with that, right? Also, you aren't putting anything back into the array you just defined. Your average variable is also going to be wrong...

I recommend you go back through the documentation, up to arrays. It should help you see what's wrong in your code.
May 18, 2013 at 9:09am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>

using namespace std;

int main()
{
    const size_t N = 20;
    size_t size;

    while ( true )
    {
        size = 0;
        cout << "Enter class size <1-" << N << ">: ";
        cin >> size;

        if ( !cin || ( size > 0 && size <= N ) ) break;

        cout << "Class size is NOT within required range. The required range is 1 to " << N << endl;
    }

    if ( size )
    {
        int sum = 0;
        for ( size_t i = 0; i < size; i++)
        {
            int score;
            cout << "Enter Score: ";
            cin >> score;
            sum += score;
        }

        double average = static_cast<double>( sum ) / size;
        cout << "Sum of scores: " << sum << std::endl;
        cout << "Average Score: " << average << endl;
    }

    return 0;
}
Last edited on May 18, 2013 at 9:10am
Topic archived. No new replies allowed.