How to assign values to an array using rand in C language?

To assign values to an array using the rand function, follow these steps:

  1. Firstly, it is necessary to include the header file, which contains the declaration of the rand function.
  2. Create an array and specify its size and type.
  3. Generate random numbers using the rand function, and then assign each random number to every element in the array.

Here is a sample code:

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

int main() {
   int size = 10;  // 数组大小
   int arr[size];  // 创建数组
   
   srand(time(NULL));  // 使用当前时间作为随机数种子
   
   // 使用rand函数给数组赋值
   for (int i = 0; i < size; i++) {
      arr[i] = rand();
   }
   
   // 打印数组的值
   for (int i = 0; i < size; i++) {
      printf("%d ", arr[i]);
   }
   
   return 0;
}

In the code above, the array size is set to 10, so we create an integer array, arr, containing 10 elements. Then, we use the srand function to set the random number seed, which can be obtained by using the time function to get the current time as the seed. Next, we use a for loop to iterate through the array and assign each element a random value using the rand function. Finally, we use another for loop to print the values of the array.

It is important to note that the rand function generates pseudo-random numbers, resulting in the same random number sequence every time the program runs. To avoid this issue, we typically use the srand function to pass different seed values to the rand function, ensuring a different random number sequence each time the program is run. In the example above, we use the current time as the seed value.

bannerAds