M
M
Matef2020-11-12 16:26:01
C++ / C#
Matef, 2020-11-12 16:26:01

How to add elements of a 2D array c++?

In general, given a two-dimensional array, for example:

Input:

32,23
25,12


Conclusion:
Первая строка = 55
Вторая строка = 37


How can they be folded?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2020-11-12
@Matef

In C++ you can

#include <iostream>
#include <algorithm>
#include <string>
#include <numeric>
#include <vector>
#include <iterator>

using namespace std;

//Придумай сам алгоритм число в строку или нагугли
string lineNumberToString(int ln)
{
  return to_string(ln) + " сторка ";
}

int main()
{
  auto nums2dArray = vector<vector<int>>{{32,23}, {25,12}};

  transform(begin(nums2dArray), 
            end(nums2dArray), 
            ostream_iterator<string>(cout, "\n"), 
            [](auto row){
              static int lineNumber = 1;
              return lineNumberToString(lineNumber++) + 
                     to_string(accumulate(begin(row), end(row), 0));
  });
}

W
Wataru, 2020-11-12
@wataru

You need a loop through the lines. Inside, calculate the sum of each line and output.
To find the sum of one line you need one more loop: Get a variable equal to 0 before cikorm. In a loop, add the elements of a string to it. Then take it out.
So you will have 2 nested loops.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question