1-D Array in C
A 1-Dimensional (1-D) array in C is a collection of elements of the same data type, stored in contiguous memory locations. It is the simplest form of an array, where all the elements are accessed using a single index.
Definition
A 1-D array is essentially a list of elements, where each element is identified by an index. The index starts from 0 and goes up to (n-1), where n is the number of elements in the array.
Syntax:
data_type array_name[array_size];
Example 1: Declaring and Initializing a 1-D Array
{%raw%}
#include <stdio.h>
int main()
{
int numbers[5]; // Declaration of a 1-D array
printf("Enter 5 integers:\n");
// Input from user
for (int i = 0; i < 5; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &numbers[i]);
}
// Display the array
printf("\nYou entered:\n");
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i + 1, numbers[i]);
}
return 0;
}
{%endraw%}
Output
Enter 5 integers:
Element 1: 4
Element 2: 5
Element 3: 7
Element 4: 8
Element 5: 3
You entered:
Element 1: 4
Element 2: 5
Element 3: 7
Element 4: 8
Element 5: 3
Accessing Array Elements
In a 1-D array, each element is accessed using its index. The first element is at index 0, the second at index 1, and so on. You can use both loops and direct indexing to access elements.
Example 2: Accessing Elements Using a Loop
#include <stdio.h>
int main()
{
int numbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
printf("Element at index %d: %d\n", i, numbers[i]);
}
return 0;
}
Output
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
Key Points
- Arrays in C are indexed starting from 0.
- The size of the array must be known at compile time, except for dynamically allocated arrays.
- Accessing an array element is done using its index number, which is always between 0 and (array_size - 1).
- Using a loop is the most common way to iterate over and access elements of a 1-D array.
- Be cautious of accessing array elements outside its bounds, which may lead to undefined behavior.
Example 3: Modifying Array Elements
#include <stdio.h>
int main()
{
int numbers[5] = {1, 2, 3, 4, 5};
// Modify the 2nd element (index 1)
numbers[1] = 25;
// Print the modified array
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, numbers[i]);
}
return 0;
}
Output
Element 0: 1
Element 1: 25
Element 2: 3
Element 3: 4
Element 4: 5
Element 1: 25
Element 2: 3
Element 3: 4
Element 4: 5