So I was trying to create a function called createSquare()
where the first argument is the character used to create the square and the second argument is its side length, should have worked like
createSquare('a', 3)
/* Output is
aaa
aaa
aaa
*/
I tried using the while loop to achieve this in the following way.
fun createSquare(character: Char = '*', side: Int = 3){
var i = 0
var j = 0
while(i < side){
while(j < side){
print(character)
++j
}
print('\n')
++i
}
}
fun main(args: Array<String>) {
createSquare() // Default arguments passed
}
And this is how I thought the nested while loops would work:
Execute the inner while loop
Linespace moves the output cursor to the next line
i
increments by 1
Steps 1-3 happen again till i
becomes 3, stopping the whole nested loop
However this is the output instead:
*** //Output
/*
Where I expected
***
***
***
*/
There might be silly errors in my code as yet I'm a novice programmer.
Thanks in advance!
A more "kotliny" way to write those loops would be to use ranges:
for (i in 0..side) {
// your code
}
or
repeat(side) { i ->
// your code
}
or
(0..side).forEach { i ->
// your code
}
Of course you can loop manually too, but evidently, that is error-prone