Home » Scala language

How to call method N times in Scala?

Calling method N times in Scala: Here, we will learn about the methods like how to call a method a specified number of times in Scala using a functional method or other methods?
Submitted by Shivang Yadav, on August 01, 2019

Calling a method in Scala: simply call the function using a method call in Scala, but, calling method N times can be done using either of the two ways:

  1. Using iteration
  2. Using recursion

1) Calling method N times using iteration

A simple logic to call a method n times is using on a loop that runs n times. And at each iteration, the loop calls the method. So, the same method is called n times.

Example:

Calling a method 5 times that prints "I love includeHelp" using a loop:

object MyClass {
    def printStatement(){
        println("I love includeHelp"); 
    }
    
    def main(args: Array[String]) {
        val n = 5; 
        
        for(i <- 1 to n){
            printStatement();
        }
    }
}

Output

I love includeHelp
I love includeHelp
I love includeHelp
I love includeHelp
I love includeHelp

2) Calling method N times using recursion

Another logic to call a method n times is using recursion, with parameter as the remaining numbers of time the function is to be run. At each call, the number value passed is decreased by one and the function's recursive call ends when 1 is encounters at n.

Example:

Calling a method 5 times that prints "I love includeHelp" using a recursion :

object MyClass {
    def printStatement( n: Int){
        println("I love includeHelp"); 
        if(n!= 1 ){
            printStatement(n-1);
        }
    }
    
    def main(args: Array[String]) {
        val n = 5; 
        printStatement(n);
    }
}

Output

I love includeHelp
I love includeHelp
I love includeHelp
I love includeHelp
I love includeHelp



Comments and Discussions!

Load comments ↻






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