Totaling a Grid’s Rows and Columns

Data in a matrix is entertaining and all that, but the point is usually to manipulate that data. The most basic form of manipulation I can conjure is to tally the rows and columns. Sounds like fun, but it took me a few attempts to get the code correct.

I’m certain an elegant way exists to obtain the sum of rows and columns in a grid. Rather than attempt such a solution, I chose brute force. In fact, I combined the output statements for the grid with the expressions to total the rows. The columns I handle in a separate nested loop.

To keep things from getting too obnoxious, I use two dimensional array notation as covered in last week’s Lesson. Nested loops help with the processing. A new int variable total is used and reused to obtain the totals.

2023_03_04-Lesson.c

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define SIZE 3

int main()
{
    int x,y,total;
    int grid[SIZE][SIZE];

    /* seed the randomizer */
    srand( (unsigned)time(NULL) );

    /* populate the grid */
    for( x=0; x<SIZE; x++ )
        for( y=0; y<SIZE; y++ )
            grid[x][y] = rand()%10 + 1;

    /* output the grid and row totals */
    for( x=0; x<SIZE; x++ )
    {
        total = 0;
        for( y=0; y<SIZE; y++ )
        {
            total += grid[x][y];
            printf(" %2d ",grid[x][y]);
        }
        printf("%d\n",total);
    }
    /* output column totals */
    for( x=0; x<SIZE; x++ )
    {
        total = 0;
        for( y=0; y<SIZE; y++ )
            total += grid[y][x];
        printf(" %2d ",total);
    }
    putchar('\n');

    return(0);
}

Stolen from last week’s code, array grid[][] is initialized and populated. Starting at Line 20, the grid’s values are output and the row totals calculated.

Variable total is initialized at Line 23. It accumulates the row cell values as the matrix is output left-to-right: total += grid[x][y]; The sum is output after each row.

Calculating column totals requires another nested loop of a similar construction, starting at Line 32 . One mistake a lot of programmers may make is to use absolute offsets. But remember that the grid’s dimensions are set with constant SIZE. If you use absolute values: grid[x][0], grid[x][1], grid[x][2], the code breaks when the value of SIZE is adjusted.

Also note in the second nested loop how the values manipulated are grid[y][x], with variables x and y swapped. Sure it could be written grid[x][y], but the point is that the inner loop sets the row values, not columns.

Here’s a sample run:

  6   8   6 20
  8   5  10 23
  9   3   2 14
 23  16  18

I did attempt to create a pointer version of this code. It’s similar to what’s shown here, but it’s boring. So,I didn’t include it. One issue I did encounter (and reminded you of above) is to use the SIZE constant to set the grid offsets when tallying the rows and columns. By doing so, you can adjust the matrix size and not have the code get stupid on you.

For example, here is the same code presented in this Lesson, but with the SIZE constant set to five:

 10   5   9   6   2 32
  2  10   6   1   8 27
  2   7   6   7   7 29
 10  10   1   7  10 38
  3   5  10   1   8 27
 27  37  32  22  35 

Next week, I frustrate myself further by presenting code that adds two matrixes to generate a third.

4 thoughts on “Totaling a Grid’s Rows and Columns

  1. It would be useful to write a function which takes a multidimensional array and returns a 1D array of the specified row and column. This would abstract away the fiddly stuff and allow you to concentrate on totalling or whatever you need to do.

    The downside is that it would duplicate memory use. There might be a way of getting and incrementing a pointer to the required row or column to get round that, but I can’t think of one right now.

  2. I mulled over a few ways to tally the rows. As you mentioned, Chris, many of them involve allocating even more memory.

  3. I’ve just had another idea. Two in one month. Ouch.

    How about a function that takes a 2D array, row or column indexes and a function pointer, and runs the function on the specified row or column? You could then throw any function at it, sum, mean, min, max etc. I haven’t thought it through but it might be doable.

  4. That makes sense! A function that given an array’s dimensions would return the row or column values as a pointer. Hmmm…..

Leave a Reply