C - Arrays

Arrays are an essential data structure in C programming that allows you to store multiple elements of the same data type in a contiguous memory block.

Initialize values without size:

If you want to initialize an array without specifying its size, you can use an initializer list. The size of the array will be automatically determined based on the number of elements in the initializer list.

int numbers[] = {1, 2, 3, 4, 5};

In this example, the numbers array is initialized with five elements: 1, 2, 3, 4, and 5. The size of the array is automatically determined as 5.

Access the elements of an array:

You can access individual elements of an array using their index. The index starts from 0 for the first element and goes up to size - 1, where size is the total number of elements in the array.

int numbers[] = {1, 2, 3, 4, 5};
int firstElement = numbers[0];   // Access the first element
int thirdElement = numbers[2];   // Access the third element

In this example, firstElement will have the value 1, and thirdElement will have the value 3.

Change an array element:

You can modify the value of an array element by assigning a new value to it using the index.

int numbers[] = {1, 2, 3, 4, 5};
numbers[1] = 10;   // Change the value of the second element to 10

In this example, the second element of the numbers array is changed from 2 to 10.

Loop through an array:

You can use loops, such as the for loop, to iterate through the elements of an array and perform operations on them.

int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);   // Get the size of the array
for (int i = 0; i < size; i++)
{
    printf("%d ", numbers[i]);   // Print each element of the array
}

In this example, the for loop is used to iterate through each element of the numbers array and print its value.

Set array size:

In C, the size of an array must be specified at the time of declaration. You can set the size of an array using a constant or a variable.

const int SIZE = 5;
int numbers[SIZE];   // Array with a constant size
int size = 10;
int values[size];    // Array with a variable size

In these examples, the numbers array has a size of 5, and the values array has a size of 10.