Thread: How do you add up certain elements in array using pointers

1. How do you add up certain elements in array using pointers

lets say I have an array decleared such as:
double numArray[15]={14.83,19.24,0.84,1.98,3.47,0,0,0,0,0,827.39,632. 85,471.38,0.04,4.83}

and also I have some pointers decleared such as:
double *first=numArray;
double *last=first+4;
double *front=first+10;
double *back=first+14;

now how would I add up elements 0-4 and add up the elements 10-14, and subtract the second list(elements 10-14) from the first list(elements 0-4).

2. Lots of different ways to do it but they should include loops, or better yet, a single loop. When you want a sum of numbers you need to initailaize a variable to zero:

int sum =0;

Than use this notation:

sum += *ptr;

The pointer is dereferenced and the sum is the running total. Could also be written as:

sum = sum + *ptr; //same thing

3. try this, you only need 1 pointer
Code:
#include <stdio.h>

int main()
{
double numarray[] = {14.83,19.24,0.84,1.98,3.47,0,0,0,0,0,827.39,632.85,471.38,0.04,4.83};
double *numarray_ptr, total = 0;

int size, x;

numarray_ptr = numarray;
size = sizeof(numarray) / sizeof(double);

for(x=0; x<size; x++)
{
if(x < 4 || x > 9)
total += *numarray_ptr;

numarray_ptr++;

}
printf("\nToatal of numbers is %.2f\n", total);
return 0;
}

More clues required.

Code:
#include <stdio.h>

double sum_array_segment ( double *start, double *end ) {
double res = 0.0;
while ( start <= end ) {// everything between the end pointers
res = res + *start; // add
start++;            // and move on
}
return res;
}

int main ( int argc, char *argv[] ) {
double numArray[15]={14.83,19.24,0.84,1.98,3.47,
0,0,0,0,0,
827.39,632.85,471.38,0.04,4.83};
double *first=numArray;
double *last=first+4;
double *front=first+10;
double *back=first+14;
printf( "%f %f\n",
sum_array_segment( first, last),
sum_array_segment( front, back ) );
return 0;
}