Check if Matrix is Magic Square Dry Run in C

Check if Matrix is Magic Square is an interactive C dry run visualizer from the Two D 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.

Check if Matrix is Magic Square Program Code

#include <stdio.h>
int main() {
    int matrix[3][3] = {{2, 7, 6}, {9, 5, 1}, {4, 3, 8}}, i, j;
    int sum, target, isMagic = 1;
    
    // Calculate target sum from first row
    target = matrix[0][0] + matrix[0][1] + matrix[0][2];
    
    // Check rows
    for(i = 1; i < 3; i++) {
        sum = matrix[i][0] + matrix[i][1] + matrix[i][2];
        if(sum != target) { isMagic = 0; break; }
    }
    
    // Check columns
    for(j = 0; j < 3; j++) {
        sum = matrix[0][j] + matrix[1][j] + matrix[2][j];
        if(sum != target) { isMagic = 0; break; }
    }
    
    // Check main diagonal
    sum = matrix[0][0] + matrix[1][1] + matrix[2][2];
    if(sum != target) isMagic = 0;
    
    // Check secondary diagonal
    sum = matrix[0][2] + matrix[1][1] + matrix[2][0];
    if(sum != target) isMagic = 0;
    
    if(isMagic)
        printf("Matrix is a Magic Square!\n");
    else
        printf("Matrix is NOT a Magic Square\n");
    return 0;
}

View the complete Two D programs page.

Program Console Check if Matrix is Magic Square Topic: C Vignaankosh.com
Execution Panel
Step 0/0
Console is empty.