Arrays
Introduction to C
Structure of a C Program
Variables and Data Types
Input and Output
Operators in C
Decision Making
If Statement
if...else Statement
Nested if Statement
Nested if...else Statement
Switch Statement
Loops
For Loop
While Loop
Do While Loop
Loop Comparison
Arrays
Strings
Functions
Function Types
Library Functions
User-Defined Functions
Recursion Function
Pointers
Structures
File Handling
Common Mistakes
Ideas
Arrays
Introduction to Arrays
What is an Array?
An Array is a collection of variables of the same data type stored in contiguous (side-by-side) memory locations. Instead of declaring 10 separate variables to store 10 test scores, you can declare one array that holds all of them.
- Index: Every item in an array has a position number called an index. In C, arrays always start at index 0.
- Size: The number of elements an array can hold is fixed once it is declared.
Syntax
To declare an array, you must specify the data type, the name of the array, and the number of elements it will hold inside square brackets [ ].
data_type arrayName[array_size];
// Example with Initialization:
int numbers[5] = {10, 20, 30, 40, 50};
// Example with Initialization:
int numbers[5] = {10, 20, 30, 40, 50};
Practical Examples
Example 1: Accessing Array Elements
int marks[3] = {85, 92, 78}; // Printing the first element (index 0) printf("First Student: %d\n", marks[0]); // Changing the second element marks[1] = 95;
Example 2: Using a Loop with Arrays
Arrays and for loops are almost always used together!
int ages[4] = {12, 15, 18, 21}; for (int i = 0; i < 4; i++) { printf("Age at index %d is %d\n", i, ages[i]); }
Warning - Zero-Based Indexing: The most common error is trying to access the last element of an array of size
N using index N. Remember: an array of size 5 has indices 0, 1, 2, 3, and 4. Accessing array[5] will cause a "Buffer Overflow" or crash!
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute