Arrays in C
Till now, we have worked with variables that store only one value at a time.
But in real programs, we often need to store multiple values of the same type under one name.
This is where arrays come into the picture.
What Is an Array?
An array is a collection of variables of the same data type stored in continuous memory locations.
Instead of creating many separate variables, an array allows us to store all related values together.
Example idea:
- Marks of 5 students
- Temperatures of 7 days
- Salaries of 10 employees
Why Arrays Are Needed
Without arrays, storing multiple values becomes difficult.
Imagine storing marks of 5 students without arrays:
- mark1
- mark2
- mark3
- mark4
- mark5
With arrays, one variable name is enough.
Declaring an Array
Syntax:
data_type array_name[size];
Example:
int marks[5];
This creates an array named marks
that can store 5 integer values.
Array Index
Each element in an array is accessed using an index number.
Important rule:
- Array index starts from 0
- Last index is
size - 1
For an array of size 5:
- First element → index 0
- Last element → index 4
Storing Values in an Array
marks[0] = 85;
marks[1] = 90;
marks[2] = 78;
marks[3] = 88;
marks[4] = 92;
Each value is stored at a specific index.
Accessing Array Elements
printf("%d", marks[2]);
This prints the value stored at index 2.
Using Loop with Array
Arrays and loops are best friends.
#include <stdio.h>
int main() {
int marks[5] = {85, 90, 78, 88, 92};
int i;
for (i = 0; i < 5; i++) {
printf("Marks[%d] = %d\n", i, marks[i]);
}
return 0;
}
This loop prints all elements of the array.
Numerical Example: Sum of Array Elements
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
int sum = 0, i;
for (i = 0; i < 5; i++) {
sum += numbers[i];
}
printf("Sum = %d", sum);
return 0;
}
Here:
- Each element is accessed using index
- Loop adds all values
Common Mistakes
- Accessing index outside array size
- Forgetting index starts from 0
- Using wrong loop condition
Accessing invalid index may cause runtime errors.
Mini Practice
- Store 5 numbers in an array and print them
- Find the largest element in an array
- Calculate average of array elements
Quick Quiz
Q1. What is an array?
An array is a collection of same type values stored in continuous memory.
Q2. What is the first index of an array?
0
Q3. How many elements can int a[5] store?
5 elements
Q4. What is the last index of an array of size 10?
9
Q5. Why are loops commonly used with arrays?
To access and process all elements efficiently