M
M
MrFlatman2017-10-12 21:41:08
C++ / C#
MrFlatman, 2017-10-12 21:41:08

Counting the sum of elements in each column of a two-dimensional array?

Hello everyone, there is a task to create a dynamic two-dimensional array, calculate the sum, and calculate the sum of the elements in each column. I did almost everything, but I got confused how to correctly calculate the sum of the elements in a column, tell me, please, how to fix it?

#include <iostream>
#include <ctime>
using namespace std;

int main()
{
  srand(time(0));
  int N;
  int M;
  int sum = 0;
  int j = 0;
  cout << "Vvedite N - kolvo strock" << endl;
  cin >> N; 
  cout << "Vvedite M - kolvo stolb" << endl;
  cin >> M;

  int **arr = new int*[N];

  for (int i = 0; i < N; i++)
    arr[i] = new int[M];

  for (int i = 0; i < N; i++)
  {
    for (int j = 0; j < M; j++)
    {
      arr[i][j] = 1 + rand() % 100;
      cout  << arr[i][j]<<"\t";
      sum =sum+ arr[i][j];
      
    }
    cout <<"\n"<< endl;
    cout << "In " << j + 1 << " col sum is " << sum << endl;
  }
  
    cout << sum << "\n";
  for (int i = 0; i < N; i++)
    delete[] arr[i];

  delete[] arr;

  system("pause");
  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2017-10-13
@MrFlatman

Set sum to zero at the beginning of the first loop.
PS: Damn, who teaches you how to make such two-dimensional arrays? Yesterday there was the same question on C++ and the same with similar two-dimensional arrays. Read about address arithmetic or learn how to use standard stl containers so as not to fence this perversion.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question