UndefVarError: ncounter

I am new to Julia. How do I fix this function?

function count(word, ltr)
ncounter = 0;
for letter in word
if letter == “a”
global ncounter = ncounter + 1

    end
    result = ncounter 
end
return result

end

wcount = count(“banana”,‘a’)

julia> include(“scratchpad.jl”)
ERROR: LoadError: UndefVarError: ncounter not defined
Stacktrace:
[1] count(::String, ::Char) at c:\Projects\PHYBUDGET\pam4_j\scratchpad.jl:9
[2] top-level scope at c:\Projects\PHYBUDGET\pam4_j\scratchpad.jl:14
[3] include(::String) at .\client.jl:457
[4] top-level scope at REPL[2]:1
in expression starting at c:\Projects\PHYBUDGET\pam4_j\scratchpad.jl:14

This works:

       wcount = count("banana",'a')
0

julia> function count(word, ltr)
       ncounter = 0;
       for letter in word
         if letter == 'a'
           ncounter = ncounter + 1
         end
       end
       return ncounter

       end

       wcount = count("banana",'a')
3

You should have a read through the scope-section of the manual. Essentially the first ncounter created a variable local to the scope of the function, wherease the second one created a global one. Thus it did not find the local one you initialised before.

Also have a look at Please read: make it easier to help you, in particular on how to quote your code in discourse. Have fun learning Julia!

3 Likes