Array
An array in C is a collection of variables of the same data type that are stored in contiguous memory locations and can be accessed using a single identifier. Arrays are useful for storing and manipulating large amounts of data, as they allow you to access and manipulate multiple values using a single loop or function.
Here is an example of declaring and initializing an array in C:
#include <stdio.h>
int main()
{
int a[5] = {1, 2, 3, 4, 5};
return 0;
}
In this example, we have declared an array a of 5 integers and initialized it with the values 1, 2, 3, 4, and 5. The array has a fixed size of 5, and the values are stored in contiguous memory locations.
You can access individual elements of the array using the index operator []. The index of an array element starts at 0 and goes up to the size of the array minus 1. For example:
#include <stdio.h>
int main()
{
int a[5] = {1, 2, 3, 4, 5};
printf("a[0] = %d\n", a[0]); // prints 1
printf("a[1] = %d\n", a[1]); // prints 2
printf("a[2] = %d\n", a[2]); // prints 3
printf("a[3] = %d\n", a[3]); // prints 4
printf("a[4] = %d\n", a[4]); // prints 5
return 0;
}
In this example, we have accessed each element of the array a and printed its value to the console.
You can also use a loop to iterate over the elements of an array. For example:
#include <stdio.h>
int main()
{
int a[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
printf("a[%d] = %d\n", i, a[i]);
}
return 0;
}