Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala

What is a while loop in Scala?

Hassaan Waqar

Scala, short for Scalable Language, combines features of object-oriented and functional languages to improve application scalability and reliability.

Scala is based on Java. Hence, the syntax is similar. We can consider a Scala program as a collection of objects that call each others’ methods.

While loops

A while loop is used when a portion of code needs to be run repeatedly until a condition is satisfied.

The basic syntax of a while loop is as follows:

while(condition){
   line(s) of code;
}

The flowchart below shows how a while loop works:

How a while loop works

A while loop checks whether a particular condition is true. If it is, code inside the loop is executed. On completion, the condition is rechecked, and the process repeats. If the condition is false, the loop ends.

Example

The code snippet below shows a while loop in Scala:

object Loop {
   def main(args: Array[String]) {
      var x = 1;
      // while loop begins
      while( x < 5 ){
         println( "Value of x: " + x );
         x = x + 1; // incrementing value of x
      }
   }
}

An infinite loop occurs when the condition of a while loop is never false. The loop does not terminate, leading to an error.

RELATED TAGS

scala

CONTRIBUTOR

Hassaan Waqar
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring