Sum of elements in 2D array Dry Run in C

Sum of elements in 2D array is an interactive C dry run visualizer from the Pointersarrays programs section. Study the source code, then use the execution controls to follow each step, variable update, highlighted line, and console output.

This page provides a browser-based dry run with source-code highlighting, auto-scroll, voice narration controls, and execution output for learning the program step by step.

Sum of elements in 2D array Program Code

#include <stdio.h>
int main() {
    int i, j;
    int matrix[3][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };
    int rows = 3, cols = 4;
    int sum1 = 0, sum2 = 0, sum3 = 0;
    
    // Method 1: Using row pointer
    int (*rowPtr)[4] = matrix;
    for(i = 0; i < rows; i++) {
        for(j = 0; j < cols; j++) {
            sum1 += rowPtr[i][j];
        }
    }
    printf("Sum (row pointer): %d\n", sum1);
    
    // Method 2: Using single pointer
    int *ptr = &matrix[0][0];
    for(i = 0; i < rows * cols; i++) {
        sum2 += ptr[i];
    }
    printf("Sum (single pointer): %d\n", sum2);
    
    // Method 3: Using double dereference
    for(i = 0; i < rows; i++) {
        for(j = 0; j < cols; j++) {
            sum3 += *(*(matrix + i) + j);
        }
    }
    printf("Sum (double deref): %d\n", sum3);
    
    return 0;
}

View the complete Pointersarrays programs page.

Program Console Sum of elements in 2D array Topic: C Vignaankosh.com
Execution Panel
Step 0/0
Console is empty.