7

Write a C program to generate random numbers

 2 years ago
source link: https://www.geeksforgeeks.org/videos/write-a-c-program-to-generate-random-numbers/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Write a C program to generate random numbers

Write a C program to generate random numbers
Hey guys. Welcome to Geeks. For geeks today, we
  • 09/09/2022

In this video, we will write a C program to generate random numbers. A random number is a number that is generated using a large set of numbers. We will take the n input and we will output n random numbers through a loop.

Example :
Input:  3

Output:
45666
45679
46778

Here we use 2 different methods for generating random numbers.
1. Using rand()
2. Using rand() with srand()

1. Using the rand() function: 
In this method, we will use the rand() function inside a for loop to generate random numbers. This rand() function returns random integer values.

A rand() function is an inbuilt function in C STL, which is defined in the header file. It is used to generate random numbers. The random number is generated by using an algorithm that gives a series of non-related numbers whenever this function is called.

It gives an output of a random number in the range [0, RAND_MAX]. RAND_MAX value will be at least 32767 depending on the system. But if you run the program again, The same set of numbers will be obtained.

2. Using rand() with srand() function:
In this method, we will use the rand() function inside a for loop but we will also use the srand() function outside the loop to generate random numbers.

A srand() function is an inbuilt function in C STL, which is defined in the header file. This function used to initialize random number generators. The srand() function sets the starting point for producing a series of pseudo-random integers. If srand() is not called, the rand() seed is set as if srand(1) were called at the program start. 

Here, If we use the srand function before rand(), We will have different outputs whenever we run the program unless approaches 1. When we run the program again, we will get a different output.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK