Monday, January 12, 2015

FOR Loop in Go Programming

Here's an exercise that will help you to understand the only looping construct present in Go programming language. Yes, you heard it right, Go has only one loop - for loop. Go is neat and concise. I really liked the way it has done away with the multiple confusing loops that are present in other languages. The code looks tidy with a few less number of brackets and no semicolons.

Let us try to get the following graphical image (Go flag) using for loop.

P.S. - for loop is a powerful control statement and is frequently used in programming. You must understand it fully and feel at home while using it. 

A few other golang for loop examples:
1. Multiplication Table - Using FOR Loop in Go . 
2. for loop used in defer statement.
3. FizzBuzz

The Output

The Solution

The solution with simple for loop is here:

package main

import "fmt"

func main() {
 str := "||Go"
 for i := 1; i <= 10; i++ {
  str += "||Go"
 for k := 19; k >= 1; k-- {

Want to Run the Code in Action and See the Output Right Now?
The alternate solution uses nested for loops. You can be a little creative and can print whatever you want in place of Go. For example replace Go with * and see a different output.

Hope you liked this. Can it be improved? Please share your views.

No comments:

Post a Comment