Arrays - Sum of each lines

Hey guys!

I'd like to know how to write out the sum of each lines' values.
So what I mean, is that if I have N lines and 7 columns with values, with the "N" line number in the first line.

3
0 1 2 3 4 5 6
0 0 0 0 0 0 1
1 1 1 1 1 1 1

I'd like the output to be
21 1 7
My code so far (not working tho):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  #include <iostream>

using namespace std;

int main()
{
    int N; 
    int C[1000];
    cin >> N;

    for (int i=0; i<N; i++)
        for (int j=0; j<7; j++)
            cin >> C[j];
    int sum=0;
    for (int i=0; i<N; i++)
            sum=sum+C[i];

    for (int i=0; i<N; i++)
        cout << sum << " ";
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

int main()
{
	vector<vector<int>> nums 
	{
		{0, 1, 2, 3, 4, 5, 6,},
		{0, 0, 0, 0, 0, 0, 1},
		{1, 1, 1, 1, 1, 1, 1}
	};

	for(auto &vec : nums)
	{
		cout << accumulate(vec.cbegin(), vec.cend(),0) << " ";
	}
	cout << endl;

	return 0;
}
I'd really like a method for static arrays, as we're only allowed to use this in the very beginning of our C++ course, but thanks for the answer!
array,I see, then

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <numeric>
using namespace std;

int main()
{
	const int columns = 7;
	const int rows = 3;

	int nums[rows][columns]
	{
		{0, 1, 2, 3, 4, 5, 6,},
		{0, 0, 0, 0, 0, 0, 1},
		{1, 1, 1, 1, 1, 1, 1}
	};

	for(auto &row : nums)
	{
		auto begin = &row[0];
		auto end = &row[columns];
		cout << accumulate(begin, end,0) << " ";
	}
	cout << endl;

	return 0;
}


And in case you're not even allowed to use the numeric header and the auto keyword, then you can roll with this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

int main()
{
	const int columns = 7;
	const int rows = 3;

	int nums[rows][columns]
	{
		{0, 1, 2, 3, 4, 5, 6,},
		{0, 0, 0, 0, 0, 0, 1},
		{1, 1, 1, 1, 1, 1, 1}
	};

	for (int(&row)[columns] : nums)
	{
		int sum = 0;
		for (int &n : row) { sum += n; }
		cout << sum << " ";
	}
	cout << endl;

	return 0;
}
Last edited on
This is really good, and yeah, I'm not allowed to use those, but here's the thing:

There are 10 test files with different inputs, so only the column is constant. The task description is that in the past N weeks, we measured the amount of rain fallen in each day. Since there are 7 days in a week, that's fine to be constant, but the amount of weeks are based on the user's input. That's why I used the cin >> N.

And the output has to be the sum of the fallen rain in each days for every different weeks (as it is in the description).

The values of the seven days each are different as well (the C[i])

Tahnk you for the constant help!
Last edited on
There are 10 test files with different inputs
the amount of weeks are based on the user's input

Not sure I understand. Is the input coming from a file or from the user?

As to the larger problem of how to handle an unknown amount of data.
In this case, you may not need any array at all. You can just accumulate and output each total as you go along.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

int main()
{
    ifstream fin("data.txt");

    int count = 0;
    fin >> count;
    
    for (int week=0; week<count; ++week)
    {
        int weektotal = 0;
        for (int day = 0; day < 7; ++day)
        {
            int n;
            fin >> n;
            weektotal += n;
        }
        cout << weektotal  << ' ';
    }    

}

Input file data.txt:
3
0 1 2 3 4 5 6
0 0 0 0 0 0 1
1 1 1 1 1 1 1

Output:
21 1 7

well, if you want to do it the "hard way" with a 1D array, then

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;

int main()
{
	const int size{ 1000 };
	const int days{ 7 };
	int inputs{}, sum{}, offset{};
	int measurements[size]{ 0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 };

	cin >> inputs;

	for (size_t week = 0; week < inputs; week++)
	{
		sum = 0;
		offset = week * days;
		for (size_t week_day = 0; week_day < days; week_day++)
		{
			sum += measurements[offset + week_day];
		}
		cout << sum << " ";
	}
	cout << endl;

	return 0;
}


Edit: ops, didn't refreshed, didn't noticed someone already replied :P
Last edited on
it's like there's a user, who tries your program 10 times, but it's actually an online test system that tests your code with different pre-written values every single times, and therefore the output and input will change all the time. You can't see the test files, all you know is that the test files are correct (no negative values, no letters if you have to use numbers, etc.)

The one I mentioned in the description is just 1 random example, the program should work for all test files.

I'll try and translate the entire task in english, so you guys will get what I exactly talk about:

"In the previous N weeks, we measured the amount of rain fallen every single days in millimetres (not important).

Write a program, that counts the amount of rain fallen for every single week".

INPUT:
The standard input's first line containts the amount of weeks (2 <= N <= 10 - This one just shows that the online testing system will attempt to try your code with 10 different values). The next N lines, you can find each week's rain amount for every single day (0 <= C[i][j] <= 1000 - This shows that there should be a C[i][j] array, and the maximum amount of rain for each days is 1000).

OUTPUT:
The standard output is only 1 line. It' shows the sum of rain fallen every day for each week. (So if we measured the rainfaill for 3 weeks, and we measured each days, there should be 3 numbers, separated with a space.)

INPUT:
3 <amount of weeks>
0 1 2 3 4 5 6 <amount of fallen rain every day in the first week>
0 0 0 0 0 0 1 <amount of fallen rain every day in the second week>
1 1 1 1 1 1 1 <amount of fallen rain every day in the third week>

OUTPUT:
21 1 7 <amount of fallen rain in the first week (21), second week (1), third week (7)
Last edited on
it's like there's a user, who tries your program 10 times, but it's actually an online test system that tests your code with different pre-written values every single times, and therefore the output and input will change all the time. You can't see the test files, all you know is that the test files are correct (no negative values, no letters if you have to use numbers, etc.)


Then the code I suggested should work, it just needs to be simplified.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;

int main()
{
    int count = 0;
    cin >> count;
    
    for (int week=0; week<count; ++week)
    {
        int weektotal = 0;
        for (int day = 0; day < 7; ++day)
        {
            int n;
            cin >> n;
            weektotal += n;
        }
        cout << weektotal  << ' ';
    }    
}
Yes, this is good, but I need to show the output only after the entire array is filled with the numbers, not after each lines.
hyperpara in this page there are already more than enough examples for you to study and understand how they work, thus getting the answer to your question.
If you don't do that excercise and just wait for someone to write for you the code that just works for this specific case, then the next time you will face a similar but slightly different problem, then you would be at the exact same point to have to ask someone else.

My suggestion is to study our examples and deduce the solution you need (friendly suggestion) ;)
Above, you have it solved with 1D array, 2D arrays, for loop and for range loops...trust me, all the answers are already there.

