What is Processing 2D Arrays in C – Online Embedded C Programming Classes

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Chapter 7 · Arrays

Processing 2D Arrays in C

Master nested loops, row averages, column peaks, transposes and the rule for passing a 2D array to a function. A hands-on free C tutorial for embedded C programming.

Processing 2D arrays in C comes down to one idea: an outer loop walks the rows and an inner loop walks the columns. Once that pattern feels natural, you can compute averages, find peaks, flip a table or refresh a display. This lecture of our free C programming course builds a small multi-room temperature logger to show every technique in action, and ends with the rule that trips up almost every beginner when passing a grid to a function. It is exactly the kind of skill that C programming for embedded systems demands every day.

What You Will Learn

  • How nested loops visit every element of a 2D array
  • Computing per-row results and per-column results
  • Transposing a table into a second array
  • Printing tidy tables with field width in printf
  • Why a function needs the column count in a 2D array parameter

Prerequisites

  • The previous lecture on declaring and addressing two dimensional arrays
  • Passing arrays to functions with a length (earlier in this chapter)
  • Comfort with for loops and printf format specifiers

Processing 2D Arrays in C with Nested Loops

A single loop can walk a list, but a table has two directions, so you need two loops. By convention the outer loop controls the row index and the inner loop controls the column index. For each row, the inner loop sweeps across all columns before the outer loop moves down one row. The body of the inner loop therefore sees every element exactly once, in the same order the elements sit in memory.

for (int r = 0; r < ROWS; r++) {
    for (int c = 0; c < COLS; c++) {
        /* work with table[r][c] */
    }
}
How the nested loops sweep a 3 by 4 table
Outer r = 0→c = 0c = 1c = 2c = 3
Outer r = 1→c = 0c = 1c = 2c = 3
Outer r = 2→c = 0c = 1c = 2c = 3

Choosing the Loop Pattern

GoalLoop shapeExample
Visit every elementRows outside, columns insidePrint or fill the whole table
One result per rowReset accumulator, then inner loop over columnsAverage of each room
One result per columnColumns outside, rows insidePeak at each time slot
Copy into flipped shapeRows outside, columns inside, swap indices on the targetTranspose
Main diagonal onlySingle loop using t[i][i]Trace of a square matrix

Free C Tutorial: Multi-Room Temperature Logger

Imagine three rooms, each with four temperature readings taken at different times of day. The program stores them in a 3 by 4 table, prints the table, calculates each room’s average, finds the highest reading in each time slot, and finally produces a transposed copy so that rows become time slots.

#include <stdio.h>

#define ROOMS 3
#define SLOTS 4

static void print_grid(int t[ROOMS][SLOTS])
{
    for (int r = 0; r < ROOMS; r++) {
        for (int c = 0; c < SLOTS; c++) {
            printf("%4d", t[r][c]);
        }
        printf("\n");
    }
}

static void row_averages(int t[ROOMS][SLOTS])
{
    for (int r = 0; r < ROOMS; r++) {
        int sum = 0;
        for (int c = 0; c < SLOTS; c++) {
            sum += t[r][c];
        }
        printf("room %d average = %.2f\n", r, (double)sum / SLOTS);
    }
}

static void column_peaks(int t[ROOMS][SLOTS])
{
    for (int c = 0; c < SLOTS; c++) {
        int peak = t[0][c];
        for (int r = 1; r < ROOMS; r++) {
            if (t[r][c] > peak) { peak = t[r][c]; }
        }
        printf("slot %d peak = %d\n", c, peak);
    }
}

static void transpose(int src[ROOMS][SLOTS], int dst[SLOTS][ROOMS])
{
    for (int r = 0; r < ROOMS; r++) {
        for (int c = 0; c < SLOTS; c++) {
            dst[c][r] = src[r][c];
        }
    }
}

int main(void)
{
    int temps[ROOMS][SLOTS] = {
        {24, 26, 29, 27},
        {22, 23, 25, 24},
        {30, 33, 35, 31}
    };
    int flipped[SLOTS][ROOMS];

    printf("readings:\n");
    print_grid(temps);
    row_averages(temps);
    column_peaks(temps);

    transpose(temps, flipped);
    printf("transposed (%d x %d):\n", SLOTS, ROOMS);
    for (int r = 0; r < SLOTS; r++) {
        for (int c = 0; c < ROOMS; c++) {
            printf("%4d", flipped[r][c]);
        }
        printf("\n");
    }
    return 0;
}
gcc -std=c17 -Wall -Wextra -Wpedantic -o lab_grid lab_grid.c
./lab_grid

Expected output:

readings:
  24  26  29  27
  22  23  25  24
  30  33  35  31
room 0 average = 26.50
room 1 average = 23.50
room 2 average = 32.25
slot 0 peak = 30
slot 1 peak = 33
slot 2 peak = 35
slot 3 peak = 31
transposed (4 x 3):
  24  22  30
  26  23  33
  29  25  35
  27  24  31

