Problem: Write a C program to search an element in the two-dimensional array. If present then prints its “Index position” otherwise output “Not Found”.

Example:

Input:
{1, 2, 3},
{4, 5, 5},
{5, 6, 5}

Search Element: 5

Output:
(1,1)
(1,2)
(2,0)
(2,2)

Input:
{1, 2, 3},
{4, 5, 5},
{5, 6, 5}

Search Element: 9

Output: Not Found

To search an element in a 2D array, we traverse the array using nested ‘for’ loops and match the search element with each element of the 2D array just like the linear search.

Steps to follow to search an element in a 2D array:

  1. Create an array and initialize it with the elements.
  2. Input the search element.
  3. For loop from i=0 to i<rows:
    1. For loop from j=0 to j<columns:
      1. Check if search_element==array[i][j]:
        1. If yes then output the row and column index position (i.e. (i, j)).
  4. If not a single match was found then output ‘Not Found’.

Here is the implementation of the steps in the C:

#include<stdio.h>

int main(){
  int rows, columns, srchElement, count=0;

  //enter the order of matrix
  printf("Enter the number of Row and Column: \n");
  scanf("%d %d", &rows, &columns);

  //create a 2D array of the same order
  int array[rows][columns];

  //Take inputs into the 2D array
  printf("Enter %d elements: \n", (rows*columns));
  for(int i=0; i<rows; i++){
    for(int j=0; j<columns; j++){
      scanf("%d", &array[i][j]);
    }
  }

  //Enter the search element
  printf("Enter the element to get the position: \n");
  scanf("%d", &srchElement);

  for(int i=0; i<rows; i++){
    for(int j=0; j<columns; j++){
      if(array[i][j] == srchElement){
        /*
          *If a match is found, then output the
          *position and increment the count
        */
        printf("(%d, %d) \n", i, j);
        count++;
      }
    }
  }

  /*
    *If count remains 0, it means- 
    *the array doesn't had the search element
  */
  if(count==0)
    printf("Not found \n");

  return 0;
}

Output 1:

Enter the number of Row and Column:
3 3
Enter the 9 elements:
1 2 3
4 5 5
5 6 5
Enter the element to get the position:
5
(1,1)
(1,2)
(2,0)
(2,2)


Output 2:

Enter the number of Row and Column:
3 3
Enter the 9 elements:
1 2 3
4 5 5
5 6 5
Enter the element to get the position:
9
Not Found


In the above program, we have used count variable to store the number of occurrences of the search element in the array.

After search operation (i.e. nested for loops) is over, if the count value remains zero it means that the array does not have the corresponding search element, so we output ‘Not Fount’.

In this tutorial, we learned to search an element in a two-dimensional array in the C programming language. If you have any suggestions or doubts then comment below.

Leave a Reply