1-D Array in C

In C programming, a 1D array, also known as a one-dimensional array, is a collection of elements of the same data type arranged in a linear sequence. It is a fundamental data structure that allows you to store and manipulate a fixed-size sequence of values. Each element in the array is accessed by its index, which represents its position within the array.

To declare and use a 1D array in C, you typically follow these steps:

1. Array Declaration

  • Specify the data type of the elements in the array.
  • Provide a name for the array.
  • Use square brackets [] to indicate that it is an array.
  • Specify the size of the array by indicating the number of elements it can hold.

Syntax

data_type array_name[size];

Example

int numbers[5];  // Declaration of an integer array with size 5
float grades[10];  // Declaration of a float array with size 10

2. Array Initialization (optional)

  • Assign initial values to the elements of the array.
  • This step is not mandatory. If not initialized explicitly, the elements will have default values (e.g., 0 for integers, 0.0 for floats, NULL for pointers).

Syntax

data_type array_name[size] = {value1, value2, ...};

Example

int numbers[5] = {10, 20, 30, 40, 50};  // Initialization of an integer array
float grades[10] = {90.5, 85.0, 77.5, 92.0};  // Initialization of a float array

3. Array Access

  • Access individual elements of the array using their indices.
  • Indices start from 0 and go up to size - 1.

Syntax

array_name[index]

Example

int value = numbers[2];  // Accessing the 3rd element of the array
printf("%d\n", value);  // Output: 30

numbers[4] = 60;  // Modifying the 5th element of the array

Array Iteration

  • Use loops (e.g., for loop) to iterate over the array elements.
  • Access each element using its index within the loop body.

Example

for (int i = 0; i < 5; i++) {
    printf("%d ", numbers[i]);  // Output: 10 20 30 40 50
}

1D arrays are commonly used to store and process collections of data in C. They provide a convenient way to work with a sequence of elements of the same data type. By using array indices, you can access and manipulate individual elements efficiently.

Next Article ❯