1. Introduction
Kotlin, renowned for its concise syntax and robust capabilities, often finds applications in creating patterns and pyramids through code. This article delves into three distinct Kotlin code To Create Pyramid and Pattern, showcasing various patterns and pyramid formations achieved through logical implementations and loop structures.
2. Example 1: Simple Pyramid
This example demonstrates a straightforward approach to creating a pyramid pattern. The outer loop manages the row count, while the inner loops handle spaces and stars to form the pyramid shape.
Code
fun main() {
val rows = 5
var k = 0
for (i in 1..rows) {
for (space in 1..rows - i) {
print(" ")
}
while (k != 2 * i - 1) {
print("* ")
++k
}
k = 0
println()
}
}
Output
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
3. Example 2: Inverted Pyramid
In this example, the inverted pyramid pattern is created by reversing the logic of the simple pyramid. The outer loop decrements from the maximum row count, while the inner loops manage spaces and stars in reverse order.
Code
fun main() {
val rows = 5
for (i in rows downTo 1) {
for (space in 0 until rows - i) {
print(" ")
}
for (j in 1..2 * i - 1) {
print("* ")
}
println()
}
}
Output
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
4. Example 3: Hollow Pyramid
This example showcases the creation of a hollow pyramid pattern. Conditions within the inner loops determine whether to print a space or a star, resulting in a hollow effect with stars only at the edges and base.
Code
fun main() {
val rows = 5
for (i in 1..rows) {
for (space in 1..rows - i) {
print(" ")
}
for (j in 1..2 * i - 1) {
if (j == 1 || j == 2 * i - 1 || i == rows) {
print("* ")
} else {
print(" ")
}
}
println()
}
}
Output
*
* *
* *
* *
* * * * * * * * *
5. Conclusion
Exploring and understanding these patterns enhances problem-solving skills and strengthens Kotlin programming proficiency. Experimenting with variations and exploring additional patterns further solidifies knowledge and mastery of Kotlin programming concepts