Iterators in Kotlin

Introduction 
 
In this article, we will learn about the Iterators in Kotlin. In Java and other programming languages, we have a for loop. In the case of Kotlin, we also have a  while loop and do-while loop. We also have a break and continue statement to execute code as per our wish. As a beginner, you may ask, "Why do we need loops?"
 
Suppose you want to print 'hello', you can simply type the print line 'hello'. Now you want to print hello multiple times, so you will simply type the print line 'hello' multiple times. In the output, you will likewise receive hello multiple times. As a beginner, you can go for this option, but let me tell you, this is not the way to do it if you have the same kind of patterned output. In this situation we have to make use of loops, or, you can say the 'Iterators'.
 
Let's check the syntax of the for loop:
  1. for (i in 0..4){   
This is the ranges now. Dot dot four is actually the range. So the i in 0 .. 4, that simply means that i will have the value of zero, one, two, three and four. Inside this, let us print hello four times.
  1. for (i in 0..4){  
  2.     println("hello")  
  3. }  
Similarly while loop has its own syntax such as while (i < 5 ) now here i is actually the counter variable.Inside the while loop we can simply print hello and then increment the counter variable i++
  1. var i = 1  
  2. while (i < 5){  
  3.     println("hello")  
  4.     i++  
  5. }  
At the end we have do-while loop and the syntax is
  1. do{  
  2.     //  
  3. }  
  4. while (condition)  
  5. var i = 1  
  6.   
  7. do{  
  8.     println("hello")  
  9. while (i < 5)   
Do followed by curly braces and here we have a While that will simply check for the condition. Now inside this, we can simply print hello and then increment the counter. So the syntax of the do-while loop and while loop is exactly the same as that of Java, the only difference we will find is in for loop.
 
In the case of a for loop and while loop, first, we are checking the condition and then only we are executing the code but in case of the do-while loop we are first executing the code and then checking the condition and then, at last, we have incrementing and decrementing of the counter. In case of for loop it is actually getting incremented internally so this was all about the syntax of for loop while loop and do-while loop.