Kotlin Function: Print numbers from 1 to n, Return Unit
Write a Kotlin function that takes an integer n as an argument and prints the numbers from 1 to n on separate lines. The function should return Unit.
Sample Solution:
Kotlin Code:
fun printNumbers(n: Int): Unit {
for (i in 1..n) {
println(i)
}
}
fun main() {
val number = 7
printNumbers(number)
}
Sample Output:
1 2 3 4 5 6 7
Explanation:
The "printNumbers()" function receives an n parameter of type Int. It uses a for loop to iterate from 1 to n and prints each number on a separate line using the println function. The return type Unit indicates that the function doesn't explicitly return a value.
In the "main()" function, a sample number (number) is provided, and printNumbers is called with this number as an argument. The function then prints the numbers from 1 to number on separate lines.
Kotlin Editor:
Previous: Print a greeting message with person's name.
Next: Print even numbers from list, Return Unit.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics