One-Dimensional Arrays
In C, an array is a collection of elements of the same type stored in contiguous
memory locations. This organization allows efficient access to elements using
their index. Arrays can also be of different types depending upon the
direction/dimension they can store the elements. It can be 1D, 2D, 3D, and more.
We generally use only one-dimensional, two-dimensional, and three-dimensional
arrays.
One-Dimensional Arrays in C
A one-dimensional array can be viewed as a linear sequence of elements. We can
only increase or decrease its size in a single direction.
Only a single row exists in the one-dimensional array and every element within
the array is accessible by the index. In C, array indexing starts zero-indexing i.e.
the first element is at index 0, the second at index 1, and so on up to n-1 for an
array of size n.
Syntax of One-Dimensional Array in C
The following code snippets shows the syntax of how to declare an one
dimensional array and how to initialize it in C.
1D Array Declaration Syntax
In declaration, we specify then name and the size of the 1d array.
elements_type array_name[array_size];
In this step, the compiler reserved the given amount of memory for the array but
this step does not define the value of the elements. They may contain some
random values. So we initialize the array to give its elements some initial valu
1D Array Initialization Syntax
In declaration, the compiler reserved the given amount of memory for the array
but does not define the value of the element. To assign values, we have to
initialize an array.
elements_type array_name[array_size] = {value1, value2, ... };
This type of The values will be assigned sequentially, means that first element
will contain value1, second value2 and so on.
This initialization only works when performed with declaration.
1D Array Element Accessing/Updating Syntax
After the declaration, we can use the index of the element along with the array
name to access it.
array_name [index]; // accessing the element
Then, we can also assign the new value to the element using assignment operator.
array_name [index] = new_value; // updating element
Note: Make sure the index lies within the array or else it might lead to
segmentation fault.
To access all the elements of the array at once, we can use the loops as shown
below.
Example of One Dimensional Array in C
The following example demonstrate how to create a 1d array in a c program
// C program to illustrate how to create an array,
// initialize it, update and access elements
#include <stdio.h>
int main()
{
// declaring and initializing array
int arr[5] = { 1, 2, 4, 8, 16 };
// printing it
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// updating elements
arr[3] = 9721;
// printing again
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output
1 2 4 8 16
1 2 4 9721 16