Loading...
arrays

Arrays in C

1. Definition

An array is a collection of elements of the same data type stored in contiguous memory locations. Arrays allow you to store and manage multiple values under a single variable name.


2. Syntax

data_type array_name[size];

Explanation:

  • data_type: The type of elements in the array (e.g., int, float, char).
  • array_name: The name of the array.
  • size: The number of elements the array can hold (must be a constant value).

Example:

int numbers[5];

3. Types of Arrays

  1. One-Dimensional Arrays

    • A linear collection of elements.

    • Example:

      int numbers[5] = {1, 2, 3, 4, 5};
      
  2. Two-Dimensional Arrays

    • A table or matrix-like structure with rows and columns.

    • Example:

      int matrix[3][3] = {
          {1, 2, 3},
          {4, 5, 6},
          {7, 8, 9}
      };
      
  3. Multi-Dimensional Arrays

    • Arrays with more than two dimensions.

    • Example:

      int tensor[2][3][4];
      

4. Accessing Array Elements

Array elements are accessed using their index, which starts from 0.

Example:

int numbers[5] = {10, 20, 30, 40, 50};
printf("%d", numbers[2]); // Outputs: 30

5. Array Initialization

  1. At Declaration:

    int numbers[3] = {10, 20, 30};
    
  2. Partially Initialized:

    • Remaining elements are set to 0.
    int numbers[5] = {10, 20}; // Remaining elements: 0, 0, 0
    
  3. Uninitialized:

    • Contains garbage values.
    int numbers[5];
    

6. Iterating Through Arrays

Use loops to process all elements in an array.

Example:

int numbers[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
    printf("%d ", numbers[i]);
}

7. 2D Array Example

Input and Output of a 2D Array:

#include <stdio.h>

int main() {
    int matrix[2][2];

    // Input
    printf("Enter 4 elements:\n");
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }

    // Output
    printf("Matrix:\n");
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    return 0;
}

8. Advantages of Arrays

  • Efficient storage and retrieval of multiple elements.
  • Easy to iterate and manipulate using loops.
  • Useful for data structures like matrices, stacks, and queues.

9. Limitations of Arrays

  • Fixed size: Once defined, the size of an array cannot be changed.
  • Stores only one type of data.
  • Insertion and deletion operations are not efficient.