In: Computer Science
c++
In this program ask the user what name they prefer for their file, and make a file, the file name should za file.
Get a number from the user and save it into the create file. should be more than 20 number in any order.
print out all 20 numbers in a sorted array by using for loop, last print out its total and average.
At last create a function in which you will call it from main and swap all the numbers in that function, only one function.
/* Below is your required code*/
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int main()
{ string name;
cout<<"Enter file name to be created: ";
cin>>name;
fstream file;
file.open(name,ios::out);
if(!file)
{
cout<<"Error!";
return 0;
}
else{
int x[25];
int n=25;
cout<<"Enter array.";
for(int count = 0; count < n; count ++){
cin>>x[count];
file << x[count] << " " ;
}
int i, j;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if (x[j] > x[j+1])
swap(&x[j], &x[j+1]);
cout<<"Sorted Array!\n";
float total,avg;
for (i = 0; i < n; i++){
total+=x[i];
cout<<x[i]<<" ";
}
cout<<"\n Total = "<<total;
avg=total/n;
cout<<"\n Average = "<<avg;
file.close();
}
return 0;
}