I have a scenario in which I have to take n inputs from the user and store it in an array and I also need to find the sum of all elements in the array. Since it is in codeforces, I wanted to know about the most optimal way of doing it.
Generally, I/O operations are considered notorious for using a lot of CPU time. Does it have a performance hit in large-scale input (i.e. 1000s of inputs) if I frequently switch over from I/O and processing than just taking plain input first and then processing the sum later?
I am using the C++ language and online judge (Codeforces).
First approach: I loop through n times and read n inputs from the input stream and place them one by one in the array. And later sum them all.
int n, sum=0;
cin >> n;
int *myarray = new int[n];
for(int i=0; i<n; i++)
{
cin >> myarray[i];
}
for(int i=0; i<n; i++)
{
sum += myarray[i];
}
Second approach: I loop through n times in and read n inputs. Each time, I place it in an array and sum the number I just took as input as well.
int n, sum=0;
cin >> n;
int *myarray = new int[n];
for(int i=0; i<n; i++)
{
cin >> myarray[i];
sum += myarray[i];
}