← Previous | 🏠 Homepage | Next Chapter → |
First, a Problem:
x = 5;
x = 10;
printf("%d", x); // Prints 10
Why not 5? Because poor x
can only remember one thing at a time.
But what if you had to store marks of 100 students? You could make 100 variables...
Or you could just use one awesome array.
So, What’s an Array?
An array is like a row of boxes , all of the same type (like all int
, or all float
).
Each box has:
-
A name (like
marks
) -
A position (called an index, starting from 0)
Example:
int marks[5] = {48, 88, 69, 23, 96};
Here:
-
marks[0]
is 48 -
marks[1]
is 88 -
And guess what?
marks[4]
is 96
But if you ask formarks[5]
, C gets angry. It doesn't exist!
Declaring an Array
int marks[30];
Means: "Hey C! Reserve 30 boxes to store integers!"
Let's Build a Cool Example
int marks[30]; // 30 students
int sum = 0, avg;
for (int i = 0; i < 30; i++) {
printf("Enter marks: ");
scanf("%d", &marks[i]); // Put marks in each box
}
for (int i = 0; i < 30; i++) {
sum += marks[i]; // Add all marks together
}
avg = sum / 30;
printf("Average marks = %d", avg);
1.Array Initialization – Give It a Head Start!
Instead of stuffing values after declaring the array, why not feed it right away?
int num[6] = {2, 4, 12, 5, 45, 5}; // Full buffet
int n[] = {2, 4, 12, 5, 45, 5}; // No size? No problem!
float press[] = {12.3, 34.2, -23.4, -11.3}; // Floats love arrays too
Tips:
-
If you don’t initialize, C fills it with garbage (not banana peels, but random numbers).
-
If you use
static
, C is kind enough to fill all with 0. Zero is love
2.Memory Magic – Where Arrays Live
int arr[8];
int arr[8];
Boom — 8 boxes (a.k.a. memory slots) are created:
-
In Turbo C: 2 bytes each = 16 bytes total
-
In modern systems: 4 bytes each = 32 bytes
And guess what? All boxes are side by side — like besties in a train compartment
But remember: uninitialized = garbage inside! Unless declared static
.
3.Beware of Array Overflow – C Won’t Warn You!
Here comes the monster:
int num[40], i;
for (i = 0; i <= 100; i++)
num[i] = i; // Yikes!
You’re writing way past the array’s limit. What happens?
-
C says nothing
-
You might overwrite other data
-
Or even crash your program
C doesn’t babysit. It’s your job to stay within the bounds. No crossing the array border!
No comments:
Post a Comment