One Dimensional Array in C
Hello Everyone, In this article, we will cover the concept of One Dimensional Array in C Programming. We will cover common operations and provide examples to help you understand how 1-D arrays work in real programs. Whether you’re new to C or have some experience, this guide will help you to understand Basics of 1 D Array in C effectively. Let’s get started.
In C programming, one dimensional array, is also known as, 1D array is a collection of elements of the same data type stored in contiguous memory locations. The array elements can be accessed by their index values, which start from 0 and go up to the size of the array minus 1.
Syntax of 1D Array
int arr[5]; // declares a 1D array of integers with size 5
This creates an array with 5 integer elements, where the first element has an index of 0, the second element has an index of 1, and so on up to the fifth element with an index of 4. Elements in the array can be accessed using square brackets notation:
arr[0] = 10; // assigns 10 to the first element in the array
arr[1] = 20; // assigns 20 to the second element in the array
Here, arr[0] refers to the first element in the array and arr[1] refers to the second element in the array. We can also use a loop to iterate through the array elements:
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
This will print all the elements in the array to the console.
C Program to declare, initialize, and access elements in a 1D array
#include <stdio.h>
int main() {
// declare and initialize a 1D array
int arr[5] = {1, 2, 3, 4, 5};
// access elements in the array
printf("%d\n", arr[0]); // output: 1
printf("%d\n", arr[2]); // output: 3
printf("%d\n", arr[4]); // output: 5
// modify an element in the array
arr[1] = 10;
printf("%d %d %d %d %d\n", arr[0], arr[1], arr[2], arr[3], arr[4]); // output: 1 10 3 4 5
return 0;
}
In the code above, we first declare and initialize a 1D array called arr with 5 integer elements. We then access elements in the array using their index values, and print the output to the console using printf(). Finally, we modify an element in the array by assigning a new value to it, and print the updated array to the console using printf(). Note that we used the %d format specifier to print integers in C.