How to generate a random array in the C language?

In C language, you can use the rand() function to generate random numbers and store them in an array to create a random array. Here are the specific steps:

  1. Include the header file .
  2. Use the srand() function to set the random number seed. You can use the time() function to obtain the current time as the seed to ensure a different random number sequence is generated every time the program is run. For example, srand(time(NULL));.
  3. Define an array and allocate enough memory space. For example: int arr[10];.
  4. Use a for loop to generate random numbers and store them in an array. For instance, for (int i = 0; i < 10; i++) { arr[i] = rand(); }.

The complete example code is shown below:

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

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

    int arr[10];
    for (int i = 0; i < 10; i++) {
        arr[i] = rand();
    }

    printf("随机数组:\n");
    for (int i = 0; i < 10; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}

After running the program, an array containing 10 random numbers will be generated and printed out. Each time the program is run, a different sequence of random numbers will be generated.

bannerAds