Go for loop, break, continue and range Tutorial

Udemy Generic 728x90

Definition:

A for loop is the only repetition control structure in GO. the for statement is used to repeat a block of code for multiple time i.e. execution of the same line of code for the specified number of times.

Syntax:

<br />
for initialization; Boolean_expression(condition); iteration {</p>
<p>//Statements execute till condition is true</p>
<p>}<br />

Let’s understand the flow of control in a for loop:

  • The first step is initialization,it is used to declare and initialize any variables that we use in the loop.This step is executed only once. This part can be left blank,but semicolon must be there.
  • In the second step, Boolean expression is evaluated.If it evaluates to true,the execution of loop continue.If it evaluates to false,then the execution of loop ends and flow of control jumps to the next line of code after the loop.
  • The third step is used to update variables declared in the first step.This part can be left blank but semicolon has to be after the Boolean expression.
  • The repetition process(body of loop,update variables,check condition) continues till the condition is true.

Note:-All the three parts ( initialization, condition, iteration) can be left blank.In this case loop will execute for an infinite number of times.
Let’s understand for loop with some examples
Print a table of 2.

<br />
package main<br />
import &quot;fmt&quot;<br />
func main() {<br />
    /* initialize i to 1;<br />
       check each time that i is less than 11;<br />
       increment i after each iteration<br />
    */<br />
    for i := 1; i &lt; 11; i++ {<br />
        fmt.Println(&quot;2 X&quot;,i,&quot;=&quot;,2*i)<br />
    }<br />
}<br />

Output:

2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20

Example 2:
Create right angled triangle using for loop.

<br />
package main<br />
import &quot;fmt&quot;<br />
func main() {<br />
    /* initialize i to 0;<br />
       check each time that i is less than 10;<br />
       increment i after each iteration<br />
    */<br />
     for i := 0; i &lt;10; i++ {<br />
     //nested for loop initialize j to 0;check j less then i+1;<br />
         for j :=0; j &lt;i+1;j++ {<br />
         // print * in one line till condition is true<br />
             fmt.Print(&quot;*&quot;)<br />
         }<br />
         // after each inner loop jump to the next line<br />
         fmt.Println()<br />
     }<br />
}<br />

Output:

*
**
***
****
*****
******
*******
********
*********
**********

Now let’s understand what will happen if any part left empty

<br />
package main<br />
import &quot;fmt&quot;<br />
func main() {<br />
    /*<br />
      prints the table of 2 infinitely<br />
      because condition is missing<br />
    */<br />
    for i := 1; ; i++ {<br />
        fmt.Println(&quot;2 X&quot;,i,&quot;=&quot;,2*i)<br />
    }<br />
}<br />

<br />
package main<br />
import &quot;fmt&quot;<br />
func main() {<br />
    /*<br />
      prints &quot;2 x 1=2&quot; infinitely<br />
      because increment part is missing<br />
      and i can never reach 11<br />
    */<br />
    for i := 1; i &lt; 11; {<br />
        fmt.Println(&quot;2 X&quot;,i,&quot;=&quot;,2*i)<br />
    }<br />
}<br />

<br />
package main<br />
import &quot;fmt&quot;<br />
func main() {<br />
    str := &quot;&quot;<br />
    /*<br />
       See both initialization and incrementing is missing<br />
       but it is managed outside of for loop<br />
    */<br />
    for ; str != &quot;xxxxxx&quot;; {<br />
        fmt.Println(&quot;Value of str:&quot;, str)<br />
        str = str + &quot;x&quot;<br />
    }<br />
}<br />

This function has output because it contains a valid condition,see the output below:

Value of str:
Value of str: x
Value of str: xx
Value of str: xxx
Value of str: xxxx
Value of str: xxxxx

Multiple variable assignment can be done in GO for loop and similarly, incrementation or updation of multiple variables can be done.Multiple conditions can be given with && and ||.Let’s understand this with the example given below:

