Matrix search.kindly explain me what i am doing wrong in my code

#include
using namespace std;
int main() {
int n,m,target;
cin>>n>>m;
int a[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>a[i][j];
}
}
cin>>target;
for(int i=0;i<n;i++){
for(int j=m-1;j>=0;j–){
if(a[i][j]==target){
cout<<1;
break;
}
else if(a[i][j]>target){
j–;
}
else{
i++;
}
}
}
cout<<0;

return 0;

}

Hey @Prabhleen_sheenu,

Always share your code using some Online IDE.
The way you share it has introduced many syntax errors to it.

STEPS:

  1. Paste the code at https://ide.codingblocks.com/
  2. Save it there.
  3. Share the URL generated.

Mistake in your code:
Wrong selection of loops:
for(int i=0;i<n;i++){
for(int j=m-1;j>=0;j–){
This will lead the traversal of the matrix in a fixed way.

Solution:
Rather you the while loop as:
int i=0;
int j=m-1;
while(i<m && j>=0){}

Hope, this would help.

Hey @Prabhleen_sheenu,

Please, check my last response. I have shared some steps.
Follow that and share your code.

1 Like

using while loop

using 2 foor loops

sir can you please explain why for loops is giving error and while loop is giving correct ans.thanks :slight_smile:

Hello @Prabhleen_sheenu,

This is because of the order in which you are accessing the elements of the matrix.

To understand the difference better, i would suggest you to dry run both the codes for same input using pen on paper.

That will help you to understand your mistake.

hello
i am accessing elements in this order because first i will check if my target is equal to a[0][m-1]
sorry to bother you sir but i am not understanding this

Hello @Prabhleen_sheenu,

No problem.
I will explain to you in brief.

In the case of while loop:
the loop will terminate when

  1. you will find the target element i.e. achieved using the break statement.
  2. or you will go out of the range i.e is achieved by the condition mentioned inside the while loop i<m && j>=0.

Also, the movement i.e. left and down will be decided by the else if and else statements inside the while loop.
Reason:
we are changing the value of index inside that.

In the case of for loop:
for(int i=0;i<n;i++){
for(int j=m-1;j>=0;j–){
the above mentioned nested loop will iterarte the matrix row by row and each row will traversed from right to left as the initial indeces are i=0 and j=m-1 and after each iteration we are decrementing j and incrementing i.
But, the else if and else conditions inside will also affect the movement.

This way the entire execution will become ambiguous and hence, not searching in step case fashion.

Hope, this would help.

1 Like

Ohh now i got it .thank you so much sir :slight_smile: :slight_smile: