Casey Nelms
Casey Nelms

Reputation: 3

Multiple arrays in a function

I am trying to input multiple arrays into a function the arrays are b0[5] and b1[5]

do I declare it at the top as

double calcTotVol(double[], double[], float, int);

then receiving

double totalVol;
totalVol = calcTotVol(b0, b1, dbh, totalHt);

do I use the names of the array when creating the function

double calcTotVol(double b0[], double b1[], float dbh, int totalHt)

double totalVol;

totalVol = b0[5] + b1[5] * (dbh*dbh) * totalHt;

return totalVol;

Upvotes: 0

Views: 98

Answers (2)

rlam12
rlam12

Reputation: 603

I think this is what you are trying to do:

double calcTotVol(double b0[], double b1[], int arraySize, float dbh, int totalHt)
{
    double totalVol = 0;

    for(int i = 0; i < arraySize; i++)
    {
        totalVol += ( b0[i] + b1[i] );
    }
    float values = (dbh*dbh) * totalHt;
    totalVol *= values;

    return totalVol;
}

And a solution that is even better is replacing the c-style arrays with the new C++11 std::array type for added safety and easier usage.

Upvotes: 1

Ali Mohyudin
Ali Mohyudin

Reputation: 242

You're doing everything correctly except 'opening {' and 'closing }' braces in the given code.

1- As you asked: Do I declare it at the top as?

double calcTotVol(double[], double[], float, int);

Yes you can declare it as it is, it's called Prototype of a function in which you don't need to write down the names for variables.

2- And yes you're calling this function calcTotVol correctly in

totalVol = calcTotVol(b0, b1, dbh, totalHt);

3- You're third question is doubtful but here is a little demonstration for your doubtful question: Surely, You've to use the names of variables including the names of arrays in the function definition, without these names you'll get compile time error. And it's not required to write down the same names of variables or arrays name as your variables names that you're passing while calling your function, you can write any name as you want.

Upvotes: 0

Related Questions