<br />
package main<br />
import &quot;fmt&quot;<br />
func main() {<br />
    /*<br />
      multiple initialization;<br />
      a consolidated bool expression with &amp;&amp; and ||;<br />
      multiple ‘incrementation’<br />
    */<br />
    for i,j := 0,5;i&lt;j &amp;&amp; j&gt;0; i,j = i+1,j-1 {<br />
        fmt.Println(&quot;Value of i and j:&quot;,i,j,&quot;respectively&quot;)<br />
    }<br />
}<br />

Output:

Value of i and j: 0 5 respectively
Value of i and j: 1 4 respectively
Value of i and j: 2 3 respectively

break Keyword:

break keyword terminates the for loop. After the execution of loop ends,the flow of control jumps to the next statement past the for loop.Let’s see how it terminates the for loop with the help of examples given below:
Print the prime numbers from 1 to the given limit.

<br />
package main<br />
import &quot;fmt&quot;<br />
func main() {<br />
    //define limit<br />
    limit := 20<br />
    fmt.Println(&quot;Prime numbers between 1 and&quot; , limit);<br />
    //loop through the numbers one by one<br />
    for i :=1; i &lt; limit; i++ {<br />
        isPrime := true<br />
    //check to see if the number is prime<br />
        for j := 2; j &lt; i ; j++ {<br />
            if i % j == 0 {<br />
                isPrime = false<br />
                break<br />
            }<br />
        }<br />
        // print the number<br />
        if isPrime {<br />
            fmt.Print(i, &quot; &quot;)<br />
        }<br />
    }<br />
}<br />

Output:

Prime numbers between 1 and 20
1 2 3 5 7 11 13 17 19

Example:

<br />
package main<br />
import &quot;fmt&quot;<br />
func main() {<br />
    for i := 0; i &lt; 10; i++ {<br />
    //break out of this for loop when this condition is met<br />
        if i==5 {<br />
            fmt.Println(&quot;condition(i==5) breaks the loop&quot;)<br />
            break<br />
        }<br />
        fmt.Println(&quot;Value of i :&quot;,i)<br />
    }<br />
    fmt.Println(&quot;statement after loop&quot;)<br />
}<br />

Output:

Value of i : 0
Value of i : 1
Value of i : 2
Value of i : 3
Value of i : 4
condition(i==5) breaks the loop
statement after loop

In the example above, when i is equal to 5 then it terminates the for loop not the whole program.After it breaks the loop, the flow of control jumps to the next statement i.e. fmt.Println(“statement after loop”).
break keyword is beneficial in terminating an infinite loop.Let’s understand it with the example given below:

<br />
package main<br />
import &quot;fmt&quot;<br />
func main() {<br />
    str := &quot;&quot;<br />
    //there is no condition, this is an infinite loop<br />
    for {<br />
        //terminate the loop when this condition met<br />
        if str == &quot;OOOOOO&quot; {<br />
            break<br />
        }<br />
        fmt.Println(&quot;Value of i is:&quot;, str)<br />
        str=str+&quot;O&quot;;<br />
    }<br />
}<br />

Output:

Value of i is:
Value of i is: O
Value of i is: OO
Value of i is: OOO
Value of i is: OOOO
Value of i is: OOOOO

continue keyword:

continue keyword is used to skip the single iteration of the for loop.It means it does not break the loop,it only skips the single iteration and the flow of control jumps to the beginning of the for loop for the next iteration.
continue statement only used in for loop in GO.
Let’s understand it with the help of examples:

<br />
package main<br />
import &quot;fmt&quot;<br />
func main() {<br />
    for i := 0; i &lt; 5; i++ {<br />
    //skip the iteration when this condition is met<br />
        if i==2 {<br />
           continue<br />
        }<br />
        fmt.Println(&quot;Value of i :&quot;,i)<br />
    }<br />
    fmt.Println(&quot;Value of i : 2 is missing from the loop&quot;)<br />
}<br />

Output:

Value of i : 0
Value of i : 1
Value of i : 3
Value of i : 4
Value of i : 2 is missing from the loop

As you can see in the output,when i=2 it skipped that one and continue with the next one.
Example:
Print the Even number between 1 and 20 and see the role of continue statement.

