Sum of rows and columns

closed account (zwpL3TCk)
Hi! How can i print the sum of every rows and every column?

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
29
30
31
32
33
34
#include <iostream>
#include <conio.h>
using namespace std;

const int ROWS=3;
const int COLS=5;
int i, j;

int main() {
    int arr[ROWS][COLS];   
    for(i = 0; i < 3; i++) 
    {
        for (j = 0; j < 5; j++)
        {
                cout<<"Enter the value of row and " << i+1;
                cout<<" column " << j+1 <<": ";
                cin>>arr[i][j];
                }
        }
        system ("cls");
        cout << "\n\t\t\t\tThe numbers are" << endl;
        for (i=0; i<3; i++) 
        {
            cout << endl;
            for (j=0; j<5; j++) 
            {
            cout << "\t" << arr[i][j] << "\t"; 
            }
                     
    }
    getch();
    return 0;
}

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <conio.h>
using namespace std;

const int ROWS=3;
const int COLS=5;

int main() {
    int arr[ROWS][COLS];
    for(int i = 0; i < ROWS; i++)
    {
        for (int j = 0; j < COLS; j++)
        {
            cout << endl << "Enter the value of row and " << i+1;
            cout << " column " << j+1 <<": ";
            cin >> arr[i][j];
        }
    }
    //system ("cls");
    cout << "\n\t\tThe numbers are" << endl;
    cout << "\n\t\t===============" << endl;

    int sum;

    // print rows and sums of rows
    for (int i=0; i<ROWS; i++)
    {
        cout << endl;
        sum = 0;

        for (int j=0; j<COLS; j++)
        {
            cout << arr[i][j] << "\t";
            sum = sum + arr[i][j];
        }
        cout << sum << endl;
    }

    // print rows and sums of rows
    cout << endl;
    cout << endl;
    for (int j=0; j<COLS; j++)
    {
        sum = 0;
        for (int i=0; i<ROWS; i++)
        {
            //cout << arr[i][j] << "\t";
            sum = sum + arr[i][j];
        }
        cout << sum << "\t";
    }
    cout << endl;
    getch();
    return 0;
}

Last edited on
closed account (zwpL3TCk)
Thank you! i just remove the const int ROWS=3; const int COLS=5; and make the int arr[3][5].
mrgxsy wrote:
Thank you! i just remove the const int ROWS=3; const int COLS=5; and make the int arr[3][5].


On the contrary, keep them it's good practice to do that, but I would have them inside main(), rather than being global, same for variables i & j. Further, make use of these variables in the code. For example:

27
28
29
30
31
32
33
34
35
36
37
38
39
    for (row =0; i<ROWS; i++)
    {
        cout << endl;
        sum = 0; // could have a better name for this RowSum, say

        for (col =0; j<COLS; j++)
        {
            cout << arr[row][col] << "\t";
            sum +=  arr[row][col];
        }
        cout << sum << endl;
    }
    }


The idea is to not have "magic" numbers throughout the code.

I dislike using i and j for variable names - they look too similar, and this can cause problems. I would use row & col instead.

Hope this helps a bit :+)
closed account (zwpL3TCk)
Then i need to replace from 3 to ROWS and 5 to COLS inside main?
Yes, and declare them inside main as well, so they are not globals.


1
2
3
4
5
6
7
8
9
int main() {

const int ROWS=3;
const int COLS=5;

int row = 0; // always initialise variables to something
int col = 0;

}


Edit:

You could make them unsigned int as well - no need to have any negative values for those.
Last edited on
Yes keep the const definitions as they are for that means you can change the size of the array by changing the const values rather than having to go through all the code to change all the 5's and 3's to some other values.

As for i,j they are commonly used in loops and recognized as such. I have no problem with reading them but I would define them in the loop not as global variables. (see above I have modified the code). One advantage with using row and col as the labels is they make it clear how they are being used. Using meaningful labels is a form of self commenting.

Last edited on
closed account (zwpL3TCk)
Thank you @TheIdeasMan!

What is the difference of int row =0; int col =0; and int row; int col;


@CodeWriter

I just declare them inside main.

EDIT:

How can i use search algorithm to find the highest and lowest integer in 2-Dimensional array?
Last edited on
Q. How can i use search algorithm to find the highest and lowest integer in 2-Dimensional array?

Set max = 0
Set min = 99999 // some big value
Then loop through the values as you have done to print them and/or compute their sums.
for each item compare it with max and min.
if arr[row][col] > max then max = arr[row][col]
if arr(row][col] < min then min = arr[row][col]

By the way you might like to use setw() instead of /t
http://www.cplusplus.com/reference/iomanip/setw/
Last edited on
closed account (zwpL3TCk)
Hi, It works now.

Btw, Why do i need to set the min to some big value? When i set the min to 0 it always print the lowest number to 0 but when i set the min to some big value like 99999 it prints the lower value i put in the array.

It also works if i initialized the min to the value of the first element of array.

min = [0][0];

Can you explain why to set to some big value?
Last edited on
What is the difference of int row =0; int col =0; and int row; int col;


The former sets a value for the variables, the latter might have garbage values. There are situations where variables are assigned a default zero value, but it is better to always initialise variables to some value. This is often a very big source of errors - especially for beginners. Note that zero is not the best value in all situations, sometimes it is better to set some value that is obviously wrong, as in:

