Why does "Doesn't exist" always print?

Hello,
Please take a look at the following code:

function search()
    array = [1,2,3,4,5]
    low = 0
    high = 0
    while true
        print("Please enter two numbers for Low and high index: ")
        low, high = parse.(Int, split(readline()))
        if (low <=0) || (high > length(array))
            println("Wrong range.")
        else
            break
        end
    end
    print("Please enter a number to check if it exists: ")
    n = parse.(Int, readline())
    flag = 0
    for i = low : high 
        if n == array[i]
           println("Exist.")
           break
        else
            flag += 1
        end
    end
    if flag > 0
        println("Doesn't exist.")
    end
end
search()

Why does Doesn't exist always print?

Thank you.

If you enter low = 1, high = 5 and n = 1 then it doesn’t show the Doesn't exist. message.

The issue is that flag is increased whenever the first entry is not equal to n. Instead you might want to change the logic for example like

found = false
for i = low : high 
    if n == array[i]
        println("Exist.")
        found = true
        break
   end
end
if !found
    println("Doesn't exist.")
end
4 Likes

Or just use something like

println(isnothing(findfirst(==(n), @view array[low:high])) ? "Doesn't exist" : "Exist.")

which imho is easier to get correct … the one-liner is just for fun though, e.g., multi-line if might be clearer.

1 Like

Putting the fixed bug aside,

  1. You don’t need to broadcast over scalars, n = parse(Int, readline()) is enough.
  2. Why are you hard-coding the array values and taking low, high, n from separated readline() calls instead of easier arguments for the search() call?
1 Like

Hello,
Thank you so much for your reply.
I found another way:

flag = 0
    for i = low : high 
        if n == array[i]
           println("Exist.")
           flag = 0
           break
        else
            flag +=1
        end
    end
    if flag > 0
        println("Doesn't exist.")
    end

Hello,
Do you mean the search() function with input arguments?

yes

1 Like

Mh, there is the potential edge case of an empty range, such as low = 2, high = 1, n = 10. Here your code doesn’t print anything, whereas you might either add a check low < high or print Doesn't exists.

1 Like

Hi,
Great advice.