Doubt

#include
using namespace std;

int keyfound(int a[],int n,int key){
for(int i=0;i<n;i++){
if(a[i]==key){
return i;
break;
}
else{
return-1;
}
}
}

int main() {
int a[100];
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
int key;
cin>>key;
cout<<keyfound(a,n,key);
return 0;
}

Hello @discobot,
You are not required to put else condition for if(A[i]==key) , because if you don’t get after checking every element the loop will finish and at the end of the function you will return -1 that is element not found.
correct code will be
int keyfound(int A[],int n,int key){
for(int i=0;i<n;i++){
if(A[i]==key){
return i;//directly it will come out of loop if it returns so no need of break
}
}
return -1; ///if after trversing whole array you don’t get the element
}

Hi! To find out what I can do, say @discobot display help.

i have return the code mentioned by ta bu still my output is not correct here is the code

#include using namespace std; bool linearsearch(int key,int arr[],int n){ for(int i=0;i<n;i++){ if(arr[i]==key){ return i; } } return -1; } int main(){ int arr[100]; int n; cin>>n; for(int i = 0;i<n;i++){ cin>>arr[i]; } int key; cin>>key; cout<<linearsearch(key,arr,n); cout<<endl; return 0; }

Could you pls share the error code you are getting the whole error.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.