But as such both are wrong

Dark Mode

423 views

0 votes

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

2 votes

Best answer

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

0