Let us learn to search an element from a 2-D Array using C Programming Language

in hive-175254 •  2 years ago 

Welcome back,
Today we are going to perform a search operation in a 2-D Array or matrix, we have already done this for a 1D Array so make sure to revisit that blog in case you want a revise the topic.

Here is the code itself.

Screenshot 2023-01-28 194346.png

Code continued

Screenshot 2023-01-28 194408.png

#include <stdio.h>

#define ROWS 3
#define COLS 3

void search(int array[ROWS][COLS], int element) {
int i, j;
int found = 0;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
if (array[i][j] == element) {
printf("Element %d found at position (%d, %d)\n", element, i, j);
found = 1;
break;
}
}
}
if (!found) {
printf("Element not found in the array\n");
}
}

int main() {
int array[ROWS][COLS];
int i, j;
int element;

printf("Enter elements of the array:\n");
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
scanf("%d", &array[i][j]);
}
}

printf("Enter the element to search: ");
scanf("%d", &element);
search(array, element);

return 0;
}

The program first defines the size of the 2-D array as ROWS and COLS. The size of the array is defined as 3x3 in this example.

The main function takes input of elements of array from user and then calls the function search() and passes the array and element to be searched. The search() function iterates through each element of the array using nested for loops, comparing each element to the search element.

If a match is found, the position of the element is printed, and the found variable is set to 1. If the element is not found in the array, the message "Element not found in the array" is printed.

Let us look at the output now.

image.png

As you can see we were successfull in finding the element at the correct position of the element searched. Don't get confused as the row and column number starts from 0 and not 1.

If you also want to learn coding then find your teacher according to your language. For me i am comfortable with hindi language and follow hindi teachers.

You can refer to my teacher below in case you are also comfortable with hindi.

Source

I will soon call myself a trader and a small programmer together.

Happy trading and keep learning what you love.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!