Julia While Loop
Julia while loop is used to iterate a set of statements over a collection of elements, like an array.
In this Julia Tutorial, we will learn how to write While Loop in Julia programs with examples.
Syntax – While Loop
The syntax of While loop in Julia is
while boolean_expression statement(s) end
where while
and end
are keywords.
Example 1 – While Loop to count
In this example, we use a while loop to print the numbers from 1 to 4.
script.jl
n = 0 while n < 4 n += 1 println(n) end
Output
1 2 3 4
Example 2 – Julia While Loop with String Array
In this example, we will use the while loop to greet all the guests, whose names are stored in a string array.
script.jl
guests = ["Ted", "Robyn", "Barney"] i = 1 while i <= length(guests) friend = myfriends[i] println("Hi $friend, good to see you!") i += 1 end
Output
Hi Ted, good to see you! Hi Robyn, good to see you! Hi Barney, good to see you!
Example 3 – Julia While Loop to Find Factorial
In this example, we will use the while loop to find the factorial of a number.
script.jl
n = 0 result = 1 while n < 4 n += 1 result *= n end println(result)
Output
24
Conclusion
In this Julia Tutorial, we learned the syntax and usage of While Loop in Julia, with the help of example scripts.