Gavin Youker Gavin Youker - 2 months ago 8
C++ Question

Changing Values of a Row in a 2D Array Using For Loops

I have a function called

zero_row
. This function inserts the value of zero into all a row that is specified. The function takes to variables.
a
(the array) and
row
(the row in the array). Here is my function

void zero_row (int a [4][5], int row){
for (int i = 0; i < 4; i++) {
a[i][j] = 0;
}
}


I know how to set values of the entire array to zero. As i have a function to do this as well.

void zero_all (int a [4][5]) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
my_arr[i][j] = 0;
}
}
}


I cant seem to figure out how to do this using the variable
row
. I want to use this variable so I can later change the row in my main function, like so:
zero_row(a, 3);
. Can anyone help?

Thanks!

Answer

In your case the first index corresponds to a row and the second index corresponds to a column.

Use

void zero_row (int a [4][5], int row){
    for (int j = 0; j < 5; j++) {  // 5 instead of 4
        a[row][j] = 0;
    }
}