423 views

Consider the function give below, which should return the index of first zero in input array of length $n$ if present else return $-1.$

int index of zero(int[ ] array,int n){
for(int i=0;  P  ;i++);
if(i==n){
return -1;
}
return i;
}

What should be placed in place code at ‘P’,So that code will work fine?

$A)$array[i]!=0 && i<=n

$B)$ array[i]!=0 && i<n

B would be correct answer if we just reverse array[i]!=0 && i<n to  i<n&&array[i]!=0 now it will not give segmentation fault as when i=n it'll break out without executing array[n]!=0 which will give index out of bound error

A is totally incorrect here, it'll give error and after loop execution, i will be n+1, thus no way of -1 anyhow

The flag idea is correct but code is wrong(if you dry run or actual run you'll  notice), but i guess you do know the right code,
But as such both are wrong

@Anuj Mishra

option A) is not correct

because, int n means n numbers in it

now, if u perform

for(int i=0; array[i]!=0 && i<=n ;i++);

it will execute (n+1) numbers , that is why it is not correct.

i guess you do know the right code,

means? I donot know any code for it. :)

Do it has any code format?

Sorry @srestha for misleading you, I might have overlooked code, corrected my answer now

### 1 comment

give explaination plz