w3resource

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.


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax: Familiarity with writing and running Kotlin programs.
  • Kotlin Functions: Understanding how to define and call functions in Kotlin.
  • Unit Type: Awareness that functions without a return value implicitly return Unit in Kotlin.
  • Loops in Kotlin: Knowledge of using for loops to iterate over a range of numbers.
  • Range Operator: Understanding the range operator (..) to define a sequence of numbers.
  • Printing Output: Familiarity with the println() function to display output on the screen.

Hints (Try before looking at the solution!)

  • Define the Function.
  • Use a For Loop.
  • Print Each Number.
  • Call the Function.
  • Test with Different Values.
  • Common Errors to Avoid:
    • Forgetting the range operator.
    • Misplacing loop boundaries.
    • Unnecessarily adding a return statement.

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.



Follow us on Facebook and Twitter for latest update.