简体   繁体   中英

Why can't I define a count variable outside of my loop in this function (C++)

This is a very basic question, I know, but I was solving the following simple exercise:

my2Darray is a two-dimensional array of doubles with nRows rows and nCols columns. Write a function that sums all the elements in each column and returns them in an array called totalsByColumn. Write a second function that sums all the elements in each row, and returns them in an array called totalsByRow.

My code works just fine now, but I was very curious as to why the following function wasn't working:

void colSum (int arrayArg[nRows][nCols]) {

    static int sumofCols[nCols] = {};
    int rowcount = 0;

    for (int i = 0; i < nCols; i++) {
        for ( ; rowcount < nRows; rowcount++) {
            sumofCols[i] += arrayArg[rowcount][i];
        }
        cout << sumofCols[i] << endl;
    }
}

Why is it that I can't create this rowcount variable outside of my nested for loops? Only the first column of the two rows from the array I used as argument to the function was being summed into sumofCols[0] , which led to sumofCols[1] to equal 0. When I set rowcount within the boundaries of either the first for loop, or the second one, the iteration works just as intended.

for (int rowcount = 0; rowcount < nRows; rowcount++)

This is the code I had to use.

I just wanted to make sure I understand 100% of what I'm doing, as C++ can be quite confusing for a beginner like me.

Oh, and I did change this function to return an int* value, as I'm basically assigning sumofCols to another array, as the exercise demands.

Because after the first iteration rowCount will be equal to nRows. And for the 2nd iteration of the outerloop it doesn't re-initialize to 0 therefore the code inside this for (; rowcount < nRows; rowcount++) loop doesn't work. You have to reset the value of rowCount to 0 after the iteration of the inner loop. If you really want to declare the rowCount outside of the loop you can do the following,

void colSum (int arrayArg[nRows][nCols]) {

    static int sumofCols[nCols] = {};
    int rowcount = 0;

    for (int i = 0; i < nCols; i++) {
        for ( ; rowcount < nRows; rowcount++) {
            sumofCols[i] += arrayArg[rowcount][i];
        }
        cout << sumofCols[i] << endl;
        rowCount = 0; // Here we are resetting the value to 0.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM