CSE NotesCSE Notes
Simplifying Complexity

It seems like you’re referring to arrays with different dimensions. Let’s break down what you might mean by “Array: 1-D, 2-D”:

1-D Array (One-Dimensional Array)

A 1-D array in programming is a list of elements arranged in a linear sequence. Each element can be accessed using an index.

Example in C:

#include <stdio.h>

int main() {
    // Declare a 1-D array of integers with 5 elements
    int arr[5] = {1, 2, 3, 4, 5};

    // Accessing elements of the 1-D array
    for (int i = 0; i < 5; i++) {
        printf("Element at index %d: %d\n", i, arr[i]);
    }

    return 0;
}

Explanation:

  • int arr[5] creates a 1-D array with 5 elements.
  • The array elements can be accessed using indices arr[0] to arr[4].
  • The program prints each element of the array.

2-D Array (Two-Dimensional Array)

A 2-D array is essentially an array of arrays. It’s often used to represent tables or matrices, where each element is accessed using two indices: one for the row and one for the column.

Example in C:

#include <stdio.h>

int main() {
    // Declare a 2-D array (matrix) with 3 rows and 4 columns
    int arr[3][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };

    // Accessing elements of the 2-D array
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            printf("Element at arr[%d][%d]: %d\n", i, j, arr[i][j]);
        }
    }

    return 0;
}

Explanation:

  • int arr[3][4] creates a 2-D array with 3 rows and 4 columns.
  • The array can be visualized as a matrix:
    1  2  3  4
    5  6  7  8
    9 10 11 12
    
  • The elements can be accessed using two indices: arr[i][j] where i represents the row and j represents the column.

Comparison Between 1-D and 2-D Arrays:

  • 1-D Array: A simple list of elements.
    • Accessed with a single index: arr[i].
  • 2-D Array: A table (array of arrays).
    • Accessed with two indices: arr[i][j].

Conclusion:

  • A 1-D array is a single line of elements, whereas a 2-D array can be thought of as a grid with rows and columns.
  • In C, both arrays are stored in contiguous memory locations, but the 2-D array is essentially a matrix, and each element can be accessed using two indices: one for the row and one for the column.

If you were referring to something different or need more specific examples, feel free to clarify!