Find sum of elements in an array
This is a problem which asks to find sum of all elements in an array.
Approach 1:
Run a for loop from first element to the last ,use a auxiliary variable sum and add each variable as you run through the loop.
code for this approach looks like
int sum=0;
int arr[10]={1,2,3,4,5,6,7,8,9,0};
for(int i=0;i<10;i++)
sum+=a[i];
printf("sum of array elements is %d",sum);
Approach 1 uses 'n' iterations to compute sum of elements.
Approach 2:
use a while loop to add first , last element until you reach the middle element ,this reduces the number of iterations to half.
int sum=0;
int arr[10]={1,2,3,4,5,6,7,8,9,0};
int first=0,last=10-1;
while(first
{
sum+=arr[first]+arr[last];
first++;//move to next element
last--;//move to prev element
}
printf("sum of array elements is %d",sum);
This prints sum of elements in an array.using O(log(n)) iterations .
thus time complexity reduces using this second approach.