For Loop In 'Go'(Learn 'Go' - Part 11)

in #programming7 years ago

In Go, we use the 'For' statement to repeat a block of statements multiple times. Unlike other languages, Go has just one type of loop, i.e., 'for' and we can use it in a variety of ways.

 

For Instance,

 

package main

import "fmt"

func main(){

i := 1
for i <= 10{

fmt.Println(i)

i = 1 + 1

}

}

 
 

In this program, we have created a variable called 'i' to store the number we want to print. After that, we have created a for loop with a conditional expression to check whether the value of 'i' is less than or equal to '10'. After that, we have used the fmt.Println statement to print the value of 'i' and finally adding 1 to the value of 'i' before completing the loop.

 

As long as the value of 'i' will be less than or equal to 10, the loop will continue. As we can clearly predict, the loop will continue until 10 and at each increment it will print the value. So, it will print numbers 1 to 10 and after that the loop will end.

 

You can also write the same program in a simpler way.

func main(){

for i := 1; 1 <= 10; i++ {fmt.Println(i)

}

}

We can use '++' to increment and '--' operators to decrement the values by 1 in our programs.

 
 
 

Previous Posts In The Series

 
 

Introduction To 'Go' Programming Language(Learn 'Go' - Part 1)

 

25 Basic Keywords Of The Go Programming Language (Learn 'Go' - Part 2)

 

How To Set The Go Programming Environment On Your System?(Learn 'Go' - Part 3)

 

Create Your First Program In Go Language (Learn 'Go' - Part 4)

 

Strings In 'Go'(Learn 'Go' - Part 5)

 

Booleans In 'Go'(Learn 'Go' - Part 6)

 

Numbers In 'Go'(Learn 'Go' - Part 7)

 

Variables In 'Go'(Learn 'Go' - Part 8)

 

Constants In 'Go'(Learn 'Go' - Part9)

 

Multiple Variables In 'Go'(Learn 'Go' - Part10)


 
 

Upcoming Posts

 

'If' Statement In Go(Learn 'Go' - Part 12)

Coin Marketplace

STEEM 0.22
TRX 0.28
JST 0.042
BTC 104621.15
ETH 3895.38
SBD 3.29