In C programming language, an array is a collection of elements of the same data type, stored in contiguous memory locations. Arrays are used to store and manipulate multiple values of the same data type, such as a list of numbers or a sequence of characters.
To declare an array in C, you need to specify the data type of the elements and the number of elements in the array. The basic syntax for declaring an array is as follows:
data_type array_name[array_size];
Here, data_type
is the data type of the elements in the array, array_name
is the name of the array, and array_size
is the number of elements in the array. For example, to declare an array of 5 integers, you would use the following code:
int numbers[5];
This declares an array named numbers
that can hold 5 integers. The elements of the array are numbered from 0 to 4, so you can access individual elements of the array using their index, which is an integer value between 0 and array_size - 1
. For example, to set the value of the first element of the array to 10, you would use the following code:
numbers[0] = 10;
You can also initialize an array with a list of values. For example, to initialize the numbers
array with the values 1, 2, 3, 4, and 5, you would use the following code:
Syntax :
int numbers[] = {1, 2, 3, 4, 5};
This automatically sets the values of the elements of the numbers
array to the corresponding values in the list.
You can access and modify individual elements of an array using their index. For example, to print the third element of the numbers
array, you would use the following code:
printf("%d\n", numbers[2]);
This prints the value of the third element of the numbers
array, which is 3.
You can also use loops to iterate over the elements of an array. For example, to calculate the sum of the elements of the numbers
array, you would use the following code:
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
printf("Sum = %d\n", sum);
This initializes a variable named sum
to 0, and then uses a for
loop to iterate over the elements of the numbers
array and add their values to the sum
variable. Finally, it prints the value of the sum
variable.
Comments