UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C
  • » how to find the sum of the elements in a three dimensional array using a single loop

#1 2009-03-10 01:38 PM

rvan
Member
Registered: 2009-02-27
Posts: 13

Re: how to find the sum of the elements in a three dimensional array using a single loop

Offline

#2 2009-03-10 01:59 PM

Nope
Administrator
From: Germany
Registered: 2004-01-24
Posts: 385
Website

Re: how to find the sum of the elements in a three dimensional array using a single loop

Offline

#3 2009-03-10 03:28 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: how to find the sum of the elements in a three dimensional array using a single loop

Offline

#4 2009-03-11 06:54 AM

rvan
Member
Registered: 2009-02-27
Posts: 13

Re: how to find the sum of the elements in a three dimensional array using a single loop

Thank you for your replies.

i understand that the starting position can be calculated using a + (20*50*50)+ (30*50)+49 and the same applies to find out the ending position too...
then we can find the number of elements by subtracting the ending - starting position + 1. but to access the element in this position we cannot use a + (20*50*50)+ (30*50) + 49 i.e a + 51549 since a is a 3 dimensional array. ( in case of three dimensional array a +1 gives the address of the next 2-D array.) am not clear how to access the element without using row, column... indexes.

Thanks

Offline

#5 2009-03-11 01:47 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: how to find the sum of the elements in a three dimensional array using a single loop

Just use a simple pointer variable to your base array type...  Ie: assuming this is an
array of ints:

int a[50][50][50];
int *p, *q;

for (p = &(a[20][30][49]), q = &(a[30][30][30]); p < q; p++) {
    /* do whatever to each element; eg: */
    sum += *p;
}

Note: you may want "<=" for that loop test; it wasn't entirely clear from your initial
post if the range was enclusive of the endpoint or not...

Offline

#6 2009-03-11 03:27 PM

rvan
Member
Registered: 2009-02-27
Posts: 13

Re: how to find the sum of the elements in a three dimensional array using a single loop

Thank you.

Offline

  • Index
  • » C
  • » how to find the sum of the elements in a three dimensional array using a single loop

Board footer

Powered by FluxBB