Pages

Thursday, April 17, 2025

Search in Sorted matrix(code) in C++ (2D Arrays)

#include<iostream>
using namespace std;

bool search(int arr[][4], int n, int m, int key) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (arr[i][j] == key) {
                cout << "found at cell [" << i << "][" << j << "]" << endl;
                return true;
            }
        }
    }
    cout << "no keys are found" << endl;
    return false;
}

int main() {
    int arr[4][4] = {
        {10, 20, 30, 40},
        {22, 45, 35, 36},
        {34, 33, 64, 92},
        {23, 39, 87, 67}
    };

    search(arr, 4, 4, 64);  // rows = 4, cols = 4, key = 33

    return 0;
}


Facing some errors-
1. Not able to identify correct position of row and column.

Mistakes done while writing this code-

🧠 Key Fixes (While Keeping Your Style):

IssueFix
int arr[10] = {{...}};Changed to int arr[4][4] = {...};
int m; used but not initializedAdded int m = 4;
if (int arr[i][j] == n)Changed to if (arr[i][j] == n)
Closing ) in last rowFixed to }
search(4, 4, 33);Changed to search(arr, 4); and passed key via n parameter
else prints "no keys are found" every loopKept, but note it will print many times unless key is found early

No comments:

Post a Comment

Stack using Linked List – Partial (University Exam Topic)

 #include <iostream> using namespace std; struct Node {     int data;     Node* next; }; class Stack {     Node* top; public:     Stac...