issue with array in the while loop

Hi I am having difficulty with printing only 20 values in my loop. It should only repeat the loop 20 times but mine is repeating it 21 times. Can someone look over my code and tell me what I am doing wrong?

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
53
54
55
56
57
58
59
60
  #include <iostream>
#include <iomanip>
using namespace std;

int const MAX_VALUES = 20;

void programInfo();
void inputList(double numbers[], int & count);


int main()
{
	int count = 0;
	double numbers[MAX_VALUES];
	programInfo();
	cout << "\n";
	cout << fixed << showpoint << setprecision(1);
	inputList(numbers,count);
	



	return 0;
}


void programInfo()
{

	cout << "\n";
	cout << "Please follow instructions carefully." << endl;
	cout << "Enter one value at a time (at least 3 and up to 20)." << endl;
	cout << "You must enter valid data or program will not work." << endl;
	cout << "Enter -1 to signal end of data (-1 or -1.0)." << endl;
}

void inputList(double numbers[], int & count)
{
	count = 0;
	double value;

	cout << "Please enter a value -->";
	cin >> value;

	while (value != -1.0 && count < MAX_VALUES)
	{
		numbers[count] = value;
		count = count + 1;
		cout << "Please enter a value -->";
		cin >> value;
	}
	cout << "\n";
	cout << "There are " << count << " values in the data set." << endl;

	if (count < 3)
	{
		cout << "Error: You entered less than 3 values." << endl;
		cout << "Please enter more values." << endl;
	}
}
Last edited on
closed account (48T7M4Gy)
Run this simplification and you'll see what is happening to item numbers and item counts given the initialisation and incrementing of 'count'.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int const MAX_VALUES = 20;

int main()
{
	int count = 0;
	
	while (count < MAX_VALUES)
	{
	    std::cout << "Item number: " << count << std::endl;
	    count++;
	}
	std::cout << "Number of items: " << count << std::endl;
	return 0;
}


Item number: 0
Item number: 1
Item number: 2
Item number: 3
Item number: 4
Item number: 5
Item number: 6
Item number: 7
Item number: 8
Item number: 9
Item number: 10
Item number: 11
Item number: 12
Item number: 13
Item number: 14
Item number: 15
Item number: 16
Item number: 17
Item number: 18
Item number: 19
Number of items: 20
 
Exit code: 0 (normal program termination)

Topic archived. No new replies allowed.