I rewritten your code, removed global variables, changed formatting for easier reading, rename some variables to more explain for what they are and add function prototypes. Hope this will help you a little.
There are still lot of places which should be changed, but i want to keep as close to your original code as possible.
If you have any questions feel free to ask.
#include <iostream>
#include <fstream>
using namespace std;
//functions prototypes (these will be moved to header file if you wanna use this code from another file)
void to_read(int &len, int * array, const char * name); //added name parameter to avoid glogal variables
void to_print(int len, int * array, const char * name);
int to_sum(int len, int * array); //added parameters to avoid global variables
int main()
{
int lenght = 20; //moved to here, try to avoid global variables
int array_1[lenght]; //preconfigured size depend on variable
const char D[] = "Data.txt";
const char R[] = "Rezults.txt";
to_read(lenght, array_1, D);
//to_sum(lenght, array_1); //not needed here, not storing/processing result
to_print(lenght, array_1, R);
return 0;
}
void to_read(int &len, int * array, const char *name)
{
int lenght;
ifstream fd(name); //you should check if opening was successful
fd >> lenght; //you should check if reading was successful
if (lenght < len) len = lenght; //to prevent overflow of array, read max 20
for (int i=0; i<len; i++){
fd >> array[i];
}
fd.close();
}
int to_sum(int len, int * array)
{
int sum=0;
for (int i=0; i<len; i++){
sum += array[i]; //changed sum = sum + value; to sum += value; its same but this is more often used
}
return sum;
}
void to_print(int len, int * array, const char *name)
{
int sum = to_sum(len, array);
ofstream fr(name);
fr << len << endl;
for (int i=0; i<len; i++){
fr << array[i] << " ";
}
fr << endl;
fr << sum << endl;
fr.close();
}
4
solved Get the SUM of array (C++)