Course Content
C Basics
C Basics
Introduction to Arrays
In earlier lessons, we discussed creating variables to hold some data. But what if we need to store a large amount of data, like the grades for a hundred high school students? It wouldn't be practical (or efficient) to create a hundred individual variables.
That's where arrays come in handy.
Think of an array as a collection of variables, all of the same type. If you visualize a variable as a single storage box, then an array is like a big warehouse filled with these boxes.
What's more, each box has its own unique identifier or index, allowing us to easily reference it.
Declaring an array looks something like this:
Here's how you'd declare an array with room for three elements. To store specific values in this array, you'd use curly braces:
You can access each item in the array using its index.
Indexes
An index is the unique number assigned to each item in the array. Think of it like your position in line at a coffee shop. Using indexes, we can pinpoint and access any item in the array. It's important to note that index counting starts from zero; so the first item's index is 0.
Main
#include <stdio.h> int main() { int array[3] = {56,3,10}; // array declaration printf("%d", array[0]); // print the first element of the array return 0; }
Note
The arrays we've discussed so far are static, meaning their size remains constant throughout the program's runtime. There are also dynamic arrays, which can adjust in size during program execution.
Here's another way to declare an array:
If you're directly specifying the items, you don't need to mention how many there are. The compiler will automatically determine the number of items in the array and allocate the appropriate amount of memory. This method works well for arrays with predetermined values.
However, declaring an array like this won't work.
And of course, you can modify the values stored in an array by referencing the desired index:
main
#include <stdio.h> int main() { int array[3] = { 56, 3, 10 }; printf("%d ", array[0]); printf("%d ", array[1]); printf("%d\n", array[2]); array[2] = 555; // change 10 to 555 printf("%d ", array[0]); printf("%d ", array[1]); printf("%d\n", array[2]); return 0; }
Thanks for your feedback!