An array is a collection of single type of data.
Syntax:
datatype arrayName[arraySize];
Assigning values to array.
int age[5] = {56, 45, 87, 23, 54};
We can also remove the size of the array so that the compiler will automatically determine the size of the array by counting the elements inside thew curly bracket.
int age[] = {56, 45, 87};
If the size of an array is 5 and we adds only 3 value to it then the remaining two values will be occupied by 0.
int age[5] = {56, 45, 87};
Access array elements.
In c programming each element of an array is represented with a value known as index value. Index value starts with 0, therefore the first element of an array will have the index value 0.
To access the element in an array we use:
arrayName[index]
Example:
int age[5] = {56, 45, 87, 89, 54};
printf("%d", age[0]);
Assign values using index number.
int age[5];
age[0] = 22;
age[1] = 65;
age[2] = 43;
age[3] = 56;
age[4] = 26;
age[5] = 89;
Assign values to an array from user input
int age[5];
printf("Enter 5 input values: ");
scanf("%d", &age[0]);
scanf("%d", &age[1]);
scanf("%d", &age[2]);
scanf("%d", &age[3]);
scanf("%d", &age[4]);
scanf("%d", &age[5]);
Changing array elements.
#include <stdio.h>
int main() {
int age[5] = {4, 56, 8, 43, 6};
//changing array elements.
age[2] = 26;
printf("%d", age[2]);
return 0;
}
In the above code, we have changed the value 8 to 26. The index value of 8 is 2.
Loops in array
We can use loops in C programming to assign or print values in an array.
#include <stdio.h>
int main() {
int age[5];
for(int i=0; i<5; i++){
scanf("%d", &age[i]);
}
for(int i=0; i<5; i++){
printf("%d", age[i]);
}
return 0;
}
Index out of Bound Error
If we try to access array outside of its bound or limit or allocated memory space then it can cause error.
Example:
int age[5];
for(int i=0; i<5; i++){
scanf("%d", &age[i]);
}
for(int i=0; i<6; i++){
printf("%d ", age[i]);
}
Output:
8 6 5 4 3 32764
In the above code the size of an array is 5. And in the second loop we are trying to access the 6th element of the array named age. Therefore this caused the index out of bound error and prints the value 32764.
Top comments (0)