While-loop in Julia

While-loop is a control flow statement, used to execute a set of statements as long as this given control condition holds true. It falls under the indefinite iteration category.

Content

  1. Intorduction to While-loop in Julia
  2. Break Statement
  3. Continue Statement
  4. Practice Exercise

1. Introduction to While-loop in Julia

While-loop is a control flow statement, used to execute a set of statements as long as this given control condition holds true. It falls under the indefinite iteration category. When the number of iterations is not specified explicitly in advance, it’s called indefinite iteration.

While-loop in Julia follows the similar syntax to the while-loop in Python and R. An end statement is required to end the loop, this is the major difference as compared to that of Python and R

Let’s have a look at the syntax :

Syntax of a while loop

while condition is true
    # do something here
    # make sure the logic breaks the condition at some point
    # else results in infinite loop
end

Let’s understand while loop with a simple example.

# Print all negative numbers greater than equal to the given number `-5`
num = -5
while num < 0
    println(num)
    num += 1
end
# Output : 
-5
-4
-3
-2
-1

2. Break Statement

Break statement is a loop control statement, used to stop the while-loop even before the control statement becomes false.

Let me explain it with an example.

# Print all the square numbers of 1 to 20, but make sure the squared numbers are less than 100
num = 1
while num < 20
    sq_num = num*num
    if sq_num > 100
        break
    end
    println(sq_num)
    num += 1
end
# Output :
1
4
9
16
25
36
49
64
81
100

Without the break keyword, the above while-loop would iterate up to 20. This loop is exited early by using a break statement.

You have seen how to break a loop over some specific condition with the break statement. What if you wish to continue a loop over some specific condition. Let’ see how to do that.

3. Continue Statement

Continue statement is a loop control statement, used to stop an iteration and move to the next one immediately.

Let me explain it with an example.

# Print all the multiples of 3 which are less than 10
num = 1     
while num < 10  
    num += 1
    if num % 3 != 0
        continue
    end
    println(num)
end
# Output :
3
6
9

4. Practice Exercises

Q1. Count the total digits in a given number

num = 1236789
count = 0
while num != 0
    num ÷= 10
    count+= 1
end
println("Total digits are: ", count)
# Output :
Total digits are: 7

Q2. Find factorial of a number

num = 6
fac = 1
if num == 0
    println(1)
else
    while num >= 1
        fac = fac*num
        num -= 1
    end
    println(fac)
end
# Output :
720

Conclusion

So, now you should have a fair idea of how to execute while-loops in Julia. Next, I will see you with more Data Science oriented topics in Julia.

Read more about Julia here