The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
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++);
        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 by Veteran (116k points)
edited by | 97 views

2 Answers

+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

by Active (2.1k points)
selected by

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

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

yes, then better to take a flag

if flag==1 element found else not

like this

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


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

+2 votes

answer is B  

by (137 points)
give explaination plz

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,339 questions
55,763 answers
90,771 users