So let’s now see an example where we can put our while loop to use, type the program below and execute it. Change the value of number and see. This program finds if a number is prime or not.

number = 71

counter = 2

while number % counter != 0
    counter += 1
end

if number != counter
    print(number, " is not prime")
else
    print(number, " is prime")
end

Output:

71 is prime

Let’s see how it works. If you know math, then you would know that primes are divisible only by 1 and it self. So if any number is prime then it gives a non zero reminder if it divided by any other number other than itself or 1. In the above program that’s what we do. We have a variable counter and we set it to 2 here counter = 2, next we have this code block:

while number % counter != 0
    counter += 1
end

now look at the condition, if the number is prime and not 2, this condition number % counter != 0 will be true, and if you are wondering != stands for, it stands for not equal to in programming. So if the condition is true, the code between while and end executes, hence counter now becomes 3 by executing counter += 1, and once again 71 % 3 is not zero and so again counter increments and in next iteration it is 71 % 4 and so on. The loop ends when counter is 71, where 71 % 71 is 0 and hence number % counter != 0 fails and the program control comes out of the while.

It (the program execution) now encounters this:

if number != counter
    print(number, " is not prime")
else
    print(number, " is prime")
end

Here in the above piece of code if the number is not equal to counter we print it’s not a prime, but when it is, we print is as prime.

The notebook for this blog can be found here: https://gitlab.com/data-science-with-julia/code/-/blob/master/while.ipynb.