Arrays

Declaring, initializing, and accessing elements of arrays. Working with single and multi-dimensional arrays.


Working with Multi-Dimensional Arrays in C

Introduction

Multi-dimensional arrays are a powerful way to organize and store data in a structured manner in C. They allow you to represent data in multiple dimensions, such as a table (rows and columns) or a cube (height, width, and depth). This document focuses on 2-dimensional arrays (2D arrays), also known as matrices, and provides examples of common operations.

Understanding 2D Arrays

A 2D array is essentially an array of arrays. Each element of the outer array is itself an array. Imagine it as a grid or a table.

Declaration: A 2D array is declared using the following syntax:

data_type array_name[rows][columns];

Where:

  • data_type: The type of data the array will store (e.g., int, float, char).
  • array_name: The name you give to the array.
  • rows: The number of rows in the array.
  • columns: The number of columns in the array.

Example:

int matrix[3][4]; // Declares a 2D array named 'matrix' with 3 rows and 4 columns, storing integers.

Reading Data into a 2D Array

You can populate a 2D array by reading data from user input or from a file. Nested loops are typically used to iterate through each row and column.

#include <stdio.h>

int main() {
  int matrix[3][4];
  int i, j;

  printf("Enter the elements of the 3x4 matrix:\n");

  // Read data into the array
  for (i = 0; i < 3; i++) {
    for (j = 0; j < 4; j++) {
      printf("Element [%d][%d]: ", i, j);
      scanf("%d", &matrix[i][j]);
    }
  }

  // Display the array (to verify input)
  printf("\nThe matrix you entered:\n");
  for (i = 0; i < 3; i++) {
    for (j = 0; j < 4; j++) {
      printf("%d ", matrix[i][j]);
    }
    printf("\n");
  }

  return 0;
} 

Explanation: The code prompts the user to enter each element of the 3x4 matrix. The nested loops iterate through each row (i) and column (j), using scanf to read the integer value and store it in the corresponding element of the matrix.

Performing Matrix Operations

Matrix Addition

To add two matrices, they must have the same dimensions. The corresponding elements of the matrices are added together to produce the result.

#include <stdio.h>

int main() {
  int matrix1[2][3] = {{1, 2, 3}, {4, 5, 6}};
  int matrix2[2][3] = {{7, 8, 9}, {10, 11, 12}};
  int sum[2][3];
  int i, j;

  // Calculate the sum of the matrices
  for (i = 0; i < 2; i++) {
    for (j = 0; j < 3; j++) {
      sum[i][j] = matrix1[i][j] + matrix2[i][j];
    }
  }

  // Display the sum matrix
  printf("The sum of the matrices:\n");
  for (i = 0; i < 2; i++) {
    for (j = 0; j < 3; j++) {
      printf("%d ", sum[i][j]);
    }
    printf("\n");
  }

  return 0;
} 

Explanation: The code initializes two 2x3 matrices, matrix1 and matrix2. The nested loops iterate through each element, adding the corresponding elements of the two matrices and storing the result in the sum matrix.

Matrix Subtraction

Matrix subtraction is similar to addition, requiring the matrices to have the same dimensions. The corresponding elements are subtracted.

#include <stdio.h>

int main() {
  int matrix1[2][3] = {{7, 8, 9}, {10, 11, 12}};
  int matrix2[2][3] = {{1, 2, 3}, {4, 5, 6}};
  int difference[2][3];
  int i, j;

  // Calculate the difference of the matrices
  for (i = 0; i < 2; i++) {
    for (j = 0; j < 3; j++) {
      difference[i][j] = matrix1[i][j] - matrix2[i][j];
    }
  }

  // Display the difference matrix
  printf("The difference of the matrices:\n");
  for (i = 0; i < 2; i++) {
    for (j = 0; j < 3; j++) {
      printf("%d ", difference[i][j]);
    }
    printf("\n");
  }

  return 0;
} 

Explanation: This code mirrors the addition example, but instead subtracts the corresponding elements of matrix2 from matrix1.

Displaying the Array in a Structured Format

To present the 2D array clearly, you can format the output using loops and formatting specifiers.

#include <stdio.h>

int main() {
  int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
  int i, j;

  printf("The matrix:\n");
  for (i = 0; i < 3; i++) {
    for (j = 0; j < 4; j++) {
      printf("%4d", matrix[i][j]); // %4d allocates 4 spaces for each integer
    }
    printf("\n");
  }

  return 0;
} 

Explanation: The %4d format specifier in the printf statement allocates 4 spaces for each integer, ensuring that the numbers are aligned neatly in the output. Adjust the number to suit the expected range of values in your array. The outer loop iterates through rows, and the inner loop iterates through columns, printing each element with the specified formatting. The newline character (\n) after each inner loop ensures that each row is printed on a new line.