Hey people,

I basically want to include an if condition into my for loop, which repeats the loop with the previews iteration variable, if the condition hasn’t been satisfied.

In this case there are a few things to consider:

First, the loop hast to fill all entries of A.

Since A should be filled with values greater than 4, I wanted to implement a condition wich repeats the loop if S is smaller than 4.

In this example, A[n] equals 0, if the condition wasn’t satisfied for the n’th loop.

A = zeros(Float64,6)

counter = 1

for n = counter:length(A)

S = rand(1:10)

```
if S > 4
A[n] = S
else
n = counter -1 (obviously this didn't work)
end
```

end

print(A)

```
A = zeros(Float64,6)
for n in eachindex(A)
local S
while true
S = rand(1:10)
if S > 4; break; end
end
A[n] = S
end
print(A)
```

Should give you what you want. Note that in this concrete example `S = rand(5:10)`

could replace the `while`

loop.

Thanks for your answer!

Could you maybe explain the commands while ‘true’ and ‘local’.

Why did you make use of them?

I used `local S`

to declare a local variable named `S`

in the scope of the for loop otherwise the `while`

loop would create its own local variable `S`

that is unknown to the outer `for`

loop.

I used `while true`

because I cannot write `while S > 4`

before a value was bound to `S`

.

I could have also written

```
for n in eachindex(A)
S = rand(1:10)
while S > 4
S = rand(1:10)
end
A[n] = S
end
```

but I don’t like to write `S = rand(1:10)`

twice.

1 Like

Indeed, thank you for help !

You can still do it in a much shorter way like this:

```
A = zeros(6)
for n in eachindex(A)
while (S = rand(1:10)) < 5 end
A[n] = S
end
print(A)
```