Problem with a counting mechanism in a for loop

The problem is with taking 'counter' and applying it to the for loops at the end of the program so that the output only shows the inputs, and not the rest of the blank array. I'm probably overthinking this, but advice would be nice.

I'm aware the cout<<counter<<endl is unnecessary, but it helps me visualize where the problem is.

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


const int ARRAY_SIZE = 1000;
const int RANGE_SIZE = 100;

int arraySize[ARRAY_SIZE];
int arrayRange[RANGE_SIZE];

int input;
int x;
int counter;

int main()
{
       {
		x=0;
		while(input>=0 && input<=99 && x<ARRAY_SIZE)
		{
			 cin>>input;
			 arraySize[x]=input;
			 x++;
			 counter=x;
		}
		cout<<counter<<endl;

		for (int i = 0; i<counter ; i++)
		{
			int elem =arraySize[i];
			arrayRange[elem]++;
		}
 
		for (int i = 0; i<counter; i++)
		{
			 if(arrayRange[i]>0)
			{
			cout << i <<" appears "<<arrayRange[i]<<" times."<<endl;
		}
	}
 
}
return 0;
}
Last edited on
A few problems here:

Line 19: input is uninitialized. First time through the loop, behavior will be undefined.

Line 31: arrayRange is uninitialized. This line increments a random value.

Line 34: I think you want your termination condition to be i<100 since you are counting how many times each number occurred.
I'd like the termination condition to be the number of inputted values -1. So you're recommending a do while loop instead of a for loop?

EDIT: i<100 and the while loop got me, the program runs fine now. I'm not sure why the uninitialized array isn't causing a problem though.
Last edited on
What happens if the user enters a bunch of out of range values in the first loop? x keeps incrementing regardless and the values are still stored. Therefore when you reach line 30, 31 isn't there a possibility that some elements in arraySize are not acceptable as offsets into the other array?

Perhaps you want something more like this
1
2
3
4
5
6
7
8
int input = 0;  // ensure that you start with something in range
for(int x = 0;  x < ARRAY_SIZE; x++)
{
    while(cin>>input && input >=0 && input<=99)
    {
	arraySize[x]=input;
    }
}


http://www.parashift.com/c++-faq/stream-input-failure.html

Sometimes the fact that the program currently runs without crashing is quite deceiving.
Topic archived. No new replies allowed.