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.
for statements
Started by kumamako, Jul 30 2009 07:11 AM
4 replies to this topic
#1
Posted 30 July 2009 - 07:11 AM
|
|
|
#2
Posted 30 July 2009 - 07:26 AM
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;
}
#3
Posted 01 August 2009 - 07:17 AM
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:
This only works with static arrays. Try this with a pointer and you'll most likely get garbage, if not a seg fault.
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
Posted 02 August 2009 - 07:04 AM
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
Posted 02 August 2009 - 09:27 AM


Sign In
Create Account


Back to top









