C Programming - Beginner to Brilliance / Arrays and Strings

Types of Arrays

Arrays in C can be categorized based on how many dimensions they have and how they’re used.

1️⃣ One-Dimensional Array (1D Array)

A 1D array is like a row of boxes where each box stores a value.

🎯 Analogy: A row of lockers 📦📦📦

✅ Declaration:

int marks[5];

This creates 5 integer slots: marks[0], marks[1], ..., marks[4]

✅ Initialization:

int marks[5] = {85, 90, 75, 60, 95};

This stores values in a linear fashion in memory.

✅ Accessing Elements:

printf("%d", marks[2]); // Prints 75

Indexing always starts from 0

✅ Use Case:

Used when you need to store:

  • List of scores 🏅

  • Product prices 💰

  • Temperatures over a week 🌡️


🔹 2️⃣ Two-Dimensional Array (2D Array)

A 2D array is like a grid or a matrix — rows and columns.

🎯 Analogy: A chessboard or spreadsheet

✅ Declaration:

int matrix[3][2];

This creates:

  • 3 rows

  • 2 columns in each row

So it can hold 3 × 2 = 6 elements

✅ Initialization:

int matrix[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};

matrix[0][0]

matrix[0][1]

matrix[0][2]

1

2

3

matrix[1][0]

matrix[1][1]

matrix[1][2]

4

5

6

✅ Accessing Elements:

printf("%d", matrix[1][2]); // Output: 6

✅ Use Case:

Used for:

  • Storing data in rows and columns

  • Matrix operations

  • Tables or scoreboards


🔹 3️⃣ Three-Dimensional Array (3D Array)

A 3D array is like a cube made of multiple matrices.

🎯 Analogy: A Rubik’s Cube, or a set of spreadsheets stacked on top of each other 📊📊📊

✅ Declaration:

int cube[2][3][4];
  • 2 blocks (pages)

  • Each block has 3 rows

  • Each row has 4 columns

    → Total: 2 × 3 × 4 = 24 elements

✅ Initialization:

int cube[1][2][2] = {
    {
        {1, 2},
        {3, 4}
    }
};

Visualize as:

  • 1 layer → 2 rows → 2 columns each

Accessing:

printf("%d", cube[0][1][1]); // Output: 4

✅ Use Case:

Used in:

  • Scientific calculations

  • 3D graphics

  • Complex data tables (like time-series of 2D data)


🆚 Comparison Table

Type

Dimensions

Syntax

Visual

1D Array

1

int arr[5]

🧱🧱🧱🧱🧱

2D Array

2

int arr[2][3]

📊 Grid

3D Array

3

int arr[2][2][2]

🧊 Cube


🔥 Bonus: Higher-Dimensional Arrays

C technically supports more than 3 dimensions (like 4D, 5D), but they are:

  • Difficult to manage

  • Rarely used in practice

  • Mainly useful in scientific or simulation-heavy applications


⚠️ Key Things to Remember

  • You must declare all dimensions' sizes, except for the first during initialization.

int arr[][3] = {
    {1, 2, 3},
    {4, 5, 6}
};  // ✅ OK

But this is not allowed:

int arr[][] = {{1,2}, {3,4}};  // ❌ Error

🧠 Memory Layout Insight

C stores multi-dimensional arrays in row-major order:

For int arr[2][3] = {{1,2,3}, {4,5,6}};

Memory layout is:

Index:  [0][0] [0][1] [0][2] [1][0] [1][1] [1][2]
Value:     1      2      3      4      5      6