in Programming in C edited by
644 views
0 votes
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

in Programming in C edited by
by
644 views

2 Answers

2 votes
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

selected by

4 Comments

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

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

0
0
2 votes
2 votes

answer is B  

1 comment

give explaination plz
0
0

Related questions