• Home
  • How to Store Array?

How to Store Array?

In C language, an array is a collection of elements of the same type, stored in contiguous memory locations. To store an array in C, you need to declare a variable of the desired type, and specify the size of the array.

Here is an example of declaring and initializing an array of integers in C:

int array[10]; // declare an array of 10 integers

int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // declare and initialize an array of 10 integers

In the first example, the array is declared with a size of 10, but no values are initialized. The elements of the array are uninitialized, and have undefined values.

In the second example, the array is declared and initialized with values. The elements of the array are initialized with the given values, in the order they appear. The size of the array is inferred from the number of values provided.

You can also declare an array with a size larger than the number of values provided, and initialize only a subset of the elements:

int array[10] = {0, 1, 2}; // declare and initialize an array of 10 integers, with 3 values

In this example, the first three elements of the array are initialized with the given values, and the rest of the elements are uninitialized, and have undefined values.

You can access the elements of the array using the array subscript notation, as shown in the following example:

int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // declare and initialize an array of 10 integers

printf("%d\n", array[0]); // print the first element of the array
printf("%d\n", array[9]); // print the last element of the array

You can also modify the elements of the array using the array subscript notation:

int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // declare and initialize an array of 10 integers

array[0] = 100; // modify the first element of the array
array[9] = 200; // modify the last element of the array

You can also iterate through the elements of the array using a loop:

int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // declare and initialize an array of 10 integers

int i;
for (i = 0; i < 10; i++) {
printf("%d ", array[i]); // print the element at index i
}
printf("\n");

In this example, the loop iterates from 0 to 9, and prints out the elements of the array. The output of this code is “0 1 2 3 4 5 6 7 8 9”.

You can also use the sizeof operator to determine the size of the array:

int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // declare and initialize an array of 10 integers

int size = sizeof(array) / sizeof(array[0]); // calculate the size of the array
printf("The size of the array is %d\n", size);

In this example, the size of the array is calculated by dividing the total size of the array (in bytes) by the size of a single element