Go Language for Loop Examples

by on November 2, 2012 · 0 comments· LAST UPDATED December 2, 2013

in , ,

How do I write a for loop using Go programming language? How do I use golang for loop to repeat certain tasks? How do I set infinite loops using for statement on golang?

A 'for loop' is a golang statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement i.e. it is the repetition of a process within a go program. For example, you can run certain task or print message five times or read & process list of files using a for loop. Golang for loop is similar to but not the same as—C's for loop syntax.

Syntax

The basic syntax is:

for init; condition; post {
  // run commands till condition is true
}

Infinite for loop syntx:

for {
   // I will run forever
}

Examples

The following golang program print welcome message five times using a for loop. Create a file called for.go:

// for.go : A simple for loop program written in golang
package main
// get fmt package for Printf()
import "fmt"
// Our main()
func main() {
        // set a for loop
        for i := 1;  i<=5; i++ {
                fmt.Printf("Welcome %d times\n",i)
        }
}

Save and close the file. Run it as follows:
$ go for.go
Sample outputs:

Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times

Here is another example to print sum of all digits using a for loop:

// sum.go : golang for loop demo code
package main
import "fmt"
func main() {
        sum := 0
        for i := 1;  i<=20; i++ {
                sum += i
        }
        fmt.Printf("Sum =  %d\n",sum)
}

Save and close the file. Run it as follows:
$ go sum.go
Sample outputs:

Sum =  210

How do I use golang for as infinite loops?

Infinite for loop can be created with empty expressions, such as:

// forver-in-love.go : an infinite loop example
package main
import "fmt"
func main() {
    for {
        fmt.Println("I am in love with the Terminal (hit Ctrl+C to stop)")
    }
}

In this example, read an integer (number) from keyboard and display message on screen:

// for2.go : A modified version of for.go. This program use Scan() to read input from user
package main
import "fmt"
func main() {
	y := 0
        // Get number from user
	fmt.Printf("Enter a number : ")
	fmt.Scan(&y)
	for i := 1;  i<=y; i++ {
		fmt.Printf("Welcome %d times.\n",i)
	}
}

Sample outputs:

$ go run for2.go
Enter a number : 3
Welcome 1 times.
Welcome 2 times.
Welcome 3 times.
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 0 comments… add one now }

Leave a Comment

Tagged as:

Previous Faq:

Next Faq: