Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Why does this code not work? Obviously the return statement is never reached bec

ID: 3786670 • Letter: W

Question

Why does this code not work? Obviously the return statement is never reached because I keep getting an error that there is no return statement.

// REQUIRES: mat points to a valid Matrix
// ptr points to an element in the Matrix
// EFFECTS: Returns the row of the element pointed to by ptr.
int Matrix_row(const Matrix* mat, const int* ptr) {

   for (int r = 0; r < (mat->height); r++) {
       for (int c = 0; c < (mat->width); c++) {
           if (ptr == (&mat->data[((mat->width) * r) + c])) {
               return r;
           }
       }
   }
}

Explanation / Answer

Answer:

you have written a return statement in if block. If block executes then return statement will return the value. Let us assume If condition is met then return statement will not execute. So we have to provide anothe return statement to method level. If your condition does not meet then method level return statement will return the value.

I updatd the code and highlighted the code changes below

int Matrix_row(const Matrix* mat, const int* ptr) {

   for (int r = 0; r < (mat->height); r++) {
       for (int c = 0; c < (mat->width); c++) {
           if (ptr == (&mat->data[((mat->width) * r) + c])) {
               return r;
           }
       }
   }

return -1;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote