๐ C 1D Arrays – Understanding One-Dimensional Arrays
A 1D array in C is a simple data structure that allows you to store multiple values in a single variable. It represents a collection of elements, all of the same type, stored in a contiguous block of memory. These elements can be accessed using an index starting from 0.
๐น Declaring and Initializing a 1D Array
To declare a 1D array in C, you specify the data type, followed by the array name, and the number of elements it can hold in square brackets.
๐ Example 1: Declaring a 1D Array
Here’s an example of how to declare a 1D array of integers:
#include <stdio.h>
int main() {
int numbers[5]; // Declaring a 1D array with 5 elements
numbers[0] = 10; // Assigning value to the first element
numbers[1] = 20; // Assigning value to the second element
numbers[2] = 30; // Assigning value to the third element
printf("First element: %d\n", numbers[0]);
printf("Second element: %d\n", numbers[1]);
return 0;
}
๐น Initializing a 1D Array
You can initialize a 1D array at the time of declaration by specifying values for each element in the array.
๐ Example 2: Initializing a 1D Array
Here’s an example of initializing a 1D array with values at the time of declaration:
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50}; // Initializing a 1D array
printf("First element: %d\n", numbers[0]);
printf("Second element: %d\n", numbers[1]);
return 0;
}
๐น Accessing Array Elements
Each element of a 1D array can be accessed using its index. The index starts at 0 for the first element, 1 for the second, and so on.
๐ Example 3: Accessing Array Elements
In this example, we access each element of the array and print it using a loop:
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
// Loop to access and print each element of the array
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i + 1, numbers[i]);
}
return 0;
}
๐ฏ Key Points about 1D Arrays
- A 1D array stores multiple elements of the same data type in a single variable.
- The elements are stored in contiguous memory locations, and they can be accessed using an index.
- The index of the first element is always 0, and the index of the last element is
size-1. - Array elements can be accessed and modified using the index value.
๐ก Practice Challenge
Try creating a 1D array of different data types (e.g., floats or characters). Modify the arrayโs values, and experiment with printing different elements using different indices.