Scala program to implement infinite loop using while and do-while loop

Here, we are going to learn how to implement infinite loop using while and do-while loop in Scala programming language?
Submitted by Nidhi, on May 06, 2021 [Last updated : March 09, 2023]

Scala – Infinite Loop Using While and Do-while

Here, we will implement an infinite loop using the while and do-while loop and print the "hello" message infinite times on the console screen.

Scala code to implement infinite loop using while and do-while loop

The source code to implement infinite loop using 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 defined main() function. The main() function is the entry point for the program.

Implement infinite loop using while loop

// Scala program to implement infinite loop 
// using "while" loop

object Sample {  
    def main(args: Array[String]) {  
        while(true)
        {
            printf("Hello");
        }
    }
}  

Output

HelloHelloHelloHelloHelloHelloHelloHelloHelloHello
....
infinite time

Explanation

Here, we implemented the infinite loop using the while loop to print the "Hello" message infinite times on the console screen. we used the true value in the loop condition, that's why it will execute infinite times.

Implement infinite loop using do-while loop

// Scala program to implement infinite loop 
// using "do-while" loop

object Sample {  
    def main(args: Array[String]) {  
        do
        {
            printf("Hello")
        }while(true)
    }
} 

Output

HelloHelloHelloHelloHelloHelloHelloHelloHelloHello
....
infinite time

Explanation

Here, we implemented the infinite loop using the do-while loop to print the "Hello" message infinite times on the console screen. we used the true value in the loop condition, that's why it will execute infinite times.

Scala Looping Programs »





Comments and Discussions!

Load comments ↻





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