2D Arrays(Manipulation)

Hi
I'am new to programming and i need help concerning 2D arrays. If i read in data values from a file and stored these data into a 2D array. How can i manipulate the datas stored within this array?? Say...

My Array is;

float num[3][2];

and the file data is;

intergers1 integers 2
1 2
3 4
5 6
Now the manipulation is, i want to sum up all values under heading (integers2) and print out the sum.
Last edited on
The more obvious way would be to introduce two loops to read and write the array.

1
2
3
4
5
6
7
for (int i = 0; i<3;i++)
    {
      for (int j= 0; j<2; j++)
         { 2DArray[i][j] = whatever;
         }
    }


This way you can iterate through the whole array and address every element seperately.

A more elegent way I think is to iterate throught the array this way:

1
2
3
4
5
6
7
8

int 2DArray [3][2] = {0];
int* p2DArray = 2DArray;

for (int i = 0; i< 6; i ++)
{ *(p2DArray + i) = whatever;
}


I hope I have pointed you into the right direction.

int main
To write your hole array you could also use the relatively fast function memset
To add up the numbers you want, just think of how the indices change as you move through the array. You know that the first dimension index has to increase by 1 each time, and that the second dimension index is always 1 since you always want the 2nd value. So we can create a single loop to sum these numbers:
[code=c++]
sum = 0;
for( int i = 0; i < 3; i++ ) {
sum += num[i][1];
}
[/code]
Topic archived. No new replies allowed.