# Nesting a for loop in a while loop

**URL:** https://discourse.julialang.org/t/nesting-a-for-loop-in-a-while-loop/78336
**Category:** New to Julia
**Tags:** question, control, loops, control-flow
**Created:** [March 23, 2022, 2:51pm UTC](https://discourse.julialang.org/t/nesting-a-for-loop-in-a-while-loop/78336 "2022-03-23T14:51:32Z")
**Posts on this page:** 7
**Page:** 1

<div class="post-metadata">

### Author: ![phantom](https://avatars.discourse-cdn.com/v4/letter/p/e0b2c6/32.png) [@phantom](https://discourse.julialang.org/u/phantom)
#### Post date: [March 23, 2022, 2:51pm UTC](https://discourse.julialang.org/t/nesting-a-for-loop-in-a-while-loop/78336/1 "2022-03-23T14:51:32Z")

</div>

Hi,

I apologize if this is a very elementary mistake but I still struggling with programming and Julia. I would like to iterate through a list while a certain conditions hold true. I would also like to be able to stop the process with an outside code at any time without resorting to the ctrl c method. I thought the most intuitive way to handle this task would be to nest a for loop in a while loop.

With a while loop I can do something like this

```julia
 function sqrt(x)
    repeat = Ref(true)
    count = 0
    @async while count< 5 && repeat[]
        println(" the square root of $x is $(x^(1/2)) ")
        count+=1
        sleep(5)
    end 
    return(repeat)
end  

```

If I input a = sqrt(4) I would get something like the following

```julia
julia> b=sqrt(4)
 the square root of 4 is 2.0 
Base.RefValue{Bool}(true)
julia> the square root of 4 is 2.0 
julia> the square root of 4 is 2.0 

```

Because of the “count” condition this would continue for 5 times or I could terminate the program at anytime by entering

```julia
julia> b[]=false
false

```

However once I turn x into a list and try to iterate through it with a for loop, (nest a for loop in a while loop) it appears that the while loop conditions no longer are being tested.

e.g.

```julia
function sqrt(sets)
    repeat = Ref(true)
    count = 0
    @async while count< 5 && repeat[]
        for i in sets
            try
                println("the square root of $i is $(i^(1/2))")
                count+=1
                sleep(5)
            catch
                continue
            end 
        end 
    end 
    return(repeat)
end 

```

I get something like this.

```julia
julia> a = sqrt([4,16,25,36,81,100])
the square root of 4 is 2.0
Base.RefValue{Bool}(true)
julia> the square root of 16 is 4.0
julia> the square root of 25 is 5.0
julia> the square root of 36 is 6.0
julia> a[]=false
false
julia> the square root of 81 is 9.0
the square root of 100 is 10.0

```

As you can see the “count” condition no longer limits the lines of output and I am no longer able to terminate the program with the reference call. Consequently I assume that the conditions of the while loop are being ignored because of the way I nested the for loop. If anyone has any insights on what is happening and the proper way to approach something like this in Julia it would be greatly appreciated. Thank you.

---

<div class="post-metadata">

### Author: ![Henrique\_Becker](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/henrique_becker/32/15443_2.png) [@Henrique\_Becker](https://discourse.julialang.org/u/Henrique_Becker)
#### Post date: [March 23, 2022, 3:16pm UTC](https://discourse.julialang.org/t/nesting-a-for-loop-in-a-while-loop/78336/2 "2022-03-23T15:16:08Z")

</div>

The code seems to work as expected to me, but this comment of yours

> As you can see the “count” condition no longer limits the lines of output

makes me think that you are confused about what the code should be doing.

You have a `while` with a `for` inside, changing `repeat` (`a` outside of the function) guarantees that the `while` will not start the next iteration _of itself_ but the `while` only do a **single** iteration, in which the `for` inside it does 5 iterations.

I believe what you wanted to do is:

```julia
julia> function sqrt(sets)
           repeat = Ref(true)
           count = 1
           @async while count < 5 && repeat[]
                   i = sets[count]
                   try
                       println("the square root of $i is $(i^(1/2))")
                       count+=1
                       sleep(5)
                   catch
                       continue
                   end 
           end 
           return(repeat)
       end

```

---

<div class="post-metadata">

### Author: ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)
#### Post date: [March 23, 2022, 3:16pm UTC](https://discourse.julialang.org/t/nesting-a-for-loop-in-a-while-loop/78336/3 "2022-03-23T15:16:15Z")

</div>

> [@phantom](#):
>
> ```julia
> @async while count< 5 && repeat[]
> for i in sets
> 
> ```

The test of the condition on `repeat` is outside the for loop, so probably you need to add something like `!repeat[] && break` inside the `for` loop so it is sensible to that flag.

---

<div class="post-metadata">

### Author: ![phantom](https://avatars.discourse-cdn.com/v4/letter/p/e0b2c6/32.png) [@phantom](https://discourse.julialang.org/u/phantom)
#### Post date: [March 24, 2022, 9:48am UTC](https://discourse.julialang.org/t/nesting-a-for-loop-in-a-while-loop/78336/4 "2022-03-24T09:48:19Z")

</div>

Thank you! this really clears things up a lot. The code now gets stuck if it encounters an error. e.g. if sets = [4,16,-25,36,81] it just gets stuck at -25 as opposed to throwing an error at -25 and then continuing through the iteration. So I added a count+=1 after the catch statement. Is that the correct approach to address the issue?

```julia
julia> function sqrt(sets)
           repeat = Ref(true)
           count = 1
           @async while count < 5 && repeat[]
                   i = sets[count]
                   try
                       println("the square root of $i is $(i^(1/2))")
                       count+=1
                       sleep(5)
                   catch
                       count+=1 
                       continue
                   end 
           end 
           return(repeat)
       end

```

---

<div class="post-metadata">

### Author: ![phantom](https://avatars.discourse-cdn.com/v4/letter/p/e0b2c6/32.png) [@phantom](https://discourse.julialang.org/u/phantom)
#### Post date: [March 24, 2022, 10:12am UTC](https://discourse.julialang.org/t/nesting-a-for-loop-in-a-while-loop/78336/5 "2022-03-24T10:12:04Z")

</div>

thanks! would this be done by putting an if then statement within the for loop?

---

<div class="post-metadata">

### Author: ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)
#### Post date: [March 24, 2022, 11:40am UTC](https://discourse.julialang.org/t/nesting-a-for-loop-in-a-while-loop/78336/6 "2022-03-24T11:40:37Z")

</div>

```julia
!repeat[] && break

```

and

```julia
if !repeat[]
    break
end

```

are the same (`&&` is the circuit-breaking _and_ operator, meaning that `break` will be evaluated only if the first condition holds).

---

<div class="post-metadata">

### Author: ![Henrique\_Becker](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/henrique_becker/32/15443_2.png) [@Henrique\_Becker](https://discourse.julialang.org/u/Henrique_Becker)
#### Post date: [March 25, 2022, 12:24am UTC](https://discourse.julialang.org/t/nesting-a-for-loop-in-a-while-loop/78336/7 "2022-03-25T00:24:54Z")

</div>

I would go with:

```julia
julia> function sqrt(sets)
           repeat = Ref(true)
           count = 1
           @async while count < 5 && repeat[]
                   i = sets[count]
                   try
                       println("the square root of $i is $(i^(1/2))")
                   catch
                       println("error when tried to compute sqrt($i)")
                   finally
                       sleep(5)
                       count+=1 
                   end 
           end 
           return(repeat)
       end

```

Note that you cannot remove the `catch` and stay just with the `finally`, because otherwise the `async` thread will bubble the exception up.
