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:
-
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.
-
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.