w3resource

Scala control flow program: Multiplication table using a for loop


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


Pre-Knowledge (Before you start!)

  • Basic Scala Syntax: Familiarity with writing and running Scala programs.
  • Variables in Scala: Knowledge of declaring and initializing variables using val for immutable values.
  • For Loops: Understanding how to use for loops to iterate over a range of numbers.
  • Arithmetic Operations: Ability to perform multiplication and store results in variables.
  • String Interpolation: Awareness of embedding variables within strings using s"string ${variable}".
  • Printing Output: Familiarity with the println() function to display output on the screen.

Hints (Try before looking at the solution!)

  • Define the Main Object: Create an object with a main method, which serves as the entry point of the program.
  • Initialize Variables: Declare variables to store the number for which you want to print the multiplication table and the size of the table.
  • Use a For Loop: Use a for loop to iterate from 1 to the specified table size. Calculate the product of the number and the current iteration value in each step.
  • Display the Output: Use println() to print each row of the multiplication table in the format "number * multiplier = result".
  • Test with Different Numbers: Change the value of the number and table size to verify the program works for various cases, including small and large numbers.

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?



Follow us on Facebook and Twitter for latest update.