Conteúdo do Curso
Introduction to Scala
Introduction to Scala
While Loop
Introduction to Loops
Programming in many ways is similar to our real life where we have to perform different instructions to achieve certain results. However, it's often the case that these instructions are repetitive, which can be tedious and routine work. Fortunately, Scala, like many other programming languages, spares us from writing the same lines of code millions of times by providing loops.
In fact, there are several types of loops in Scala:
- while loops;
- do while loops;
- for loops.
Each has its own way of defining the start and end conditions for the repetition.
What is a While Loop?
A while loop repeatedly executes specific statements (which can include other loops, conditional statements, etc.) as long as a given condition is true
. Let's take a look at the general syntax:
Main
while (condition) { // Statement(s) to execute }
First, the condition is checked and only if it is true
the code within the loop body is executed.
Examples
As you can see, there is absolutely nothing complicated here. Let's now take a look at an example. Suppose, we want to print Hello five times. Here's how we can accomplish it with a while loop:
Main
object Main { def main(args: Array[String]): Unit = { var i = 0 while (i < 5) { println("Hello") i += 1 } } }
In our case, the loop body is executed five times, as expected. When i
goes from 0
to 4
, it is less than 5
, so the condition is true
. When i
becomes equal to 5
, the condition is false
, so the loop is terminated.
In general, however, a loop variable is referred to as iterator.
Let's take a look at our example once again where we print the value of i
at each iteration (step of the loop) to clarify everything:
Main
object Main { def main(args: Array[String]): Unit = { var i = 0 while (i < 5) { println("Hello") println(i) i += 1 } } }
Otherwise, if the condition is always true
, we'll get an infinite loop (the loop will run infinitely).
Here is another example of a while loop where we use it for creating a countdown from 10
to 1
:
Main
object Main { def main(args: Array[String]): Unit = { var i = 10 while (i > 0) { println(i) i -= 1 } } }
Obrigado pelo seu feedback!