<br />
package main<br />
import &quot;fmt&quot;<br />
func main() {<br />
    //define limit<br />
    limit := 20;<br />
    fmt.Println(&quot;Even numbers between 1 and &quot; , limit);<br />
    //loop through the numbers one by one<br />
    for number := 1; number&lt;limit ; number++ {<br />
        //if it is  odd, skip this number<br />
        if number%2 != 0 {<br />
            continue<br />
        }<br />
        //when number%2 is equal to 0, and then it is even<br />
        fmt.Print(number,&quot; &quot;)  <br />
    }<br />
}<br />

Output:

Even numbers between 1 and 20
2 4 6 8 10 12 14 16 18

range Keyword:

The range clause is used in for loop to iterate over the items of list.List may be an array,a slice, a map or channel. In other Words,range keyword is used to get each index of an array or map.Integer index is returned when it is used with arrays and slices.But in case of maps,every element is in key-value pair,so it can return only key and both key and its corresponding value.
Let’s understand it with the examples given below:
Example:
Find out the shortest element in the given array.

<br />
package main<br />
import &quot;fmt&quot;<br />
var shortestValue int=0;<br />
func main() {<br />
    //define an array a<br />
    a := []int{<br />
        48,96,86,68,<br />
        57,9,63,70,<br />
        37,34,83,27,<br />
        19,97, 82,17,<br />
    }<br />
    //loop through each element one by one<br />
    for i := range a {<br />
        //again loop through each element to check shortest element<br />
        for j := range a {<br />
            //check element with other elements in array<br />
            if a[i] &gt; a[j] {<br />
                //assign shortest value<br />
                shortestValue=a[j]<br />
            }<br />
        }<br />
    }<br />
    //print shortest value<br />
    fmt.Println(&quot;Shortest element in array is:&quot;, shortestValue)<br />
}<br />

Output:

Shortest element in array is: 9

Example:
Print the definition of each abbreviation given in the map.
package main
import &quot;fmt&quot;
func main() {
    //define a map 
    importantKeywords := map[string]string{
        &quot;HTML&quot;: &quot;Hypertext Markup Language&quot;,
        &quot;PHP&quot;: &quot;PHP: Hypertext Preprocessor&quot;,
        &quot;JVM&quot;: &quot;Java Virtual Machine&quot;,
        &quot;XML&quot;: &quot;Extensible Markup Language&quot;,
        &quot;CSS&quot;: &quot;Cascading Style Sheets&quot;,
        &quot;JSP&quot;: &quot;Java Server Page&quot;,
        &quot;JDK&quot;: &quot;Java Development Kit&quot;,
        &quot;SDK&quot;: &quot;Software Development Kit&quot;,
        &quot;SQL&quot;: &quot;Structured Query Language&quot;,
        &quot;AJAX&quot;: &quot;Asynchronous JavaScript And XML&quot;,
    }
    // loop through each element to get key and value
    for keyword,description :=range importantKeywords {
        //print keyword and its defination
        fmt.Println(keyword,&quot;means:&quot;,description)
    }
}

Output:

PHP means: PHP: Hypertext Preprocessor
SDK means: Software Development Kit
SQL means: Structured Query Language
AJAX means: Asynchronous JavaScript And XML
JDK means: Java Development Kit
HTML means: Hypertext Markup Language
JVM means: Java Virtual Machine
XML means: Extensible Markup Language
CSS means: Cascading Style Sheets
JSP means: Java Server Page

The for loop in the above example can be replaced by the following code and you will get the same result:

<br />
for keyword :=range importantKeywords {<br />
    fmt.Println(keyword,&quot;means:&quot;,importantKeywords[keyword])<br />
}<br />

This is the second way of getting the  key and value of each key-value pair in maps using the range clause.
Note:- Maps are  unordered collections of key-value pairs like an associative array,so maps are not sequential.When iterating over the map using range in for loop, the order of iteration is not specified and is not guaranteed that it would be same from one iteration to the next.So,the output of the above program will be different, every time you run this program.

Udemy Generic 728x90

Spread the word. Share this post!