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:

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:

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

4 + twenty =