What is an Array?
Think of an array as a row of lockers in a school hallway. Each locker has a number (starting from 0), and you can store something in each locker. Similarly, an array is a collection of variables of the same data type stored in consecutive memory locations.
Why Use Arrays?
Instead of creating separate variables like:
int student1_score = 85;
int student2_score = 92;
int student3_score = 78;
// ... and so on for 100 students!
You can use an array:
int scores[100]; // One array to store all 100 scores!
Array Declaration
The basic syntax for declaring an array is:
data_type array_name[size];
Examples:
int numbers[5]; // Array of 5 integers
char letters[10]; // Array of 10 characters
float prices[3]; // Array of 3 floating-point numbers
Array Initialization
You can initialize arrays in several ways:
Method 1: Initialize during declaration
int ages[4] = {25, 30, 35, 40};
char grades[5] = {'A', 'B', 'C', 'D', 'F'};
Method 2: Initialize without specifying size
int numbers[] = {10, 20, 30, 40, 50}; // Size automatically becomes 5
Method 3: Partial initialization
int values[5] = {1, 2}; // First two elements are 1,2; rest are 0
Accessing Array Elements
Array elements are accessed using index numbers starting from 0.
int scores[5] = {85, 92, 78, 96, 88};
printf("%d", scores[0]); // Prints 85 (first element)
printf("%d", scores[2]); // Prints 78 (third element)
printf("%d", scores[4]); // Prints 88 (last element)
Array Index Table
| Index | Value | Description |
|---|---|---|
| 0 | 85 | First element |
| 1 | 92 | Second element |
| 2 | 78 | Third element |
| 3 | 96 | Fourth element |
| 4 | 88 | Fifth element |
Modifying Array Elements
You can change array elements by assigning new values:
int numbers[3] = {10, 20, 30};
numbers[1] = 25; // Changes second element from 20 to 25
numbers[2] = 35; // Changes third element from 30 to 35
// Now array is: {10, 25, 35}
Complete Example
Here's a practical example showing array basics:
#include <stdio.h>
int main() {
// Declare and initialize an array
int temperatures[7] = {22, 25, 28, 30, 27, 24, 21};
// Print all temperatures
printf("Weekly temperatures:\n");
for(int i = 0; i < 7; i++) {
printf("Day %d: %d°C\n", i+1, temperatures[i]);
}
// Modify a temperature
temperatures[3] = 32; // Change day 4 temperature
printf("\nUpdated temperature for day 4: %d°C\n", temperatures[3]);
return 0;
}
Important Points to Remember
- Array indices start from 0, not 1
- Array size must be specified during declaration (except when initializing)
- All elements in an array must be of the same data type
- Accessing an index outside the array bounds can cause errors
- Array name represents the address of the first element
Arrays are fundamental building blocks in C programming, making it easy to work with collections of related data!