Course contentsShow
← C
Lesson 413 of 1,2196. Arrays and StringsFree lesson

Summing rows and columns individually

Summing rows and columns individually

What you'll learn: How to use nested loops to isolate and calculate the totals of specific rows and columns within a 2D array.

Thinking in Grids

When you work with a 2D array, like a 3x3 grid, it is helpful to think of it as a spreadsheet. Sometimes, you don't just want the "Grand Total" of every number in the table. Instead, you might need the sum of each horizontal row (like a monthly budget total) or each vertical column (like the total spent on a specific category).

To achieve this, we use nested for loops, but with a specific trick: we must reset our "running total" variable at the right moment.

Summing Rows (Horizontal)

To sum rows, we lock onto one row and iterate through all its columns. Before we start moving through the columns, we set a rowSum variable to zero. Once the inner loop finishes that row, we print the result and move to the next row, resetting the sum to zero again.

int grid[3][3] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

// Summing Rows
for (int i = 0; i < 3; i++) {
    int rowSum = 0; // Reset for every new row
    for (int j = 0; j < 3; j++) {
        rowSum += grid[i][j];
    }
    printf("Sum of row %d: %d\n", i, rowSum);
}

Summing Columns (Vertical)

Summing columns is essentially the same logic, but we "flip" our perspective. We lock onto one column index and iterate through the rows. Imagine scanning a barcode vertically; you stay in the same horizontal position while moving your eyes from top to bottom.

// Summing Columns
for (int j = 0; j < 3; j++) {
    int colSum = 0; // Reset for every new column
    for (int i = 0; i < 3; i++) {
        colSum += grid[i][j];
    }
    printf("Sum of column %d: %d\n", j, colSum);
}

The "Reset" Rule

The most common mistake is declaring your sum variable outside the first loop. If you do that, the totals will keep accumulating across the entire grid instead of giving you individual results. By declaring rowSum or colSum inside the outer loop, you ensure each line starts with a clean slate.

Key takeaway

To sum individuals rows or columns, place your "sum" variable inside the outer loop so it resets before each new line is calculated.