What is One Dimensional Array in C?
An array with only one subscript is known as a one-dimensional array.
Example: int arr[10]
.
Syntax:
1 | data-type arrayName [ arraySize ]; |
Declaration of 1D Array in C:
For declaration, the programmer needs to specify the type of element and number of elements in an array.
Certain rules for declaring One Dimensional Array
- The declaration must have a data type(int, float, char, double, etc.), variable name, and subscript.
- The subscript represents the size of the array. If the size is declared as 10, programmers are allowed to store only 10 elements (index 0 to 9).
- An array index always starts from 0 as its first element. For example, if an array variable is declared as
arr[10]
, then it ranges from 0 to 9. - Each array element stored in a separate memory location.
1 | type arrayName [ arraySize ]; |
The data-type must be a valid C data type, a unique name must be specified to each array and the arraySize must be of an integer constant. Let see an example for integer array with 10 elements:
1 | int arr[10]; |
Initialization of 1D array in C:
Array can be initialize by using a single statement or one by one. The Initialization is done within the curly braces {}.
1 2 3 | int arr[5] = {45, 23, 99, 23, 90}; OR int arr[] = {45, 23, 99, 23, 90}; |
On second one the array size is not declared so that you can initialize as much value as you want.
Users can also directly assign the value to the particular element in an array by specifying the index number such as: below shows how to assign the value 23 to the 5th element of an array.
1 | arr[4] = 23; |
NOTE:
In the above example number 4 means the 5th element as the array index starts from 0.
Accessing a 1D Array Elements:
An array can be accessed by using the specific index number. It can be achieved by placing the particular index number within the bracket []. Such as:
1 2 | arr[4]; //the 5th element is accessed arr[7]; //the 8th element is accessed |
We can also assign the value particular index number to other variable but their data type must be same such as:
1 | int numb = arr[4]; |
In the above, the value of 5th element from an array arr[] is assigned to the numb variable.
Example of 1D Array in C.
Declaring and assigning 5 elements in an array and display them accordingly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <stdio.h> void main() { int arr[5], i; printf("Enter 5 Elements.\n"); for (i = 1; i <= 5; i++) { printf("Element %d = ", i); scanf("%d", &arr[i]); } printf("\nElements in an Array:\n"); for (i = 0; i <= 5; i++) { printf("%d ", arr[i]); } } |
Output:
1 2 3 4 5 6 7 8 9 | Enter 5 Elements. Element 1 = 23 Element 2 = 45 Element 3 = 66 Element 4 = 90 Element 5 = 100 Elements in an Array: 23 45 66 90 100 |