Scala program to print numbers from 1 to 10 using while, do-while, and for loop

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

Scala – Printing numbers from 1 to 10

Here, we will print numbers from 1 to 10 using the while, do-while, and for loop on the console screen.

Scala code to print numbers from 1 to 10 using while, do-while, and for loop

The source code to print numbers from 1 to 10 using while, do-while, and for loop is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

In the below programs, 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.

Print numbers from 1 to 10 using while loop

// Scala program to implement "while" loop 
// to print numbers from 1 to 10

object Sample {  
    def main(args: Array[String]) {  
        var cnt:Int=0
        
        // Counter variable initialization
        cnt=1
        while(cnt<=10)
        {
            printf("%d ",cnt)
            // Counter variable updation
            cnt=cnt+1
        }
        println()
    }
}  

Output

1 2 3 4 5 6 7 8 9 10

Explanation

Here, we created an integer variable cnt, which is initialized with 0. we will use the cnt variable as a counter variable in the while loop. Here, we printed the value of the counter variable on the console screen till it's become 10.

Print numbers from 1 to 10 using do-while loop

// Scala program to demonstrate "do-while" loop 
// to print numbers from 1 to 10

object Sample {  
    def main(args: Array[String]) {  
        var cnt:Int=0
        
        // Counter variable initialization.
        cnt=1; 
    
        do
        {
            printf("%d ",cnt);
            cnt=cnt+1; //Counter variable updation
        }while(cnt<=10)
        
        println()
    }
}

Output

1 2 3 4 5 6 7 8 9 10

Explanation

Here, we created an integer variable cnt, which is initialized with 0. we will use the cnt variable as a counter variable in the do-while loop. Here, we printed the value of the counter variable on the console screen till it's become 10.

Print numbers from 1 to 10 using for loop

// Scala program to demonstrate "for" loop 
// to print numbers from 1 to 10

object Sample {  
    def main(args: Array[String]) {  
        for( cnt <- 1 to 10 )
        {
            printf("%d ",cnt);
        }
        println()
    }
}  

Output

1 2 3 4 5 6 7 8 9 10

Explanation

Here, we printed numbers from 1 to 10 using the to keyword in the for loop on the console screen.

Scala Looping Programs »





Comments and Discussions!

Load comments ↻





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