C107: Arrays
Array is used to store a list of data using a same name. data type can int, float, double, char. Array name is same as variable name, array size indicates how many data this array can store.
following example declares an array called num with size of the array is 5.
this means num can store up to 5 integer values. This statement only give name and allocates enough space for the array. It does not contain values. Array uses index to refer to particular elements in an array. Index 0 for the first element, 1 for second, and so on.
following line is to store a value as first element in num
this statement will store 2 at index 0 of the num array. Let's assign value for every element in the array.
now all the space in the array contains a value. Take note that the index of last element in the array is (arraySize - 1) because index start from 0.
now we can use the array value to do calculations
this means total is 4 + 5, so the total value is 9.
we use for loop to find the sum of values stored in the array
the output is
displaying all the element of num using for loop:
the output for the second example is
dataType arrayName[arraySize];
following example declares an array called num with size of the array is 5.
int num[5];
this means num can store up to 5 integer values. This statement only give name and allocates enough space for the array. It does not contain values. Array uses index to refer to particular elements in an array. Index 0 for the first element, 1 for second, and so on.
following line is to store a value as first element in num
num[0] = 2;
this statement will store 2 at index 0 of the num array. Let's assign value for every element in the array.
num[1] = 1;
num[2] = 4;
num[3] = 5;
num[4] = 3;
num[2] = 4;
num[3] = 5;
num[4] = 3;
now all the space in the array contains a value. Take note that the index of last element in the array is (arraySize - 1) because index start from 0.
now we can use the array value to do calculations
total = num[2] + num[3];
this means total is 4 + 5, so the total value is 9.
we use for loop to find the sum of values stored in the array
int total = 0;
for(int i = 0; i < 5;i++){
total = total + num[i];
}
prinf("Total num : %d\n", total);
for(int i = 0; i < 5;i++){
total = total + num[i];
}
prinf("Total num : %d\n", total);
the output is
Total num : 15
displaying all the element of num using for loop:
int total = 0;
for(int i = 0; i < 5;i++){
int temp = i+1;
printf("Element %d : %d\n",temp, num[i];
}
for(int i = 0; i < 5;i++){
int temp = i+1;
printf("Element %d : %d\n",temp, num[i];
}
the output for the second example is
Element 1 : 2
Element 2 : 1
Element 3 : 4
Element 4 : 5
Element 5 : 3
Element 2 : 1
Element 3 : 4
Element 4 : 5
Element 5 : 3
Comments
Post a Comment