In: Computer Science
Write a C++ program that randomly generates N integer numbers (such that N is entered by the user) and then stores them to a text file (myNumbers.txt) sorted in increasing (non-decreasing) order.
Again, please notice that the size of the data (N) is known during the run time, not the compile-time (needs to be entered by the user after running the program).
Code:
#include<iostream>
#include<stdlib.h>
#include<time.h>
#include<fstream>
using namespace std;
int main(){
srand(time(0));
int n;
cout<<"Enter N:";
cin>>n;
int i,j;
int a[n];
for(i=0;i<n;i++){
a[i]=rand();
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(a[i]<a[j]){
int tem;
tem=a[i];
a[i]=a[j];
a[j]=tem;
}
}
}
ofstream f;
cout<<"\n successfully stored numbers to a text
file in sorted order.";
f.open("output.txt"); //name of output file
for(i=0;i<n;i++){
f<<a[i]<<endl;
}
}
Output:
text file: