C Arrays
Arrays
Arrays are a fundamental data structure in C programming used to store collections of elements of the same data type. They offer an efficient way to manage and access multiple related values under a single variable name.
Arrays use zero-based indexing. The first element has index 0, the second has index 1, and so on.
To insert values to it, use a comma-separated list, inside curly braces:
int myNumbers[] = {25, 50, 75, 100};
We have now created a variable that contains an array of four integers.
Accessing elements of an array is a specific programming language you're using.
To access an array element, refer to its index number.
Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
This statement accesses the value of the first element [0] in myNumbers:
Example
#include <stdio.h>
int main() {
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);
return 0;
}
Output
25
Change an Array Element
To change the value of a specific element, refer to the index number:
Example
myNumbers[0] = 33;
Example
#include <stdio.h>
int main() {
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;
printf("%d", myNumbers[0]);
return 0;
}
Output
33
Looping through an array : allows you to access and manipulate each element efficiently.
You can loop through the array elements with the for loop.
The following example outputs all elements in the myNumbers array:
#include <stdio.h>
int main() {
int myNumbers[] = {25, 50, 75, 100};
int i;
for (i = 0; i < 4; i++) {
printf("%d\n", myNumbers[i]);
}
return 0;
}
Output
25
50
75
100
Set Array Size
Set Array Size typically refers to the action of specifying or defining the number of elements that an array can hold in a programming context
Example
#include <stdio.h>
int main() {
// Declare an array of four integers:
int myNumbers[4];
// Add elements to it
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;
printf("%d\n", myNumbers[0]);
return 0;
}
Output
25
Using this method, you should know the number of array elements in advance, in order for the program to store enough memory.
You are not able to change the size of the array after creation.