unsigned short int DayOfWeek = 200;

because zero is a valid value for this variable.

It is also good practice to declare and define 1 variable per line of code. It allows comments, and avoids problems with modifiers only applying to the first variable:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int MyVarA = 1; // min value -10, max value +10
int MyVarB = 2; // min value -20, max value +10
int MyVarC = 3; // min value -10, max value +20
int MyVarD = 4; // min value -30, max value +30

                                     // p in front of a var name is a convention that means it is a pointer
int* pMyVarA, pMyVarB;  // only pMyVarA is a pointer to int, pMyVarB is an int with a confusing name
                                     // neither are initialised

                                 // on a 64 bit system
pMyVarB = &MyVarB; // error, the address(64bit) of MyVarB is too big to fit into an int (32 bit)

int *pMyVarC = &MyVarC;  // No confusion here
int *pMyVarD = &MyVarD;  // and both initialised 


How can i use search algorithm to find the highest and lowest integer in 2-Dimensional array?


Have Max & Min variables declared before the loops, assign the first value of the array to both the Min and Max variables. Then cycle through the array, just as before. If the number you are looking at is less than Min, assign it to Min, if larger than Max, assign it to Max.

@CodeWriter

I saw a situation years ago, where there was 2 pages of code full of i and j - it was a large matrix, with a small matrix being used to do operations to the larger one. There was a problem, so I suggested renaming the i's and j's to Row & Col. The problem became immediately apparent - there was a (Row, Row) that should have been (Row, Col)
closed account (zwpL3TCk)
Thanks for the reply @TheIdeasMan!

Can you explain why i need to set the Min and Max to the value of the first array?

The search for highest and lowest integers works fine now.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    int MaxValue = arr[0][0];
    int MinValue = arr[0][0];
    
    cout << endl;
    for (row=0; row<ROWS; row++)
    {
        for(col=0; col<COLS; col++)
        {
                   if (arr[row][col] > MaxValue) 
                   MaxValue = arr[row][col];     
                   
                   if (arr[row][col] < MinValue) 
                   MinValue = arr[row][col];    
                   }
                   }
                   cout << "The highest integer is: " << MaxValue << endl;
                   cout << "The lowest integer is: " << MinValue;


What kind of search algorithm is 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <conio.h>
using namespace std;

const int ROWS=3;
const int COLS=5;

int main() {
    int arr[ROWS][COLS];
    for(int row = 0; row < ROWS; row++)
    {
        for (int col = 0; col < COLS; col++)
        {
            cout << endl << "Enter the value of row and " << row+1;
            cout << " column " << col+1 <<": ";
            cin >> arr[row][col];
        }
    }
    //system ("cls");
    cout << "\n\t\tThe numbers are" << endl;
    cout << "\n\t\t===============" << endl;

    int sum;

    // print rows and sums of rows
    for (int row=0; row<ROWS; row++)
    {
        cout << endl;
        sum = 0;

        for (int col=0; col<COLS; col++)
        {
            cout << arr[row][col] << "\t";
            sum = sum + arr[row][col];
        }
        cout << sum << endl;
    }

    // print rows and sums of rows
    cout << endl;
    cout << endl;
    for (int col=0; col<COLS; col++)
    {
        sum = 0;
        for (int row=0; row<ROWS; row++)
        {
            //cout << arr[row][col] << "\t";
            sum = sum + arr[row][col];
        }
        cout << sum << "\t";
    }

    // find minimum and maximum value in array
    int max = 0;
    int min = 9999;  // must be larger than any minimum value

    for (int row=0; row<ROWS; row++)
    {
        for (int col=0; col<COLS; col++)
        {
            if  (arr[row][col]>max)
                max = arr[row][col];
            if (arr[row][col]<min)
                min = arr[row][col];
        }
    }
    cout << "max value = " << max << endl;
    cout << "min value = " << min << endl;

    getch();
    return 0;
}
Last edited on
Can you explain why i need to set the Min and Max to the value of the first array?


If you set Min to some other value, then there might be a value that is less than that, so that value won't be set to Min. You could set Min to be the largest value that it's type can hold, but it's easier to just set it to the first value in the array.

What kind of search algorithm is this?


Not sure that it has any particular name.


Make sure you have your braces lining up: the one on line 15 should be in the same column as the brace on line 6, likewise with the brace on line 14 should line up with the one on line 8.

Also, it is very good practice to use braces - even where there is 1 line of code, as in lines 10 and 13. This will save you one day when you add some more code after line 10.

You should be able to set your IDE to do these things automatically. Even if you import some code that is badly formatted, your IDE can indent it properly for you. If you set your tabs to be 4 spaces, instead of an actual tab char - then it will display better on this site. Tabs are converted to 8 spaces here. Lines 10 & 13 should be indented more than the if statements. This stuff is important - it aids understanding & can help prevent errors.

While we are at it, don't have using namespace std; - there is plenty written on the web about why it is bad - Google it. Instead prefix each std thing with std:: as in std::cout , std::cin , std::endl , std::string , std::vector etc.
It might seem to be a pain, but you can see that all the expert coders on this site do it.

Also, conio.h is not standard C++, so don't use it. You can std::cin a dummy variable if you want to keep your window open at the end. If you want to move the cursor around and do colours, have a look at ncurses.
Topic archived. No new replies allowed.