I'm trying to write code with arrays and loops for a program that allows a user to enter 20 numbers, then displays each number and its difference from the numeric average of the numbers entered
every time i compile and run the script it freezes up after the first number i enter
#include <iostream>
#include <string>
usingnamespace std;
int main ()
{
int SIZE = 12;
int numbers[SIZE];
int value = 0;
int counter = 0;
int total = 0;
int average = 0;
int diffFromAvg = 0;
int SENTINEL = -1;
cout << "please enter a positive number: " << endl;
cin >> value;
while (( counter < SIZE ) and ( value != SENTINEL ));
{
total = total + value;
numbers[counter] = value;
counter = counter + 1;
if (counter != SIZE);
{
cout << "please enter a positive number: ";
cin >> value;
}
}
if (counter > 0)
{
average = total/counter;
for ( int i = 0; counter - 1; )
{
diffFromAvg = numbers[i] - average;
cout << "Number["<<i<<"]: " << numbers[i] << "difference from average is: " << diffFromAvg;
}
}
else
cout << "Processing incomplete. No values in the array.";
return 0;
}
Line 8 should be const or constexpr int, instead of just int. GCC has an extension that lets it being lenient about this, but it should not be relied on.
Line 21: Remove the semi-colon! It appears to be "freezing" because you have an infinite loop.
Line 26: Also remove the semi-colon here. In both cases, you're cutting off your while/if statement so it doesn't have a body.
Line 38: You should review for-loop syntax.
Probably you meant for (int i = 0; i < counter; i++)
Note that averages are often not whole numbers. If you don't want integer rounding to happen, change average to a double and do something like: average = static_cast<double>(total) / counter;