Hey guys,

I am working on some software and I have ran into an issue which I cannot seem to get past. This is probably easy for most of you, but I am rather new to c++ and could use some help. Basically what I need to do is read a bunch of numbers from a text file ranging from 0-60 and then break them into three groups (0-20, 21-40, 41-60). Then from there I need to find how many numbers were in each group. So if my text file holds the following numbers: 3, 19, 28, 17, 35, 36, 58, 4, 26, 28, 5, 60, 48.......then I would need the program to read those numbers, store them into an array, and then count how many numbers fall into each category. So based on the those numbers the output should be something like:

There are 5 numbers in group 1 (0-20).

There are 5 numbers in group 2 (21-40).

There are 3 numbers in group 3 (41-60).

Like I said it is probably very easy, but I cannot seem to figure out how to get it done. Any help would be much appreciated. Thanks guys.

Recommended Answers

All 4 Replies

One way to do that is to create an integer to contain the sum of each group.

int sum1 = 0; // 0-20
int sum2 = 0; // 21-40
// etc for each group

Then while reading each value from the file compare it with the gruping

if( numRead >= 0 && numRead <= 20)
    sum1++;
else if( numRead >= 21 && numRead <= 40)
   sum2++;
/// etc

Another way is to use an array of ints, but if you have not studied arrays yet you might want to stick to the above method.

Thanks for the quick reply. I tried to use what you showed me but it is still giving me the same problem. Instead of adding up the sum, it is just printing like this:

There are 1 1 1 1 1 numbers in the 1st group.

I cannot seem to get it to add the 1's together. Any thoughts as to why this might be?

post code. I can't see your monitor very well from where I am sitting.

Why are u printing 1's every time u find a number in certain range. U just count them first (as suggested by Ancient Dragon) and at last print them one by one i.e
printf("There are %d numbers in Range (0-20)", sum1);
-
-
and so on

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.