Search code examples
functionloopskotlinwhile-loopnested-loops

Problems with nested while loops in Kotlin


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:

  1. Execute the inner while loop

  2. Linespace moves the output cursor to the next line

  3. i increments by 1

  4. 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!


Solution

  • 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
    }
    
    • This has the benefit (and downside) of not leaking the counter
    • These will all essentially compile down to a for-loop in bytecode

    Of course you can loop manually too, but evidently, that is error-prone