Well, here's another suggestion: try to store the sums in a second array, then print that.
Last edited on
Yes, this is good, but I need to show the output only after the entire array is filled with the numbers, not after each lines.

That in itself is not a major problem. If the input comes from an automated system, all that will appear in the output will be the three numbers "21 1 7 ".

Have you tried using the automated testing system with that code to see how it responds - perhaps that could cost you some marks, I've no idea.


On the other hand if an actual human user was to use the program then there world be additional output, there would be prompt messages, such as "Please enter the number of weeks" and the user input would appear interspersed with the output. In that case, you could use a simple 1D array int total[1000]; so instead of outputting the total as it is calculated, instead store it in the array. Then afterwards, output the contents of the total array.

(Personally I might use a stringstream instead of an array, to defer the printing of the output until later).


The description of the task seem to state that you must use a 2D array, which though unnecessary might be something you have to do to satisfy the teacher?

Last edited on
I have 5 more exercises related to this task, all I want to understand is this sum thing, so I can figure out the related stuffs to this. :)
I'm still trying to understand what it is that your teacher requires.

Solving the problem doesn't require any arrays.

For the purposes of formatting the output, you might use a 1D array or a stringstream. But which approach is needed depends on what your teacher requires you to do.
Here's a version using a stringstream:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <sstream>

