# Thread: How do we add across an array?

1. ## How do we add across an array?

I have a text file that have the following data,

0 1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24

I have put those values into a one dimension array already using a loop and infile >> Line0 >> Line1 >> Line2 >> ....

So for example Line0[0] would be 0. Line0[1] would be 11. Line0[2] would be 18. Line1[1] would be 1 and so forth.

What my question is how do we use a loop to add up the sum of the top row(0 1 2 3 4 5 6 7 8 9 10)?

Is there a method to change part of the variable name? I am thinking of something like this:
int i;
i=0;
Linei[0].
From there I just create a simple loop to keep adding the sum.

I know the above code will give you an undeclared variable but is it possible to do that? Or should I be looking for another method? Thanks.

2. You mentioned "one dimension array". Why not use a two dimensional array?

3. Originally Posted by chickenlittle
Is there a method to change part of the variable name? I am thinking of something like this:
int i;
i=0;
Linei[0].
No, but obviously if you change that part of the name "i" to an array, it easily becomes Line[i][0] which is doable. That is, a 2D array.

4. Wouldn't I have to use two loops in order to enter in the data with a 2-D array? The data I am getting from is from a textfile. I'm not sure how I would enter that data into a 2-D array.

5. *shrug* How is it different from having LineX where X is a number?

6. The problem I am having is how do we add numbers across the row by using a loop?
Code:
```int sum;
sum = 0;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 11; j++)
{
sum = sum + num[i][j];
}

}```

7. What is wrong with your current approach?

Popular pages Recent additions