w3resource

Kotlin function: Print asterisk pattern

Kotlin Function: Exercise-15 with Solution

Write a Kotlin function that prints a pattern of asterisks based on a given size. The size represents the number of rows and columns in the pattern. Use a single-expression function.

Sample Solution:

Kotlin Code:

fun printPattern(size: Int) = repeat(size) { println("*".repeat(size)) }

fun main() {
    val patternSize = 5
    printPattern(patternSize)
}

Sample Output:

*****
*****
*****
*****
*****

Explanation:

In the above exercise -

  • The "printPattern()" function takes an integer parameter size, representing the number of rows and columns in the pattern.
  • The "repeat()" function repeats the specified block of code size times. In each iteration, the code block is executed.
  • Within the code block, the println function is called to print a string of asterisks. The repeat function is used to repeat the asterisk character size times.
  • The printPattern function is called in the main function with a sample pattern size of 5.
  • Finally the asterisk pattern is printed to the console.

Kotlin Editor:


Previous: Check if the number is negative.
Next: Add two numbers with an explicit return type.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/function/kotlin-function-exercise-15.php