Question

Write a C function "RandomNumber" which returns a random number in the range 0 to 51.

Write a C function "RandomNumber" which returns a random number in the range 0 to 51.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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

int RandomNumber();

int main()
{
int num;
num=RandomNumber();
printf("Random number is %d",num);
printf("\n\n");
system("pause");
return 0;
}

int RandomNumber()
{
int num;
num=rand()%51+0;
return num;
}

Add a comment
Answer #2

You can use the rand() function from the stdlib.h library to generate random numbers in C. However, since rand() generates numbers in the range of 0 to RAND_MAX, which may not be exactly 51, you need to perform some adjustments to get the random number within the range of 0 to 51.

Here's a C function RandomNumber() that returns a random number in the range 0 to 51:

cCopy code#include <stdio.h>#include <stdlib.h>#include <time.h>int RandomNumber() {    // Seed the random number generator using the current time
    srand(time(NULL));    
    // Generate a random number in the range 0 to RAND_MAX
    int randomNumber = rand();    
    // Scale the random number to the range 0 to 51
    int scaledNumber = randomNumber % 52;    
    return scaledNumber;
}int main() {    // Test the RandomNumber function
    int randomNum = RandomNumber();    printf("Random number: %d\n", randomNum);    
    return 0;
}

In this implementation, we seed the random number generator using the current time to ensure that we get different random numbers each time the program runs. Then, we use the % operator to calculate the remainder of dividing randomNumber by 52, which ensures the result is in the range of 0 to 51. The function returns the scaled random number.

answered by: Hydra Master
Add a comment
Know the answer?
Add Answer to:
Write a C function "RandomNumber" which returns a random number in the range 0 to 51.
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT