Scala control flow Program: Find a factorial with a while loop
Write a Scala program to find the factorial of a given number using a while 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 var for mutable values.
- While Loops: Understanding how to use while loops for repetitive tasks.
- Arithmetic Operations: Ability to perform multiplication and decrement operations.
- 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 a variable to store the number for which you want to calculate the factorial. Initialize another variable to store the factorial result, starting with 1.
- Use a While Loop: Use a while loop to iterate from the given number down to 1. Multiply the current factorial value with the loop variable in each iteration.
- Decrement the Counter: Decrease the loop variable by 1 in each iteration to move toward the base case.
- Display the Output: Use println() to print the calculated factorial in a readable format, including the number in the output message.
- Test with Different Numbers: Change the input number to verify the program works for various cases, including edge cases like 0 or large numbers.
- Common Errors to Avoid:
- Forgetting to initialize the factorial variable as 1, leading to incorrect results.
- Misplacing the decrement logic, causing infinite loops or incorrect calculations.
- Not handling edge cases like 0, which should return 1 as the factorial of 0 is defined as 1.
Sample Solution:
Scala Code:
object FactorialCalculator {
def main(args: Array[String]): Unit = {
val number: Int = 4 // Number for which you want to find the factorial
var factorial: Long = 1 // Initialize the factorial variable as 1
var i: Int = number
while (i > 0) {
factorial *= i
i -= 1
}
println(s"The factorial of $number is: $factorial")
}
}
Sample Output:
The factorial of 4 is: 24
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 find the factorial. We initialize a variable factorial as 1 since the factorial of 0 is defined as 1. We also initialize a variable i with the value of "number".
- Inside the while loop, we multiply the current factorial value with i and store the result back in factorial. Then, we decrement the value of i by 1.
- The loop continues until i becomes 0. When the loop finishes, we print the result using println, which displays the factorial.
Scala Code Editor :
Previous: Scala control flow program to check even or odd number.
Next: Print Fibonacci series with while loop.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics