Jump to content

for statements

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
kumamako

kumamako

    Newbie

  • Members
  • PipPip
  • 16 posts
1) nested for statements must be used to total the elements of a two dimensional array.

I put true since the book only showed a nested for statement example to total elements in a TWO DIM ARRAY. However, the professor marked me wrong and he said its false. It is false because of the word "must." The sum of the elements may be obtained without for statements (e.g., using while statements), with one for statement, three for statements, etc.

But i do not understand how one could use while, one for, and three for to sum the integer of a two dim array. Can someone explain me and give an example of each please. I am still doubting the professors answer and still believe that the only way to sum elements in a two dim array is using nested for.

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
int array[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
int sum = array[0][0] + array[0][1] + ...;
int sum2 = 0, index1=0, index2=0;
while (index1 != 3)
{
  while (index2 != 3)
  {
    sum2+=array[index1][index2];
    index2++;
  }
  index1++;
  index2=0;
}

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,715 posts
Depending on how the array is stored in memory, you could also just use a single for or while loop, though it doesn't help readability:

size_t i, total = 0;
for(i = 0; i < NUM_ROWS*NUM_COLS; ++i)
    total += arr[i];

This only works with static arrays. Try this with a pointer and you'll most likely get garbage, if not a seg fault.
sudo rm -rf /

#4
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
int j = 0;
int k = 0;
int m = 0;
int[3][3] thearray = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for (int i = 0; i < 9; ++i) {
    if (j > 2) {
        j = 0;
        ++k;
    }
    m += thearray[k][j];
    ++j;
}
You can do it with a single for loop too, and I think this is a little more readable than dargueta's.

- Zeke

Edited by ZekeDragon, 02 August 2009 - 11:54 AM.
I only initialized the array, I should have been adding them...


#5
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,715 posts
And it doesn't rely on the memory block being contiguous or static. Nice.
sudo rm -rf /