Go If Else And Loops Statements

Go Language - For loop, If statement and Switch

For Loop :

Unlike other programming languages like C,Java-Script and Java,Go Language has only one looping construct i.e “for” loop. The for loop has three parts for initialize, condition expression and post statement. The init and post statements are optional. The braces are mandatory.

CODE/PROGRAM/EXAMPLE
package main
import "fmt"
func main() {
	sum := 100
	for i := 1; i < 10; i++ {
		sum += i
		fmt.Println(sum)
		}
		fmt.Println(" the total amount is ",sum)
		}

For loop can also be used a “while” loop in C language. We can use only the condition expression and perform while loop using the same for in Go language.

CODE/PROGRAM/EXAMPLE
package main
import "fmt"
func main() {
	sum := 100
	for ; sum < 110;  {
		sum += sum
		fmt.Println(sum)
		}
		fmt.Println(" the total amount is ",sum)
		}

Decision Making –IF

IF :

Similar to for loops if statement require only braces { }.

CODE/PROGRAM/EXAMPLE
package main
import (
"fmt"
"math"
)
func sqrt(x float64) string {
	if x < 0 {
		return sqrt(-x) + "i"
		}
		return fmt.Sprint(math.Sqrt(x))
		}
		func main() {
			fmt.Println(sqrt(5), sqrt(-5))
fmt.Println(sqrt(3), sqrt(-3))
}

Switch

Switch is very flexible with no break statements required. Constants, Variables and Integers can be provided as switch cases condition.

CODE/PROGRAM/EXAMPLE
package main
import (
"fmt"
"runtime"
)
func main() {
	fmt.Print("Go runs on ")
	switch os := runtime.GOOS; os {
		case "darwin":
		fmt.Println("OS X.")
		case "linux":
		fmt.Println("Linux.")
		default:
		// freebsd, openbsd,
		// plan9, windows...
		fmt.Printf("%s.", os)
		}
	}
#golang_loops #golang_for_loop #for_loop_in_golang #for_loop_golang #go_for_loop #golang_while_loop #golang_break_for_loop #golang_break_loop #golang_if #golang_if_else #if_else_in_golang #golang_switch_case #golang_switch #switch_case_in_golang_

(New page will open, for Comment)

Not yet commented...