Dynamic Array

Hi. Why I can't get the sum and average of entered marks?

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
#include <iostream>
using namespace std;

int main ()
{
  int i,n;
  float sum, avg;
  float *p;
  cout << "How many marks you like to enter: ";
  cin >> i;
  p = new float [i];

    for (n=0; n<i; n++)
    {
      cout << "Enter marks " << n + 1 << ": ";
      cin >> p[n];

    }

    cout << "You have entered: ";

    for (n=0; n<i; n++)
    {
        cout << p[n] << " ,";

        sum += p[n];
        avg = sum/p[i];
    }

    cout << "\nSum of marks is: " << sum << endl;
    cout << "Average marks is: " << avg << endl;

    delete[] p;
    return 0;
  }
sum and average are not initialized they are not default initialized to 0. So on lines 26 and 27 they are probably going to have an arbitrary number. By the way your average calculation is pretty wrong. Average = Sum / Count. So in other words if you have 1 4 9 then it would be Average = 14 / 3 = 4.67

*forgot to mention this but you should put the average outside the loop. There is no reason to calculate it each time. You could also add to the sum while you input the numbers.
Last edited on
closed account (j3Rz8vqX)
Sum is uninitialized, set it to 0 somewhere before you use it; it is accumulating garbage + p[n].

And use: avg = sum/i; not p[i].

p[i] is beyond the array by 1, and has no useful data that you would need.
Average could also be calculated after the accumulation of sums; can save 1 procedure per cycle during second for loop; maybe.

Have a good day.
Last edited on
Thanks
Topic archived. No new replies allowed.