The program below is supposed to find the first all-zero row, if any, of an n × n matrix. Is this a correct approach to the problem, and is there another good structured approach to this code in C, or in any language in general? I'm trying to learn more about goto statements and appropriate uses/ alternatives to them. I appreciate any help!
int first_zero_row = -1; /* none */
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (A[i][j]) goto next;
}
first_zero_row = i;
break;
next: ;
}
I'm not against using goto
in some situations, but I think this can be re-written like this:
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (A[i][j]) break;
}
if (j==n) { /* the row was all zeros */
first_zero_row = i;
break;
}
}
What about using a little helper function to simplify the code in the loop:
bool is_zero_row(int* Row, int size)
{
int j;
for (j = 0; j < size; j++)
if (Row[j] != 0)
return false;
return true;
}
and then
int first_zero_row = -1; /* none */
int i;
for (i = 0; i < n; i++) {
if (is_zero_row(A[i], n))
{
first_zero_row = i;
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With