Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ program that generates random integers between 0 and 1000. Few tasks: Genera

ID: 3666723 • Letter: C

Question

C++ program that generates random integers between 0 and 1000.

Few tasks:

Generate a first random number before entering a loop.

Generate more random numbers in a loop until you have generated a total of 500 even integers.

While you are doing this, count how many odd integers you generate.

Furthermore, keep track of the largest integer generated. after generating each integer, display it and display the largest integer you've seen so far. You can simply display each number on a line and the maximum so far beside it, as modeled below.

Sample Runs:(example of what it should look like)

(This run stops after generating 5, not 500, even integers.)

Explanation / Answer

The required program is shown below :

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
   srand((int)time(0));

int rOdd=0,rEven=0,max=0;

int r = rand() % 1000;
max = r;
cout << r << "(max so far: " << max << ")" << endl;
  
if(r%2==0)
rEven++;
else
rOdd++;

while(rEven <= 500) {
       r = rand() % 1000;

if( r > max)
max=r;

if(r%2==0)
rEven++;
else
rOdd++;
      
cout << r << "(max so far: " << max << ")" << endl;

   }

cout << "Generated "<< rOdd <<" odd integers while generating 500 even integers, with an overall maximum of "<< max << "." << endl;


   return 0;
}

The numbers generated by the rand() are not random because it generates the same sequence each time the code executed. So, if we run the code again, we'll get the same sequence repeated as in the previous run.

To make a different sequence of numbers, we should specify a seed as an argument to a srand() function:

We will get the diffent sequence of numbers by using the srand(), however, the sequence will still be repeated each time the code is executed. To generate a ever changing sequence, we need to feed something other than static integer to the argument of the srand(0function.

The best solution is to seed the rand(0 function using the current time as the argument to srand(), by calling time() function from the standard C++ library, <ctime>. This returns the time as the type of time_t. Then, for portability, we cast as an integer type:

The time() function returns the number of seconds since 00:00 hours, Jan 1, 1970 UTC (i.e., the current unix timestamp). This ensures the number generated by rand() will now seems to be truly random unless it is called again within the same second.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote