Kotlin Program: Print the first 10 natural numbers
Kotlin Control Flow: Exercise-4 with Solution
Write a Kotlin program to print the first 10 natural numbers.
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/kotlin-exercises/control-flow/kotlin-control-flow-exercise-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics