arrays/loops question

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

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
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <string>
using namespace 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;

<edit: contexpr --> constexpr>
Last edited on
Thank you so much, i often times find myself using too many semi colons and sometimes not enough lol. im just learning. i appreciate it again!
Topic archived. No new replies allowed.