w3resource

Kotlin function: Print asterisk pattern


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.


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.
  • Single-Expression Functions: Knowledge of creating concise single-expression functions in Kotlin.
  • Repeat Function: Awareness of the repeat() function to execute a block of code multiple times.
  • String Manipulation: Ability to use the repeat() method on strings to create repeated patterns.
  • Printing Output: Familiarity with the println() function to display output on the screen.

Hints (Try before looking at the solution!)

  • Define the Function.
  • Generate the Pattern.
  • Call the Function.
  • Test with Different Sizes.
  • Common Errors to Avoid:
    • Forgetting repeat() usage.
    • Misplacing string repeat logic.
    • Not testing edge cases like size = 0.

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.



Follow us on Facebook and Twitter for latest update.