Arrays in C
Arrays in C (1D & 2D Arrays)
Introduction
In C programming, an array is used to store multiple values of the same data type in a single variable.
👉 Instead of creating many variables, we can use an array to store all values together.
What is an Array?
An array is:
👉 A collection of elements of the same data type stored in contiguous memory locations
Why Use Arrays?
- ✔ Store multiple values easily
- ✔ Reduce number of variables
- ✔ Easy data handling
- ✔ Efficient memory usage
1. One-Dimensional Array (1D Array)
Syntax
data_type array_name[size];
Example
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int i;
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output
10 20 30 40 50
Accessing Elements
👉 Array elements are accessed using index:
arr[0], arr[1], arr[2]
👉 Index starts from 0
Taking Input in Array
#include <stdio.h>
int main() {
int arr[3], i;
for (i = 0; i < 3; i++) {
scanf("%d", &arr[i]);
}
for (i = 0; i < 3; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Sample Output
Input: 1 2 3
Output: 1 2 3
2. Two-Dimensional Array (2D Array)
👉 Used to represent tables or matrices
Syntax
data_type array_name[rows][columns];
Example
#include <stdio.h>
int main() {
int arr[2][2] = {
{1, 2},
{3, 4}
};
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
Output
1 2
3 4
Memory Representation
👉 1D Array:
[10][20][30][40][50]
👉 2D Array:
[1][2]
[3][4]
Comparison Table
| Feature | 1D Array | 2D Array |
|---|---|---|
| Structure | Single row | Rows & Columns |
| Index | One index | Two indices |
| Use | List | Matrix/Table |
Common Mistakes
- ❌ Accessing invalid index
- ❌ Not initializing array
- ❌ Wrong loop limits
- ❌ Confusing row & column
Pro Tips
- ✔ Always start index from 0
- ✔ Use loops for arrays
- ✔ Practice 2D arrays
- ✔ Understand memory structure
Conclusion
Arrays are essential in C programming. They allow storing and processing multiple values efficiently.
Master arrays to handle data effectively in programs.
👉 This article is part of Dharani Tech Edu Hub — where learning programming is made simple and practical.
Comments
Post a Comment