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

Hello @ashigupta.gupta570,

Observe the following code very carefully:

int i; //Staterent 1
for(int i=0;i<5;i++) //Statement 2
{
if(a[i]==search)
{
cout<<“index”<<i<<endl;
break; }
}
if (i==5) //Statement 3
{
cout<<“not present”;
}

To understand your mistake, you have to understand the scope of local and global variables:

  1. You have declared i twice in Statement 1 and statement 2.
    Where i of statement 1 would act as a global variable for the following for loop.
    i declared inside the for loop is local to that loop and it would not exist outside the loop i.e. it’s scope is limited to the for loop.

  2. Now, observe Statement 3. It is checking for the value of i which is a garbage value.
    As the i declared inside the for loop is not more exists.
    Hence, it will check for the value of i declared in statement 1.

Solution:

Hope, this would help.
Give a like, if you are satisfied.

1 Like