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

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.