Searching doubt

#include
using namespace std;
int main()
{
int a[5],search;
cin>>search;
cout<<“enter the elements”<<endl;
for(int i=0;i<5;i++)
cin>>a[i];
cout<<“elements are =”;
for(int i=0;i<5;i++)
{
cout<<a[i]<<’,’;
}
cout<<endl;
int i;
for(int i=0;i<5;i++)
{
if(a[i]==search)
{
cout<<“index”<<i<<endl;
break; }
}
if (i==5)
{
cout<<“not present”;
}

return 0;
}

what is wrong in this my not present message is not printing

@ashigupta.gupta570
This problem is occuring as you are declaring the variable ‘i’ again in loop.
When you declared variable int i ; and then you started a loop after that , you shouldn’t declare it again or otherwise these two variables will be independent and variable declared inside the loop would get incremented in the loop and as the loop breaks , it will go on and check if (i==5) . But however , the comparison made in this statement will be between 5 and the outer i . Since the value of outer i was never declared or changed , it would give you wrong answer. To correct this , do not declare a different instance of variable of i in the loop .

int i;
for(i=0;i<5;i++)

1 Like

thanks a lot sir it really helped

@ashigupta.gupta570
You’re welcome. Kindly mark this doubt as resolved in your Doubts Section if your issue is solved.

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.