w3resource

Scala control flow program: Multiplication table using a for loop

Scala Control Flow Exercise-6 with Solution

Write a Scala program to print the multiplication table of a given number using a for loop.

Sample Solution:

Scala Code:

object MultiplicationTable {
  def main(args: Array[String]): Unit = {
    val number: Int = 5 // Number for which you want to print the multiplication table
    val tableSize: Int = 12 // Size of the multiplication table

    println(s"Multiplication Table of $number:")
    for (i <- 1 to tableSize) {
      val product = number * i
      println(s"$number * $i = $product")
    }
  }
}

Sample Output:

Multiplication Table of 5:
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
5 * 11 = 55
5 * 12 = 60

Explanation:

In the above exercise -

First we define a variable "number" and assign it a value (5 in this case) for which we want to print the multiplication table. We also define a variable "tableSize" and assign it a value (12 in this case) which determines the size of the multiplication table.

We use a for loop to iterate from 1 to "tableSize". Inside the loop, we calculate the product of "number" and the current iteration value i and store it in the variable product. We then use println to display the multiplication expression and result.

Scala Code Editor :

Previous: Print Fibonacci series with while loop.
Next: Scala program to find the sum of array elements using a for loop.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/scala-exercises/control-flow/scala-control-flow-exercise-6.php