C 2D Arrays (Two-Dimensional) 🎯

beginner
6 min

C 2D Arrays (Two-Dimensional) 🎯

Welcome to our deep dive into C 2D Arrays! In this lesson, we'll explore this powerful data structure that's essential for handling multi-dimensional data. Let's start with the basics and gradually move towards advanced examples. 📝

Understanding 2D Arrays 💡

A 2D array, also known as a matrix, is an array of arrays. It consists of elements arranged in rows and columns, much like a table. Each element is accessed using two indices: the first for the row and the second for the column.

Declaring a 2D Array 📝

To declare a 2D array in C, we first specify its number of rows and columns. Here's the general syntax:

c
dataType arrayName[rows][columns];

Let's create a simple 3x3 2D array of integers:

c
#include <stdio.h> int main() { int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Accessing elements printf("%d\n", matrix[0][0]); // Output: 1 printf("%d\n", matrix[1][2]); // Output: 6 return 0; }

Initializing a 2D Array 💡

Initializing a 2D array when you declare it is called compound literals. Here's an example:

c
#include <stdio.h> int main() { int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Accessing elements printf("%d\n", matrix[0][0]); // Output: 1 printf("%d\n", matrix[1][2]); // Output: 6 return 0; }

Manipulating 2D Arrays 📝

You can perform various operations on 2D arrays, such as iterating through them, finding minimum or maximum values, and more. Here's an example of finding the minimum value in a 2D array:

c
#include <stdio.h> void findMin(int matrix[3][3]) { int min = matrix[0][0]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (matrix[i][j] < min) { min = matrix[i][j]; } } } printf("Minimum value: %d\n", min); } int main() { int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; findMin(matrix); return 0; }

Quiz 📝

Quick Quiz
Question 1 of 1

What is a 2D array in C?

Quick Quiz
Question 1 of 1

What is the general syntax for declaring a 2D array in C?