Multidimensional Arrays in C

Learn how to declare and use multidimensional arrays in C programming. Step-by-step examples on Debian 12 using Vim.

Multidimensional Arrays in C: A Beginner's Guide

Multidimensional arrays store data in more than one dimension. The most common type is a two-dimensional array, like a table with rows and columns.

Declaring a Two-Dimensional Array

Syntax:

type arrayName[rows][columns];

Example:

int matrix[3][3];

Initializing Multidimensional Arrays

You can initialize at declaration:

int matrix[3][3] = 
    1, 2, 3,
    4, 5, 6,
    7, 8, 9
;

Accessing Elements

Use two indices: row and column starting from zero.

printf(\\"%d\\", matrix[1][2]);  // Prints 6

Example Program

#include 

int main() 
    int matrix[3][3] = 
        1, 2, 3,
        4, 5, 6,
        7, 8, 9
    ;

    for (int i = 0; i < 3; i++) 
        for (int j = 0; j < 3; j++) 
            printf(\\"Element at [%d][%d]: %d\\\
\\", i, j, matrix[i][j]);
        
    
    return 0;

Compiling and Running

gcc multidim.c -o multidim
./multidim

Expected Output

Element at [0][0]: 1
Element at [0][1]: 2
Element at [0][2]: 3
Element at [1][0]: 4
Element at [1][1]: 5
Element at [1][2]: 6
Element at [2][0]: 7
Element at [2][1]: 8
Element at [2][2]: 9

Summary

Multidimensional arrays allow you to work with data structured in rows and columns, useful in matrices, grids, and more.

Subscribe to Our YouTube for More

Download as PDF

https://blog.arashtad.com/updates/multidimensional-arrays-in-c/?feed_id=13102&_unique_id=68945af1280b0

Comments

Popular posts from this blog

Why Smart Contracts Are Revolutionary? (Smart Contracts Use Cases)

How to make a skybox in Three.js: A perfect guide

A Complete Roadmap for Becoming a Back-end Developer