50.2k views
2 votes
Type two statements that use rand() to print 2 random integers between (and including) 100 and 149. End with a newline. Ex:

101
133

Sample program:

#include
#include // Enables use of rand()
#include // Enables use of time()

int main(void) {
int seedVal = 0;

seedVal = 4;
srand(seedVal);



return 0;
}

User Iamgopal
by
3.0k points

2 Answers

6 votes

Final answer:

To generate two random integers between 100 and 149 using the rand() function in C, you use the formula (rand() % 50) + 100 twice after seeding the random number generator. For reproducible results, use a fixed seed value, but for unique random numbers on each program run, use srand(time(NULL)).

Step-by-step explanation:

To print two random integers between 100 and 149, you can use the rand() function in C. The rand() function returns a pseudo-random integer, which needs to be scaled and shifted to fit the desired range. To ensure that the numbers fall between 100 and 149 inclusive, you would use the following formula inside your main function: (rand() % 50) + 100. This formula works by generating a random number between 0 and 49 and then adding 100 to shift it into the range 100-149. To print two separate random numbers, you would call this code twice, remembering to seed the random number generator with a value for reproducibility.

An example program snippet would look like:

printf("%d\\", (rand() % 50) + 100);
printf("%d\\", (rand() % 50) + 100);

Note that if you want non-reproducible random numbers each time the program is run, you should seed the generator with a value that changes, such as the current time using srand(time(NULL)) instead of a fixed seed value. However, the example given has a fixed seed for predictable outputs.

User Shaba
by
3.6k points
5 votes

Final answer:

To print two random integers between 100 and 149 inclusive, use the rand() function with a modulus of 50 and add 100 to the result, making sure to seed the random number generator with the current time using srand(time(NULL)).

Step-by-step explanation:

To generate two random integers between 100 and 149, inclusive, using the rand() function in C, you can do the following:

#include <stdio.h>
#include <stdlib.h> // Enables use of rand()
#include <time.h> // Enables use of time()

int main(void) {
srand(time(NULL)); // Seed the random number generator with the current time

int randNum1 = 100 + rand() % 50; // Generate first random number
int randNum2 = 100 + rand() % 50; // Generate second random number

printf("%d\\", randNum1); // Print the first random number followed by a newline
printf("%d\\", randNum2); // Print the second random number followed by a newline

return 0;
}

This complete code in C seeds the random number generator with the current time to ensure that the numbers are different every time the program runs. The rand() % 50 generates a number between 0 and 49, and adding 100 shifts the range to between 100 and 149.

User TWLATL
by
3.4k points