How Each Function Works

  • print_grid uses %4d, which pads every number to four characters so columns line up. The bare printf("\n") after the inner loop starts the next row on a new line.
  • row_averages resets sum to zero for every row, adds across the columns, then divides. Casting to double before dividing keeps the fraction: 106 divided by 4 is 26.5, not 26.
  • column_peaks swaps the loop order: columns outside, rows inside. It starts the peak at the first row’s value and compares the rest.
  • transpose copies src[r][c] into dst[c][r]. The 3 by 4 source becomes a 4 by 3 result, so the destination array has its dimensions reversed.
Transpose index mapping
src[0][1] = 26copies to →dst[1][0] = 26
src[2][3] = 31copies to →dst[3][2] = 31
Ruledst[c][r] = src[r][c]

Passing 2D Arrays to Functions in C

Look back at the function headers: every one of them spells out the number of columns. That is not decoration. As you saw in the layout lecture, the compiler locates element [r][c] with the formula r * COLS + c. Without knowing COLS it cannot compute where a row begins. The row count, however, never enters the formula, which is why the first dimension may be left empty.

Parameter declarationValid?Reason
int t[ROWS][COLS]YesBoth sizes stated (ROWS is ignored)
int t[][COLS]YesColumn count is the only size the compiler needs
int (*t)[COLS]YesSame thing written as a pointer to a row
int t[][]NoCompiler cannot compute row addresses
int *t[COLS]DifferentThat is an array of pointers, not a grid

Leaving out the column size produces a clear error:

error: array type has incomplete element type 'int[]'

A note on const and 2D parameters

In C17 and earlier, passing an int[3][4] to a parameter declared const int t[][4] triggers a pedantic warning in GCC, because the qualifier applies to the inner array type. The C23 standard fixes this. For beginners, the simplest approach is to leave const off 2D parameters in older language modes and to document read-only intent in a comment.

Because the function receives the address of the caller’s table, as you learned earlier in this chapter, the transpose function fills the caller’s flipped array directly. No copying of the grid takes place on the way in.

Filling a Table from Input

On a desktop, you can fill a table from the keyboard by placing scanf("%d", &table[r][c]) inside the nested loops. On a microcontroller you would instead store an ADC conversion, a received byte or a scanned key state at table[r][c]. The loop structure is identical; only the data source changes.

Real-World Uses in Embedded C Programming

  • Keypad scanning: drive each row, read the columns, and record the result in a table.
  • Thermal sensor arrays: compute row averages and hot-spot positions across an image.
  • LED matrix animation: transpose or shift a pattern before sending it to the driver.
  • Data logging: store readings per channel (rows) and per time slot (columns), then summarise.

Common Mistakes and Troubleshooting

MistakeSymptomFix
Not resetting the accumulator per rowRow averages keep growingSet sum = 0 inside the outer loop
Integer division for averages26.5 prints as 26Cast one operand to double
Transpose target with the same shape as the sourceCompile error or overflow on non-square tablesDeclare dst[COLS][ROWS]
Using the row count for the inner loopSkips or overruns columnsInner loop runs to the column count
Omitting the column size in a parameterError: incomplete element typeWrite int t[][COLS]

Best Practices, Performance and Security

Best Practices

  • Use #define or enum constants for dimensions so every function header and loop matches.
  • Keep one job per function: print, average, find peak, transpose.
  • Name loop variables r and c (or row and col) for instant readability.

Performance Considerations

Row-by-row traversal matches the memory order and is the fastest option. Column-first loops like column_peaks are fine for small tables but can be slower on large images processed by a cached CPU. Transposing large buffers also costs a second buffer of the same size in RAM, so plan for it on small devices.

Security Considerations

Never let a received value select a row or column without checking it against the table size. A single unchecked index in a lookup table can read private data or overwrite adjacent variables.

Summary and Key Takeaways

Remember these points

  • Rows on the outside, columns on the inside visits every element in memory order.
  • Swap the loop order to compute per-column results.
  • A transpose copies src[r][c] into dst[c][r] with swapped dimensions.
  • A 2D array parameter must state the column count; the row count may be omitted.

With nested loops and the column-size rule, you can process any table that your hardware produces. These patterns reappear in image processing, matrix maths and multi-channel data logging. The next lecture of this free embedded C course shows the many ways to initialize a 2D array, including partial braces, zero fill and designated initializers.

Frequently Asked Questions

How do I loop through a 2D array in C?

Use two nested loops: the outer loop runs over rows and the inner loop runs over columns, accessing table[r][c] in the body.

Why must a 2D array parameter include the column count?

The compiler needs the column count to compute where each row starts in memory. The row count is not needed for that calculation.

How do I calculate the average of each row?

Reset a sum variable at the start of each row, add every column, then divide by the column count, casting to double to keep decimals.

How does a matrix transpose work in C?

Copy each element src[r][c] to dst[c][r], where the destination array has its row and column counts swapped.

Is it faster to loop by rows or by columns?

Looping by rows is faster for C arrays because elements in a row are adjacent in memory, which suits caches and sequential access.

Can I read a 2D array with scanf?

Yes, place scanf("%d", &table[r][c]) inside the nested loops. On embedded targets, replace it with your sensor or peripheral read.

Continue the Free C Programming Course

Change the table values, add a fourth room, and predict every result before running. Then learn every way to initialize a 2D array in the next free C tutorial lecture.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →