Menu
Coddy logo textTech

Searching in 2D Array

Lesson 11 of 26 in Coddy's Arrays in C++ course.

Searching in a 2D array or matrix is similar to that searching in a 1D array. We have to iterate through each element and if it is present in the matrix then we have to return true else false.

Use nested loops to iterate using variables i and j

for(int i=0;i<m;i++){
  for(int j=0;j<n;j++){
    if(arr[i][j]==key){
      return true;
    }
  }
}
return false;

Time complexity Analysis

As we are using a loop inside a loop that means we have to iterate through n elements n times, which makes its complexity O(n2).

challenge icon

Challenge

Given a matrix and its no. of rows and columns, print the square of elements if the sum of its indices is even.

eg arr[1][3] then 1+3=4 which is even then square that element and print the other elements as it is.

Try it yourself

#include<iostream>
using namespace std;


int main(){
  
  int m,n;
  cin>>m>>n;

for(int i=0;i<m;i++){
  for(int j=0;j<n;j++){
    
    cin>>arr[i][j];
    
  }
}


//Code here




return 0;

}

All lessons in Arrays in C++