Writing a .txt file
I generate in a for loop:
1- An array made of random numbers
2- Add the elements of the array and store the
result in a number S
3- finally write in a .txt file the
number j(number of time that the for-loop has been executed)
and the number S for each j like this:
j=0 S=x
j=1 S=x
j=2 S=x
Steps 1 and 2 work fine.
Does someone has an idea how I can write
the js and the number S in a .txt file?
here is how my code till now looks like:
#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;
// The function RandomNum creates random numbers
// in the range between small and big
void RandomNum(double small,double big ,int p, double *array)
{
double range=(big-small)+1;
for (int i=0; i<p; i++){
array[i]=small+int(range*rand()/(RAND_MAX + 1.0));
}
}
//the function AdditionArr Add the elements of an
//array and store the result in a number S
double AdditionArr (double *Arr,int k)
{
int i;
double Sum=0.0;
for (i=0; i<k; i++){
Sum+=Arr[i];
}
return Sum;
}
int main()
{
srand((unsigned)time(0));
int p=3;
int j;
double S,array[3];
for(j=0;j<3;j++){
RandomNum(-1.5,1.5 ,p,&array[0]);
S=AdditionArr (&array[0],p);
for (int k=0; k<p; k++){
cout << "array"<<"["<< k << "]" <<" = " << array[k] << endl;
}
cout << "S=" << S << endl;
cout << endl;
}
return 0;
}