using namespace std;

int main()
{
    int count = 0;
    cout << "Number of weeks? ";
    cin >> count;
    
    std::ostringstream output;
    
    for (int week=0; week<count; ++week)
    {
        int weektotal = 0;
        for (int day = 0; day < 7; ++day)
        {
            cout << "Rainfall for week " << (week+1) << "  day " << (day+1) << " ? ";
            int n;
            cin >> n;
            weektotal += n;
        }
        output << weektotal  << ' ';
    }    
    
    cout << output.str() << '\n';
}


Here, if you are not allowed to use a stringstream, where I put
 
    output << weektotal  << ' ';
you might replace that with
 
    total[week] = weektotal;

and then have an additional loop at the end to output all the totals.
There are 4 more tasks for this. (NO NEED TO SOLVE!, just putting in here to figure out why arrays are necessary).

The second one is the choose the week where the most rain fell.
The third one is to select the weeks where the rainfall increased over the days during the week
The forth one is to select the N/2 terms where the rain fall was on the least days
The fifth one is the longest period where in every week the rainfaill wasn't higher than 10 mm.

The original input is
6
5 10 15 20 25 30 35
0 2 0 0 0 0 0
0 0 0 1 0 3 0
0 1 2 3 4 5 6
5 1 0 0 2 1 0
0 0 0 0 0 0 0

The original output is
140 2 4 21 9 0
1
2 1 4
2
2 3

But I chose not to select the original inputs and outputs, as I wanted to solve these tasks on my own, but I didn't really have any idea how to work with N amount of lines.
Last edited on
all I want to understand is this sum thing

1. First, you need a variable into which you do accumulate the sum.
2. Initially, the value of the sum must be 0.
3. For each value that has to be added sum, add the value to the sum.
4. You do now have the sum of the values.

Note that the principle of computing a sum of values does not care where the data comes from nor where the result will go.

In your case the sum has to be computed for 7 values. You call the group of 7 values a "line" and thus "compute sum of a line". Your input, however has multiple lines and therefore you must repeat the "compute sum of a line" for each line.


If you do want to store, rather than directly show, each sum, then you do need an array for the sums. You could use the same strategy as in your original program and preallocate statically a "sufficiently large" array, or you could use the first value of the input to allocate dynamically during runtime an array of exact size. However, "how to store data" is a different question than "how to sum".
but I didn't really have any idea how to work with N amount of lines.


That's the thing, you kind of need to worry of only ONE line.
Because as in my previous example :

1
2
3
4
5
6
cin >> inputs;

	for (size_t week = 0; week < inputs; week++)
	{
		//...DO STUFF...BUILD SUM...STORE THE RESOULT IN AN ARRAY...
	}


The inputs is already dictating how many times the loop will fire. If inputs is 1, then you have one line, if input is 33, then the loop will fire 33 times. You only need to worry to get the job done once :)
Last edited on
Thank you. I think I understand the need for arrays now.

What I think is a usual approach at this stage of learning, is to define a fixed-size array which is considered large enough for any possible inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    const int MAXWEEKS = 52;
    
    int rainfall[MAXWEEKS][7];
    
    
    int weeks = 0;
    cout << "Number of weeks? ";
    cin >> weeks;
    if (weeks > MAXWEEKS)
    {
        cout << "Error - input too big" << weeks << '\n';
        return 1;
    }
    
    
    for (int w=0; w<weeks; ++w)
    {
        for (int day = 0; day < 7; ++day)
        {
            cout << "Rainfall for week " << (w+1) << "  day " << (day+1) << " ? ";
            cin >> rainfall[w][day];
        }
    }  


The above code fills the array with the values input by the user.

There is no accumulation of totals or output of results. I'd do that as a separate loop afterwards - once you have the data in the array, things become fairly easy (relatively speaking).
Thank you for the help. The original question (even if I wasn't really clear about it) was about how to make the output, the input part was fine (I actually did it 3 different ways by the time I was trying to do it).

The messed-up for loop was my problem. I managed to print out N (line number) values, but either all of them were 0, or it was 1 single value with the total sum of the numbers, or some random value.
Topic archived. No new replies allowed.