Arrays serve to store multiple values within a single variable, eliminating the need to declare separate variables for each value.
To instantiate an array, define the data type (such as int) and specify the array’s name followed by square brackets [ ].
To populate it with values, employ a comma-separated list enclosed within curly braces:
int myNumbers[] = {25, 50, 75, 100}; |
We’ve established a variable capable of containing an array of four integers.
To access an element within an array, reference its index number.
Array indexes commence with 0: [0] corresponds to the first element, [1] to the second element, and so forth.
This statement retrieves the value of the first element [ 0 ] in myNumbers:
int myNumbers[] = {25, 50, 75, 100}; printf(“%d”, myNumbers[0]); // Outputs 25 |
To modify the value of a particular element, specify its index number:
myNumbers[0] = 33; |
int myNumbers[] = {25, 50, 75, 100}; myNumbers[0] = 33; printf(“%d”, myNumbers[0]); // Now outputs 33 instead of 25 |
You can iterate through the array elements using a for loop.
The subsequent example displays all elements in the myNumbers array:
int myNumbers[] = {25, 50, 75, 100}; int i; for (i = 0; i < 4; i++) { |
Another prevalent method of creating arrays involves specifying the array size initially and then adding elements subsequently:
// Declare an array of four integers: int myNumbers[4]; // Add elements |
When employing this approach, it’s necessary to determine the number of array elements beforehand to ensure sufficient memory allocation by the program.
Once created, you cannot alter the size of the array.