4.0k views
2 votes
Write a program that writes 10 random numbers into a file named numbers using loops.

1 Answer

2 votes

Answer:

The program in cpp for the given scenario is shown below.

#include <stdio.h>

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

//object created of file stream

ofstream out;

//file opened for writing

out.open("numbers.txt");

std::cout << "File opened." << std::endl;

//inside for loop, random numbers written to numbers.txt using rand()

for(int n=0; n<10; n++)

{

out<<rand()<<endl;

}

//file closed

out.close();

std::cout << "File closed." << std::endl;

return 0;

}

Step-by-step explanation:

1. An object of the ofstream is created. The ofstream refers to output file stream. This is used to create file for write and append operations.

ofstream out;

2. The file named, numbers.txt, is opened using the open() method with the object of ofstream.

out.open("numbers.txt");

3. The message is displayed to the user that the file is opened.

4. Inside a for loop, which executes 10 times, a random number is generated. This random number is written to the file and a new line inserted.

5. The random number is generated using rand() method. Every number is written on new line.

out<<rand()<<endl;

6. Every execution of the for loop repeats steps 4 and 5.

7. When the loop ends, the file is closed using close() method with the object of ofstream.

out.close();

8. A message is displayed to the user that the file is closed.

9. The header file, fstream, is included to support file operations.

10. The extension of the file can be changed from .txt to any other type of file as per requirement.

11. The program can be tested for writing more numbers to the file.

12. The program can be tested for writing any type of numeric data to the file.

13. The program is written in cpp due to simplicity.

14. In other languages such as java or csharp, the code is written inside classes.

15. In cpp, all the code is written inside main() method.

16. The screenshot of the output messages displayed is attached.

Write a program that writes 10 random numbers into a file named numbers using loops-example-1
User Alphazero
by
7.9k points