ARRAYS IN C
Array Concept in C
Understanding Arrays with Examples, Memory Representation, and Operations
📌 What is an Array?
An array is a collection of similar data types stored in contiguous memory locations. It allows storing multiple values under a single name, and each value is accessed using an index.
int a[5]; // array of 5 integers
⭐ Features of Arrays
- Stores multiple values of the same data type.
- Memory is allocated contiguously.
- Access using an index (starts from 0).
- Provides random access to elements.
- Fixed size (decided at compile time).
📝 Declaration & Initialization
int marks[5];
int marks[5] = {10, 20, 30, 40, 50};
int marks[] = {10, 20, 30, 40, 50};
➡️ Accessing Elements
printf("%d", marks[0]); // 10
printf("%d", marks[4]); // 50
📍 One-Dimensional Array
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
for(int i=0; i<5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
📍 Two-Dimensional Array
#include <stdio.h>
int main() {
int mat[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
for(int i=0; i<2; i++) {
for(int j=0; j<3; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
return 0;
}
💾 Memory Representation
Suppose base address = 1000 and int = 4 bytes:
| Index | Value | Address |
|---|---|---|
| arr[0] | 10 | 1000 |
| arr[1] | 20 | 1004 |
| arr[2] | 30 | 1008 |
| arr[3] | 40 | 1012 |
| arr[4] | 50 | 1016 |
⚡ Common Operations
- Traversal – visiting each element.
- Insertion – adding an element.
- Deletion – removing an element.
- Searching – Linear / Binary search.
- Sorting – Bubble, Selection, Insertion, Quick, Merge.
✅ Summary
Array = Collection of same type elements in contiguous memory.
Indexed from 0.
Can be 1D, 2D, Multi-Dimensional.
Fixed size, but efficient for storing and accessing data.
Comments
Post a Comment