How to print Hollow Square Pattern in Kotlin - Step by Step Examples
How to print Hollow Square Pattern in Kotlin ?
Answer
To print a Hollow Square Pattern in Kotlin, we use nested loops. The outer loop controls the rows, and the inner loops control the columns and the conditions for printing the hollow square pattern.
✐ Examples
1 Hollow Square Pattern
In this example,
- We define a function
printHollowSquare
that takes the size of the squaren
as a parameter. - We use two nested
for
loops to iterate over rows and columns. - Within the loops, we check if we are at the first or last row or column, or if the current position is on the border of the square. If so, we print a star (*); otherwise, we print a space.
Kotlin Program
fun printHollowSquare(n: Int) {
for (i in 0 until n) {
for (j in 0 until n) {
if (i == 0 || i == n - 1 || j == 0 || j == n - 1)
print("*")
else
print(" ")
}
println()
}
}
// Example usage
fun main() {
printHollowSquare(5)
}
Output
***** * * * * * * *****
Summary
In this tutorial, we learned How to print Hollow Square Pattern in Kotlin language with well detailed examples.
More Kotlin Pattern Printing Tutorials
- How to print Left Half Pyramid Pattern in Kotlin ?
- How to print Right Half Pyramid Pattern in Kotlin ?
- How to print Pyramid Pattern in Kotlin ?
- How to print Rhombus Pattern in Kotlin ?
- How to print Diamond Pattern in Kotlin ?
- How to print Hour Glass Pattern in Kotlin ?
- How to print Hollow Square Pattern in Kotlin ?
- How to print Hollow Pyramid Pattern in Kotlin ?
- How to print Hollow Inverted Pyramid Pattern in Kotlin ?
- How to print Hollow Diamond Pattern in Kotlin ?
- How to print Floyd's Trianlge Pattern in Kotlin ?
- How to print Pascal's Triangle Pattern in Kotlin ?