Hi, as part of my computer science homework I have to edit this program so that it works as you'd expect.
Originally there were 3 errors I was tasked to fix, however, when I run it I can enter the 6 values and it produces an average correctly but immediately after I get a error -
'C++ Runtime Library' error stating 'Stack around the variable 'pollution_level' was corrupted'.
I feel as though I've missed something but I can't quite see what it is.
Any help would be greatly appreciated =) Thank you in advance.
#include "stdafx.h"
#include <iostream>
usingnamespace std;
int main()
{
int pollution_level[6];
double average = 0;
int counter =1;
while (counter<=6)
{
cout<<"Enter pollution level for day "<<counter<<" range (1-100): ";
cin>>pollution_level[counter];
average = average + pollution_level[counter];
counter++;
}
cout<<endl;
cout<< "The average pollution level over those 6 days was :"<<average/6<<endl;
return 0;
}
Your while loop is subscripting past the end of the array. You declared the array to have 6 entries. Those entries are [0] to [5]. Your loop is looking at entries [1] to [6].
#include "stdafx.h"
#include <iostream>
usingnamespace std;
int main()
{
int pollution_level[6];
double average = 0;
int counter = 1;
while (counter<=6)
{
cout<<"Enter pollution level for day "<<counter<<" range (1-100): ";
cin>>pollution_level[counter-1];
average = average + pollution_level[counter-1];
counter++;
}
cout<<endl;
cout<< "The average pollution level over those 6 days was :"<<average/6<<endl;
return 0;
}
I seemed to have fixed it this way but I'm not sure if its really the most 'elegant' way to do it:
Your fix will work, but it is better to think in the standard C/C++ idiom of arrays, vectors and such as indexed from 0 to n-1. Subtracting 1 from the subscript everytime you reference the array is prone to errors (as you discovered).