lets Understand basic of Array
An array is a variable that can store multiple values of the same data type under one name.
Simple definition:
An array is a collection of elements of the same data type stored in contiguous memory locations.
Why Do We Need Arrays?
Without Array (problem)
int m1, m2, m3, m4, m5;Problems:
- Too many variables
- Hard to manage
- No easy processing
With Array (solution)
int marks[5];Advantages:
- Single name
- Easy to process using loops
- Clean and readable code
Array Visual Representation (Important)
Think of an array as boxes in a row:
| Index | 0 | 1 | 2 | 3 | 5 |
| Value | 10 | 20 | 30 | 40 | 50 |
1. Array Index (MOST IMPORTANT RULE)
- Array index always starts from 0
- Last index =
size - 1
Example:
int a[5];Valid indexes:
a[0] a[1] a[2] a[3] a[4]Invalid:
a[5] // ERROR (out of range)2. Array Declaration Syntax
data_type array_name[size];Examples:
int a[5];
float price[10];
char name[20];3. Array Initialization (Storing Values)
Method 1: At declaration
int a[5] = {10, 20, 30, 40, 50};Method 2: Partial initialization
python
1
2int a[5] = {10, 20};Remaining values become 0.
Method 3: Assign one by one
a[0] = 10;
a[1] = 20;4. Accessing Array Elements
printf("%d", a[2]);Output:
30Reason:
- Index
2stores value30
