Each function in your program should have a header comment as well. Describe its
ID: 3778994 • Letter: E
Question
Each function in your program should have a header comment as well. Describe its purpose, the parameters and the return value (if any). Use a format similar to:
// Function name:
// Purpose:
// Parameters:
// Return value:
(1) Write a c++ program that asks the user for a positive integer no greater than 15. The program should then store a square on a file using the character ‘X’. The number entered by the user will be the length of each side of the square. For example, if the user enters 5, the program store the following pattern in a file named “pattern.dat”:
XXXXX
XXXXX
XXXXX
XXXXX
XXXXX
The program should then read the stored pattern from the file you just created and display the pattern on the screen.
Explanation / Answer
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
int size;// var to store the size
cout<<"Enter a positive number: ";
cin>> size;//reading size from the user
if(size>=15 || size<=0){
cout<<"Number should be between 0 to 15";// showing message to the user when the number is between 1 to 5
}else{
ofstream myfile;
myfile.open ("pattern.txt");// creates a file pattern.dat
for(int i=0;i<size;i++){
for(int j=0;j<size;j++){
myfile << "X";// wrinting x for size time to generate the pattern
}
myfile << " ";
}
myfile.close();//clsoing the ofstream
//reading from the file
string line;
ifstream myfile1 ("pattern.txt");//opening the file pattern.txt
if (myfile1.is_open())
{
while ( getline (myfile1,line) )
{
cout << line << ' ';//reads a single line and print it in console
}
myfile1.close();
}
else
cout << "Unable to open file";
}
return 0;
}
---------output----------
Enter a positive number: 15
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
---------output----------
---------output----------
Enter a positive number: 2
Number should be greater than 15
---------output----------
pattern.dat file conatins
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
//Note: Feel free to ask any doubts. God bless you!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.