You are required to generate a file of 100 random numbers. The range of the numb
ID: 3819581 • Letter: Y
Question
You are required to generate a file of 100 random numbers. The range of the numbers is from 0 to an integer value read from the console. The output file’s format should match the following assuming range entered is 1000;
Random numbers from 0 to 1000:
Index Number Random Number
1 679
2 101
3 3
4 715
5 293
..
Write a program to receive the input filename from the console, and the value for the maximum number.
In C++, the function rand is used to generate trivial (non-crypotographic-quality) random numbers; it returns pseudo-random integer numbers between 0 and RAND_MAX ( a constant in <cstdlib>). The function prototype for rand is:
int rand();
To use rand to generate a pseudo-random number between 0 and a given maximum myInputValue, use
myRandomNumber = rand() % (myInputValue +1);
(strictly speaking in C++ you should also initialize the random-number generator using the function “srand ()”- ignore this step).
Explanation / Answer
#include<iostream>
#include<conio.h>
#include <stdio.h>
#include<stdlib.h>
#include <time.h>
#include <fstream>
using namespace std;
int main()
{
ofstream outputFl;
char randomNmFileName[256];
int myInputValue =0, myRandomNumber=0;
srand (time(NULL));
cout << "Enter File Name: " << endl;
cin >> randomNmFileName ;
outputFl.open(randomNmFileName);
cout << "Enter the maximum value of random number: "<<endl;
cin >> myInputValue;
if (outputFl.is_open())
{
outputFl << "Index Number Random Number" << endl;
for (int i = 1; i <= 100; i++) {
myRandomNumber = rand() % (myInputValue +1);
outputFl << i << " " << myRandomNumber << " ";
}
outputFl.close();
}
else {
cout << "Problem in opening the specified file.";
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.