Need help with c++ Arrays

I made a program that is suppose to receive 20 numbers or less and find the average, then show all numbers entered but my average does not show and a line pops up after every number returned.

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
39
40
41
42
  #include <iostream>
#include <cmath>

using namespace std;

int main()
{
    float num[20];
    int amount_num;

    cout<< "How many numbers do you want? (max 20)\n";
    cin>> amount_num;

    if (amount_num <= 0 || amount_num >= 21)
    {
        cout << "Invalid size.  Ending.\n";
        return 0;
    }
    for (int counter = 0; counter < amount_num; counter++)
    {
        cout<< "Enter value "<< counter<< ":"<< endl;
        cin>> num[counter];
    }


    for(int x = 0; x < amount_num; x++)
    {
        int total = 0;
        int average;
        total = total * num[x];

        average = total / amount_num;
        cout << "Average: "<< average << endl;
    }
        for(int x = 0; x < amount_num; x++)
        {
        cout << "You entered: " << endl;
        cout << num[x] << endl;
        }


}

Check the flow of your code - the loop on line 26 you are resetting total each loop, also you are multiplying and not adding value in num[x].

Furthermore, you are showing the average total calculated each time it loops - averages are calculated from adding all values together then dividing by the total amount of numbers, so you should be looping and adding all numbers together, then calculating the average at the end.

1
2
3
4
5
6
7
8
9
10

	int total = 0;
	int average;

	for (int x = 0; x < amount_num; x++)
		total = total + num[x];

	average = total / amount_num;
	cout << "Average: " << average << endl;


Got it Thanks!
Topic archived. No new replies allowed.