H2Oceans
H2Oceans

Reputation: 11

Generating and storing random numbers in array in c

I have to make an array containing 25 random numbers using a function to define the random numbers but keep getting it to either display only one number at a time (instead of all of them cell by cell) or simply displaying incorrectly i.e. 0. Here is what I have so far.

edit Code changed to correct stupid mistakes I missed rushing, however still unsure how to call funct as I am getting "too few arguments for funct 'get_value', apologies if this seems trivial but I am extremely new to coding thank you for your time.

int get_value (int t);
int main()
{
    srand(time(NULL));

    int temp[25], n;
    for(n=0; n<25; n++)
       {temp[n] = rand() %(40)+60;
        printf("value of %d at cell %d \n", n, temp[n]);}
    return 0;
}

  //function get_value()
  //needs to return rand # <-> 60 and 100 seed rand
  //use rand %40+60 to ensure value is <-> 60 and 100

int get_value (int t)
{
    return rand() %(40)+60;
}

Upvotes: 0

Views: 1404

Answers (3)

Bicolano
Bicolano

Reputation: 90

    //I think here's what you want to do.
    #include <stdio.h>
    #include <time.h>

    int main()
    {
        srand(time(NULL));
        int temp, i, j, h;
        int num_array[40];
        int i_need_25[25];

        //here's how im getting random numbers without repeating a number.
        //first, fill the array with numbers between
        for(i = 0; i < 41; i++)
        {
            num_array[i] = i + 60;
        }

        //then here's how we shuffle it
        for(i = 0; i < 41; i++)
        {
            j = rand() % 41;
            temp = num_array[j];
            num_array[j] = num_array[i];
            num_array[i] = temp;
        }

        //final process is to print the first 25 elements as you have said you need 25.
        for(i = 0; i < 25; i++)
        {
            printf("%d ", num_array[i]);
        }

        printf("\n\n");

        //or you can also store the first 25 elements on separate array variable.
        for(i = 0; i < 25; i++)
        {
            i_need_25[i] = num_array[i];
            printf("%d ", i_need_25[i]);
        }

        return 0;
    }

Upvotes: 0

Tanuj Yadav
Tanuj Yadav

Reputation: 1299

You have some syntax errors
for loop should be like this

for(n=0; n<25; n++)
 {
  temp[n] = get_value(n);  //in your prog u have written temp[t], t isnt defined
           printf("value at cell %d is %d \n", n, temp[n]);
 }   // you also missed the braces

Upvotes: 1

suecarmol
suecarmol

Reputation: 467

You are assigning value to temp[t], but you haven't declared t. In any case, it should be temp[n].

The scope of the variable t is only in your get_value function.

For more information about scopes

Upvotes: 0

Related Questions