Kara
Kara

Reputation: 785

calculating each line in 2d arrays c++

I'm trying to create an array loop using pointers. For example,

2 3 1 2 
3 1 2 2
4 3 2 2 

The number of lines are undetermined so we don't know how many lines of integers there will be. I have these data of integers stored into a pointer variable called "scores". So if I want to access them,

scores[0][0] = 2

scores[0][2] = 1

I'm trying to create a for loop where it will add each integer divide it by 2 and then add the sum up. So if I implement a function where it does this, i'd expect the value to be

4 // (2/2) + (3/2) + (1/2) + (2/2) = 4
4
5.5

This is what I have so far, but it's not working.

int *total;
int lines;
total = new int[lines]; //lines: how many lines there are (assume it is passed through a parameter)
for (int i=0;i<lines;i++) 
{
     for (int j=0;j<howmany;j++) //howmany is how many integers there are per line (assume it is passed again)
     {
         total[i] = scores[i][j] //not sure how to divide it then accumulate the sum per line and store it 

Assume that "scores" already hold the data of integers and we're extracting the data of integers elsewhere so the user does not input anything. I would want to access the calculated sum by doing total[0], total[1], etc..

Upvotes: 0

Views: 62

Answers (1)

yongzhy
yongzhy

Reputation: 977

For integer division

// (2/2) + (3/2) + (1/2) + (2/2) = 4
this will give 3, not 4

this will give you 4

// (2 + 3 + 1 + 2 ) / 2 = 4 

And you are expecting value such as 5.5, so you should define the result as float or double

float *result;
int lines = 3; // need to initialize local variable before new. for this case, we set the lines to 3.
int total;
result = new float[lines]; //lines: how many lines there are (assume it is passed through a parameter)
for (int i=0;i<lines;i++) 
{
    total = 0;

    for (int j=0;j<howmany;j++) //howmany is how many integers there are per line (assume it is passed again)
    {
        total += scores[i][j];
    }

    result[i] = (float)total/2;
}

Upvotes: 2

Related Questions