티스토리 뷰
Loops¶
Reference¶
https://github.com/JuliaComputing/JuliaBoxTutorials/tree/master/introductory-tutorials/intro-to-julia (github : JuliaComputing/JuliaBoxTutorials/introductory-tutorials/intro-to-julia/)
Topics:
Series¶
- http://deepstat.tistory.com/45 (01. Getting started)(in English)
- http://deepstat.tistory.com/46 (01. Getting started(한글))
- http://deepstat.tistory.com/47 (02. Strings)(in English)
- http://deepstat.tistory.com/48 (02. Strings(한글))
- http://deepstat.tistory.com/49 (03. Data structures)(in English)
- http://deepstat.tistory.com/50 (03. Data structures(한글))
- http://deepstat.tistory.com/52 (04. Loops(한글))
while loops ¶
Syntax:
<font color=green>while<\font> *condition*
*loop body*
<font color=green>end<\font>
For example, we could use while to count or to iterate over an array.
n = 0
while n < 10
n += 1
println(n)
end
n
myfriends = ["Ted", "Robyn", "Barney", "Lily", "Marshall"]
i = 1
while i <= length(myfriends)
friend = myfriends[i]
println("Hi $friend, it's great to see you!")
i += 1
end
for loops ¶
Syntax:
<font color=green>for<\font> *var* <font color=green>in<\font> *loop iterable*
*loop body*
<font color=green>end<\font>
We could use a for loop to generate the same results as either of the examples above:
for n in 1:10
println(n)
end
myfriends = ["Ted", "Robyn", "Barney", "Lily", "Marshall"]
for friend in myfriends
println("Hi $friend, it's great to see you!")
end
Now let's use for loops to create some addition tables, where the value of every entry is the sum of its row and column indices.
First, we initialize an array with zeros.
m, n = 5, 5
A = fill(0, (m, n))
for i in 1:m
for j in 1:n
A[i, j] = i + j
end
end
A
Here's some syntactic sugar for the same nested for loop
B = fill(0, (m, n))
for i in 1:m, j in 1:n
B[i, j] = i + j
end
B
The more "Julia" way to create this addition table would have been with an array comprehension.
C = [i + j for i in 1:m, j in 1:n]
Exercises ¶
4.1¶
Loop over integers between 1 and 100 and print their squares.
n = 0
while n < 100
n += 1
print("$(n^2) ")
end
for n in 1:100
print("$(n^2) ")
end
4.2¶
Add to the code above a bit to create a dictionary, squares that holds integers and their squares as key, value pairs such that
squares[10] == 100
squares1 = Dict(i => i^2 for i in 1:100)
squares1[10] == 100
squares2 = Dict()
n = 0
while n < 100
n += 1
squares2[n] = n^2
end
squares2
squares2[10] == 100
squares3 = Dict()
for n in 1:100
squares3[n] = n^2
end
squares3
squares3[10] == 100
4.3¶
Use an array comprehension to create an an array that stores the squares for all integers between 1 and 100.
n_sq = [i^2 for i in 1:100]
println(n_sq)
'Flux in Julia > Learning Julia (Intro_to_Julia)' 카테고리의 다른 글
05. Conditionals (0) | 2018.09.18 |
---|---|
04. Loops (한글) (0) | 2018.09.15 |
03. Data structures (한글) (0) | 2018.09.13 |
03. Data structures (0) | 2018.09.13 |
02. Strings (한글) (0) | 2018.09.12 |