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

Write a C function linearSearch2D that takes a 2D int array and an integer value

ID: 3582222 • Letter: W

Question

Write a C function linearSearch2D that takes a 2D int array and an integer value to be searched in the

    array. The function returns the row and column indexes of the first element in the array that equals

    to the search value (Note: search the array column-wise). If the search is not successful, the

    function returns -1 and -1 for the row and column index.

    Write a main function to test the linearSearch2D function. Use the dimensions 4 * 3 for your

    2D-array.

    Sample program runs

Enter the elements of a 4 3 i nt array row-Wise: 5 1 8 7 1 5 Enter the integer value to search for 8 The value 8 exists in the array at Crow 2, column 0)

Explanation / Answer

#include<stdio.h>
#define ROWS 4
#define COLS 3
//function prototype to search element in a matrix and return first matched element's row and col in pointer variable //row and col
void linearSearch2D(int matrix[][COLS], int search, int *row, int *col);
int main()
{
   //declare 2-D array of int
   int matrix[ROWS][COLS];
   int i, j, row, col,search;

   printf("Enter the elements of %d * %d int array row-wise: ",ROWS,COLS);
   for (i = 0; i < ROWS; i++)
   {
       for (j = 0; j < COLS; j++)
           scanf("%d", &matrix[i][j]);
   }

   printf("Enter the integer value to be searched: ");
   scanf("%d", &search);
  
   linearSearch2D(matrix, search, &row, &col);
   if (row >=0 && col >= 0)
   {
       printf("The value %d exists in the array at (row %d,col %d) ", search, row, col);
   }
   else
   {
       printf("The value %d does not exists in the array ", search);
   }
}

void linearSearch2D(int matrix[][COLS], int search, int *row, int *col)
{
   int i, j;

   for (i = 0; i < COLS; i++)
   {
       for (j = 0; j < ROWS; j++)
       {
           if (matrix[j][i] == search)
           {
               *row = j;
               *col = i;
               return;
           }
       }
   }

   *row = -1;
   *col = -1;
   return;
}

------------------------------------------------------------------------------------------------------

output:

Enter the elements of 4 * 3 int array row-wise:
5 3 1
2 8 4
8 4 7
1 3 5
Enter the integer value to be searched: 8
The value 8 exists in the array at (row 2,col 0)

output2:

Enter the elements of 4 * 3 int array row-wise:
1 2 3
4 5 6
7 8 9
10 11 12
Enter the integer value to be searched: 15
The value 15 does not exists in the array

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