Search code examples
c++if-statementfindstdvector

Why is if statement not working in c++ function?


In this code I can find an element in vector and can print it's indices too.But if i give an input lets say 1 which is not a vector element,it doesn't print output as "Element Not Found.".The if statement after while loop is not working.

#include<bits/stdc++.h>
using namespace std;
void search(vector<vector<int>> v,int e){
    int i = 0;
    int j = v[0].size() - 1;
    int found = 0;
    while(v[i][j]){
        if(v[i][j] == e){
            found = 1;
            cout<< "Element found at: (" << i <<" , "<< j <<" )"<<endl;                
            break;
        }
        else{
            if(v[i][j] > e){
                j--;
            }
            else
                i++;
        }
    }
    if(found == 0){
        cout<< "Element Not Found."<< endl;    
    }
}
int main(){
    vector<vector<int>> v{
        {10,20,30,40},
        {15,25,35,45},
        {27,29,37,48},
        {32,33,39,50}
    };
    int e;
    cout<< "Enter the element to find:";
    cin>> e;
    search(v,e);
    return 0;
}

This is my entire code. Thanks for the tips.


Solution

  • The v[i][j] will continue to iterate until the subscript returns any non-zero value, (even if it is way out of the valid boundaries).

    You should introduce this condition into the loop:

    while(i < v[0].size() && j >= 0) ...;
    

    It would be also sane to at least introduce check for v being empty. I also want to bring attention to this part:

    // ...
    if(v[i][j] == e) {
        found = 1; // Useless statement 
        cout << "Element found at: (" << i <<" , "<< j <<" )" << endl;                
        break; // We can just place a return here
    }
    // ...
    

    There's no sense in the found update, since if the condition is true, yes, we found the sought value, we print and may return (void). So the value of the found flag won't be needed for check in the if below.

    So, in the end, I would suggest you to look toward this solution:

    void search(vector<vector<int>> v,int e){
        if (!v.size()) {
            std::cout << "Empty." << std::endl;
            return; 
        }
        int i = 0;
        int j = v[0].size() - 1;
        int found = 0;
        while(i < v[0].size() && j >= 0){
            if(v[i][j] == e){
                cout<< "Element found at: (" << i <<" , "<< j <<" )"<<endl;                
                return;
            }
            else (v[i][j] > e) ? --j : ++i; // Ternary operator 
        }
        cout << "Element Not Found." << endl;    
    }
    

    Example:

    Enter the element to find: 48
    Element found at: (2 , 3 )
    
    Enter the element to find: 42
    Element Not Found.