dimanche 13 juin 2021

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.

Aucun commentaire:

Enregistrer un commentaire