w3resource

Kotlin Program: Print the first 10 natural numbers


Write a Kotlin program to print the first 10 natural numbers.


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax.
  • Kotlin Functions.
  • Loops in Kotlin.
  • Range Operator.
  • Printing Output.

Hints (Try before looking at the solution!)

  • Define the main() Function.
  • Use a For Loop.
  • Print Each Number.
  • Test the Program.
  • Common Errors to Avoid:
    • Forgetting the range operator.
    • Misplacing loop boundaries.
    • Using print() instead of println().

Sample Solution:

Kotlin Code:

fun main() {
    for (i in 1..10) {
        println(i)
    }
}

Sample Output:

1
2
3
4
5
6
7
8
9
10

Explanation:

In the above exercise,

  • The main() function serves as the program's entry point.
  • The for loop iterates from 1 to 10 (inclusive) using the range operator ‘..’.
  • Inside the loop, the current number i is printed using the println() function.
  • The loop continues until all numbers from 1 to 10 have been printed.

Kotlin Editor:


Previous: Check vowel or consonant.
Next: Print Pascal's Triangle for a given number of rows.

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.