Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

julia
communitycreator

For vs. While loop in Julia

Sathvik

For loop

For loops are used to iterate over a series of values and perform the collection of operations defined in the body of the loop. There is no C type for the loop in Julia, i.e., for (i = 0; i < n; i++). There is a “for in” loop that is equivalent the for each loop in other languages. Let’s learn how to use sequential traversals in the loop.

Syntax:

for iterator in range
    statement/'s
end

Here, for is the keyword for the for loop, in is the keyword used to describe the context in which to iterate, and end the keyword is used to denote the end of the loop.

Example:

a = [1,2,3,4,5,6]
for i in a
    print(i, " ")
end

Nested for loop

In Julia, we can use a loop within another loop. An example is shown below.

for i in 1:3
    for j = 3:5
        println(i+j)
    end
end

While loop

The while loop is used to perform a block of statements continuously before the condition is met. Once the state become incorrect, the line will be executed immediately after the program loop. If the state is incorrect when the while loop is first executed, the loop body will never be executed.

Syntax:

while expression
    statement/'s
end

Here, while is the keyword to start while you loop, expression is the condition to be met, and end is the keyword to end the while loop.

Example:

n = 0
while n<10
  print(n, " ")
  n+=1
end

RELATED TAGS

julia
communitycreator
RELATED COURSES

View all Courses

Keep Exploring