I was trying to create a program that calculates the sum of rows and columns in 2D array and the elements should be obtained from the user, when I tried to run the program the sum of the rows was a very large number even if the inputs were zeros
so please if you detected what's wrong inform me.
#include <iostream>
usingnamespace std;
int main(){
int r;
int c;
cout << "Enter the number of rows ";
cin >> r;
cout << "Enter the number of cols ";
cin >> c;
int a[r][c];
int sumr[r];
int sumc[c];
for (int i=0 ; i<r ; i++){
for (int j=0 ; j<c ; j++){
cin >> a[i][j];
sumr[i] +=a[i][j];
sumc[j] +=a[i][j];
}
cout << "The sum of row " << i+1 << " is " << sumr[i] << endl;
}
int y;
cout << "Enter the col no. to calc it's sum ";
cin >> y;
if (y>c || y<0){
cout << "Invalid col input ";
return 0;
}
cout << "The sum of col "<< y << " is " << sumc[y] << endl;
}
int **arr = newint*[rows];
for (int i = 0; i < rows; i++)
arr[i] = newint[columns];
//Do whatever
for (int i = 0; i < rows; i++)
delete[] arr[i];
delete[] arr;
You should also initialize your array to hold all zeros after you create it (or as you create it)
1 2 3 4
int **arr = newint*[rows];
for (int i = 0; i < rows; i++)
arr[i] = newint*[columns] {0};
...
And you might want to check your row/col summing algorithm.
#include <iostream>
usingnamespace std;
int main()
{
int rows = 0;
int cols = 0;
cout << "Enter the number of rows ";
cin >> rows;
rows++; // <-- make 1 extra row for totals
cout << "Enter the number of cols ";
cin >> cols;
cols++; // <-- ditto column
int** a = newint*[rows];
for(int i = 0; i < rows; ++i)
a[i] = newint[cols];
for (int i = 0 ; i < rows - 1 ; i++)
{
for (int j = 0 ; j < cols - 1 ; j++)
{
cin >> a[i][j];
a[i][cols - 1] += a[i][j]; // <-- total as you go
a[rows - 1][j] += a[i][j]; // <-- ditto
}
}
int y;
cout << "Enter the col no. to calc it's sum ";
cin >> y;
if ( y > cols || y < 0)
{
cout << "Invalid col input ";
return 0;
}
cout << "The sum of col "<< y << " is " << a[rows - 1][y - 1] << endl;
//delete cleanup required
}
Another way but a little quick, dirty and sloppy, is to make a big array say a[100][100], initialize it to zero, and input the values of r and c to use as limiters/locators only. Easy to do and no need to use new/delete.