📦 Arrays in C Language

One-Dimensional, Multi-Dimensional & Strings

🔹 What is an Array?

An array is a collection of elements of the same data type stored in contiguous memory locations and accessed using a single name.

Article Algo

✅ Why Use Arrays?

  • Stores multiple values using one variable name
  • Easy data handling
  • Efficient memory access
  • Useful for sorting, searching, and data processing

📌 Array Declaration

data_type array_name[size];
Example:
int marks[5];

📌 Array Initialization

int marks[5] = {10, 20, 30, 40, 50};

📌 Accessing Array Elements

marks[0] = 10; // first element
marks[4] = 50; // last element

📘 Example Program (One-Dimensional Array)

#include <stdio.h>

int main() {
  int a[5] = {1, 2, 3, 4, 5};
  int i;

  for(i = 0; i < 5; i++) {
    printf("%d ", a[i]);
  }
  return 0;
}

📂 Types of Arrays in C

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

A one-dimensional array stores a list of elements in a single row.

int a[5] = {10, 20, 30, 40, 50};

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

A two-dimensional array stores data in rows and columns (matrix form).

Syntax:
data_type array_name[row][column];
Example:
#include <stdio.h>

int main() {
  int a[2][2] = {{1, 2}, {3, 4}};
  int i, j;

  for(i = 0; i < 2; i++) {
    for(j = 0; j < 2; j++) {
      printf("%d ", a[i][j]);
    }
    printf("\n");
  }
  return 0;
}

3️⃣ Multi-Dimensional Array

Arrays with more than two dimensions.

int a[2][2][2];

4️⃣ Character Array (String)

A character array stores a sequence of characters (string).

#include <stdio.h>

int main() {
  char name[] = "C Language";
  printf("%s", name);
  return 0;
}

📌 Passing Array to Function

#include <stdio.h>

void display(int a[], int n) {
  int i;
  for(i = 0; i < n; i++)
    printf("%d ", a[i]);
}

int main() {
  int arr[3] = {1, 2, 3};
  display(arr, 3);
  return 0;
}

✅ Advantages of Arrays

  • Simple and easy to use
  • Fast access using index
  • Reduces number of variables

❌ Disadvantages of Arrays

  • Fixed size
  • Cannot store different data types
  • Insertion and deletion are difficult

📚 FAQs on Arrays in C

Q1. What is an array?

An array is a collection of similar data types stored in contiguous memory locations.

Q2. What is the index of the first array element?

Index starts from 0.

Q3. Can array size be changed at runtime?

No, arrays have a fixed size (use dynamic memory for flexibility).

Q4. What is the difference between array and variable?

A variable stores a single value, while an array stores multiple values.

Q5. What happens if array index exceeds size?

It leads to undefined behavior.

🔑 Key Points to Remember

  • Arrays store multiple values
  • Index starts from 0
  • Size must be specified
  • Same data type elements only