An array can be thought of as a list of items. The items could represent a sequence or a collection of some sort.
For example, we are creating an application for a business that needs to record its total profit in a week. Here, we can use arrays to create an array of size 7 where each of the 7 elements of the array represents the total profit for a specific day.
In C, an array is used to store elements of the same type. The diagram below further explains what it looks like in C programs.
In the diagram, we can see an array that contains integer numbers. The size of the array is 6, which means it can hold 6 elements. We also see that each element in the array has an index value representing where the element is placed. One thing to note is that the index of an array in C starts from 0. So if we want to retrieve the number 15 from the above array, we would need to use the index value of 3, representing the 4th element in the array.
Below, we can see the syntax to create an array.
dataType arrayName[int elements];
The placeholders used in the syntax above are:
dataType
: This represents the type of elements that the array can store.
arrayName
: This represents the name we provide to the array.
elements
: This is an integer variable representing an array's total number of elements.
Now that we have looked at the syntax to declare an array in C, let's look at the example below.
Let's suppose we have to store the text Educative
in our C program. How would we go about doing this?
We can see that the text has 9 characters in total. Hence, we can create an array of size 9. We can call this array myText
and initialize it with the text once we have created it.
Below is a C application that shows us how this can be done.
#include<stdio.h>int main() {char myText[9] = "Educative";for(int i = 0; i < 9; i++){printf("myText[%d]: %c\n", i, myText[i]);}}
Line 3: Create an array named myText
of size 9 and initialize it with the text Educative
.
Lines 5–7: Loop over the array and print the values of each specific array index from 0 to 8.
In this Answer, we discussed array in C by understanding the concept of a simple one-dimensional (1D) array. For two-dimensional (2D) arrays, you can visit this Answer.
Free Resources