HI,
I am trying to write a nested for loop, and I am not getting the desired output. Possibly I am making some mistakes, and there must be other ways to solve this problem. I am writing down the part of my code.
for i=1:5
for j=i+1:5
if (i+j)%4!=0
println("i=",i,",j=",j)
else
i=j
break
end
end
end
To me the code does what I would expect it to do (also Julia novice). Printing out where are i+j is not divisible by 4 (and j>i). What is the “rule” that you intended?
I believe a more idiomatic and compact way to write this would be
[(;i=i, j=j) for i in 1:5, j in 1:5 if j>i & (i+j)%4!=0]
I think the problem is that you are trying to assign values to i
See this part from the Julia documentation
Multiple nested for loops can be combined into a single outer loop, forming the cartesian product of its iterables:
julia> for i = 1:2, j = 3:4
println((i, j))
end
(1, 3)
(1, 4)
(2, 3)
(2, 4)
With this syntax, iterables may still refer to outer loop variables; e.g. for i = 1:n, j = 1:i is valid. However a break statement inside such a loop exits the entire nest of loops, not just the inner one. Both variables (i and j) are set to their current iteration values each time the inner loop runs. Therefore, assignments to i will not be visible to subsequent iterations: