Here is my issue if anyone can help.

I am trying to write a program that will generate 100 random numbers between 1 and 50. With these numbers, I want to generate a list that will tell the number of random numbers that fell between 1-5, 6-10, 11-15, 16-20, ... , and 46-50. Print out the results as a histogram. I am hoping to get results such as:

1-5 (11) ***********
6-10 (8) ********
11-15 (12) ************
16-20 (9) *********
21-25 (10) **********
26-30 (11) ***********
31-35 (7) *******
36-40 (8) ********
41-45 (13) *************
46-50 (11) ***********

Here is my attempt so far, not so good.....

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i;
    int d1, d2;
    int a[100];    

    for(i = 1; i <= 50; i = i + 1)
        a[i] = 0;

    for(i = 0; i < 100; i = i + 1)
        {
        d1 = rand() % 49 + 1;
    
        a[d1] = a[d1] + 1;
        }

    for(i = 1; i <= 50; i = i + 1)
        {
        printf("%d: %d\t", i, a[i]);
        printf("*", a[i]);
        printf("\n");
        }
     printf("Please press ENTER to terminate.\n");
   getchar ();
    return 0;
}

I hope someone can help, even if there is a tutorial or anything.

What you need is an array of 10 integers to contain the count of each interval. For example a[0] is the number of random numbers that fall between 1 and 5, a[1] = 6-10, etc. After generating a random number at line 15 use a series of if statements to determine which array element to increment, such as if d1 >0 and d1 < 6 then increment a[0].

line 8: array a should be 10, not 100.

line 10: arrays are always numbered from 0 to the number of elements assigned to the array. So line 10 should look like this:

for(i = 0; i < 10; i = i + 1)

lines 20-25: you need two loops, not one. The outer loop counts from 0 to 10, and the inner loop from 0 to the value of a.

Thanks for the help I will try this out and keep you posted. Thanks a lot its appreciated greatly

Member Avatar for iamthwee

Don't you need to seed the random number?

Don't you need to seed the random number?

Not absolutely required -- if you don't see it then the program will generate the same set of random numbers every time it is run. Seeding only changes that behavior to generate a different set each time the program is run, assuming it uses a different seed such as the return value from time() function.

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.