# Scope of variables

**URL:** <https://discourse.julialang.org/t/scope-of-variables/88957>\
**Category:** New to Julia\
**Tags:** scope\
**Created:** [October 19, 2022, 11:40am UTC](https://discourse.julialang.org/t/scope-of-variables/88957 "2022-10-19T11:40:04Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![jrocha](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jrocha/32/30491_2.png) [@jrocha](https://discourse.julialang.org/u/jrocha)\
**Post date:** [October 19, 2022, 11:40am UTC](https://discourse.julialang.org/t/scope-of-variables/88957/1 "2022-10-19T11:40:04Z")

</div>

Hi,  
I’m having trouble to define the scope of a variable in a simple Lagrange interpolation code, i got this “UndefVarError: i not defined”. I wonder how can i define this “i” variable, it should be local as it is used in a for loop.  
The code is something like this:

```julia
x = [-2.0, -1.0, 0.0, 1.0, 2.0]
y = [-9.0, -15.0, -5.0, -3.0, 39.0]

println("Enter number of terms")
n = parse(Int32, readline())

println("Enter xx for interpolation")
k = parse(Int32, readline())

s = 0.0

for i = 1:n
    p = 1.0
    for j = 1:n
        if(i != j)
            p = p + ((k - x[i]) / (x[i] - x[j]))
        end
    end
end

s = s + (p * y[i])
println(s)

```

Thanks in advance.  
Cheers,  
João Rocha

---

<div class="post-metadata">

**Author:** ![oheil](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oheil/32/220745_2.png) [@oheil](https://discourse.julialang.org/u/oheil)\
**Post date:** [October 19, 2022, 11:47am UTC](https://discourse.julialang.org/t/scope-of-variables/88957/2 "2022-10-19T11:47:25Z")

</div>

> [@jrocha](#):
>
> s = s + (p \* y[i])

`i` is not defined here and I can’t see which value of `i` you expect.

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [October 19, 2022, 12:21pm UTC](https://discourse.julialang.org/t/scope-of-variables/88957/3 "2022-10-19T12:21:05Z")

</div>

> [@jrocha](#):
>
> `s = s + (p * y[i])`

The loop variable `i` is not defined outside the body of the loop (unless you use the [`outer` keyword](https://docs.julialang.org/en/v1/manual/variables-and-scoping/#Loops-and-Comprehensions)).

---

<div class="post-metadata">

**Author:** ![jrocha](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jrocha/32/30491_2.png) [@jrocha](https://discourse.julialang.org/u/jrocha)\
**Post date:** [October 19, 2022, 2:33pm UTC](https://discourse.julialang.org/t/scope-of-variables/88957/4 "2022-10-19T14:33:10Z")

</div>

Thanks @oheil and @stevengj, of course it could not work outside the loop. It skiped me. It works now.  
Thank once more.  
Cheers.
