In: Computer Science
There is a pair of functions in stdlib.h (make sure to include it) that are used for generating pseudo-random numbers. These are "srand" and "rand". Examples are on pages 686 and 687. E.g., function "srand(3)" provides the seed value of 3 to the srand function. (3 is just a number, and probably isn't even a good number for this purpose, but that's a discussion for another time). The reason that we use a seed value is so that we can reproduce the series of random numbers. Thus, we call them pseudo-random numbers. Being able to reproduce them is important to verify and debug code.
Write a C program to generate a set of random numbers for a given seed value (call it lab8_part1.c). Prompt the user for the seed value, or 0 to quit. Then print 5 random values. When you run your program, try a few different seed values, then try one that you've already tried. Verify that you get the same sequence.
CODE -
#include<stdio.h>
#include<stdlib.h>
int main()
{
int seed;
// Taking seed value as input from the user
printf("\nEnter a seed value (0 to quit): ");
scanf("%d", &seed);
// Running the loop until user enters 0 to quit
while(seed != 0)
{
// Passing seed value to the function srand()
srand(seed);
// Printing 5 random values
for(int i=0; i<5; i++)
printf("%d ", rand());
// Taking next seed value as input from the user
printf("\nEnter a seed value (0 to quit): ");
scanf("%d", &seed);
}
return 0;
}
SCREENSHOTS -
CODE -
OUTPUT -
If you have any doubt regarding the solution, then do
comment.
Do upvote.