Scala program to demonstrate the break statement in while and do-while loop

Here, we are going to demonstrate the break statement in while and do-while loop in Scala programming language.
Submitted by Nidhi, on May 06, 2021 [Last updated : March 09, 2023]

Scala – Break Statement with Loops

Here, we will demonstrate the break statement in the while and do-while loop to terminate the loop during its execution based on the specific condition.

Scala code to demonstrate the example of break statement in while and do-while loops

The source code to demonstrate the break statement in the while and do-while loop is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

In the all below program, we used an object-oriented approach to create the program. We created an object Sample. We imported the scala.util.control.Breaks._ package to use the break statement.

break statement with while loop

// Scala program to demonstrate "break" statement 
// in "while" loop

// Importing  package 
import scala.util.control.Breaks._
object Sample {  
    def main(args: Array[String]) {  
        var cnt:Int=0;
        
        cnt=1;
        breakable 
        {
            while(cnt<=5)
            {
                printf("%d ",cnt);
                cnt=cnt+1;
                
                if(cnt==3)
                    break;
            }
        }
        println();
    }
} 

Output

1 2 

Explanation

Here, we created an integer variable cnt initialized with 0. We created a breakable block to use the break statement.

In the while loop, we print the value of the cnt variable. We terminate the loop using the break statement when the value of the cnt variable reaches 3.

break statement with do-while loop

// Scala program to demonstrate "break" statement 
// in "do-while" loop

// Importing  package 
import scala.util.control.Breaks._

object Sample {  
    def main(args: Array[String]) {  
        var cnt:Int=0;
        
        cnt=1;
        breakable 
        {
            do
            {
                printf("%d ",cnt);
                cnt=cnt+1;
                
                if(cnt==3)
                    break;
            }while(cnt<=5)
        }
        println();
    }
}  

Output

1 2 

Explanation

Here, we created an integer variable cnt initialized with 0. We created a breakable block to use the break statement.

In the do-while loop, we print the value of the cnt variable. We terminate the loop using the break statement when the value of the cnt variable reaches 3.

Scala Looping Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.