Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
While Loop | Conditional Statements and Loops
Introduction to Scala
course content

Course Content

Introduction to Scala

Introduction to Scala

1. Getting Started
2. Variables and Data Types
3. Conditional Statements and Loops
4. Arrays
5. Strings

bookWhile 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:

java

Main

copy
123
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:

java

Main

copy
123456789
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:

java

Main

copy
1234567891011
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:

java

Main

copy
123456789
object Main { def main(args: Array[String]): Unit = { var i = 10 while (i > 0) { println(i) i -= 1 } } }
How many times will the word "Scala" be printed?

How many times will the word "Scala" be printed?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 4
some-alt