Defining an array
- Without mentioning the array’s size
int arr[] = {1, 2, 3};
Although the array in this situation cannot be empty, we can leave the square brackets empty. There must be components in it.
- By defining the array’s size
int arr[3];
arr[0] = 1, arr[1] = 2, arr[2] = 3;
In this case, the array’s definition itself allows us to specify its size. The items of an array can then be added afterwards.
Accessing an array element
- The index number of an array element makes it simple to access that element. It is important to keep in mind that the index number actually begins at zero, not one.
#include <stdio.h>
int main()
{
int arr[] = {1, 5, 7, 2};
printf("%d ", arr[2]); //printing element on index 2
}
Output:7
Changing an array element
- Using an array’s index number, an element can be replaced.
Example:
#include <stdio.h>
int main()
{
int arr[] = {1, 5, 7, 2};
arr[2] = 8; //changing the element on index 2
printf("%d ", arr[2]); //printing element on index 2
}
Output:8