I’m doing an exercise over loops and have a doubt.
I have an array of ints and want to iterate all over this array the get the sumof the array elements. This iteraction must be done, in each pass, sum the first element and the last, on the second iteraction, sum the second element and the last element minus 1 and so on.
If I have an array with a even number of elements I’m doing this way:
int main(){
int i,sum=0,arraySize=10;
int array[] = {1,2,3,4,4,4,7,8,9,10};
for (i=0;i <arraySize/2;i++){
sum+=array[i] + array[arraySize-i-1];
}
printf("The sum is %d\n", sum);
return 0;
}
but if I have an odd number I’m doing this:
int main(){
int i,sum=0,arraySize=11;
int array[] = {1,2,3,4,4,4,7,8,9,10,11};
for (i=0;i <(arraySize/2)+0.5;i++){
if (i != (arraySize/2)){
sum+=array[i] + array[arraySize-i-1];
}
else{
sum+=array[i];
}
}
printf("The sum is %d\n", sum);
return 0;
}
Is this the correct way?
I would do it like this: