97 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

edited | 97 views

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

by Active (2.1k points)
selected by
0

@Anuj Mishra

is B) not more correct than A)?

I think B) will be exactly correct if code will be this

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


because how they could execute i==n ??

after i=(n-1), value of i will never be incremented

then how i=n possible to execute?

Am I right??

0
If the element is not present what will this code return?
0

yes, then better to take a flag

if flag==1 element found else not

like this

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


rt?

0
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
0

@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?

0

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

by (137 points)
0
give explaination plz

1