You still haven't quite grasped a couple of important concepts.
When you define an array like this:
int someNumbers[10];
your array has space enough to hold ten integers.
The
first integer is accessed with the index
0. The tenth integer in this array is accessed with the index
9. In other words, the integer in the tenth
position is
offset nine positions from the position of the first integer.
So, you want your while loop to stop when the index is greater than the index of the last integer in the array.
1 2 3 4 5 6
|
int index = 0;
while (index < 10) {
// ...
index ++;
}
|
When this runs, index will be assigned in turn the values : 0, 1, 2 ,3 ,4, 5, 6, 7, 8, 9, 10. When it reaches ten, the expression
index < 10 will be false, so the loop will no longer run.
If you use the expression
index <=10, when index holds the value ten, the condition is still true, and the loop will continue to run one more time, in which case
someNumbers[index]
will be equivalent to
someNumbers[10]
which will attempt to access the
eleventh element of the array. In other words, you will read or write past the end of the array.
The expression you have used here
!(i<=250)
will be false when i is 0, so your loop will never run.
Second, the greatest value of a function is that it can be generalized. You do not need to write another function for each number that you would like to search for. By adding that value as a parameter, you can reuse the function you have already written.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
int totalb (int c[], int b[], int candyType)
{
int btotal =0 ;
int i = 0;
while (i < 250) {
if (c[i] == candyType) {
btotal = btotal + b[i];
}
i++;
}
return btotal;
}
|
Now you can use that function like this:
1 2 3 4 5 6 7 8 9
|
const unsigned int NUM_CANDY_TYPES = 8; // for example
int typeTotal[NUM_CANDY_TYPES];
for (int typeCode = 0; typeCode < NUM_CANDY_TYPES, typeCode++ ) {
typeTotal = totalb(c, b, typeCode);
}
|
This assumes, of course, that you know the greatest number used as a candy type.