• Home
  • How to Store Value in Array?

How to Store Value in Array?

In C language, you can store values in an array by using the assignment operator (=).

Here is an example of storing a value in an array of integers in C:

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

array[0] = 123; // store the value 123 in the first element of the array

In this example, the value 123 is stored in the first element of the array, at index 0.

You can also store values in an array using a loop:

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

int i;
for (i = 0; i < 10; i++) {
array[i] = i; // store the value i in the element at index i
}

In this example, the loop iterates from 0 to 9, and stores the corresponding values in the elements of the array.

You can also use the sizeof operator to determine the size of the array, and use it to store values in the array:

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

int size = sizeof(array) / sizeof(array[0]); // calculate the size of the array

int i;
for (i = 0; i < size; i++) {
array[i] = i; // store the value i in the element at index i
}

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 (in bytes). The result is the number of elements in the array. The loop iterates through the elements of the array, and stores the corresponding values.

You can also use the memset function to store a given value in an array:

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

memset(array, 0, sizeof(array)); // store the value 0 in all elements of the array

In this example, the memset function is used to store the value 0 in all elements of the array. The function takes three arguments: a pointer to the array, the value to set, and the size of the array (in bytes).

You can also use the memset function to store a non-zero value in an array:

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

memset(array, -1, sizeof(array)); // store the value -1 in all elements of the array

In this example, the memset function is used to store the value -1 in all elements of the array. The function takes three arguments: a pointer to the array, the value to set, and the size of the array (in bytes).