Professional Documents
Culture Documents
Lecture – 02
GO language Control Structures
if x > 0 {
return y
}
Continue…
The if....else statement allows you to execute one block of code if the specified
condition is evaluates to true and another block of code if it is evaluates to false.
if condition {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Continue…
package main
import (
"fmt"
)
func main() {
x := 100
if x == 100 {
fmt.Println("Lahore")
} else {
fmt.Println("Islamabad")
}
}
Continue…
for
The Go for loop is similar to C but not the same as C. It unifies for and while and
there is no do-while. There are three forms, only one of which has semicolons.
// Like a C for
for init; condition; post { }
// Like a C while
for condition { }
// Like a C for(;;)
for { }
Short declarations make it easy to declare the index variable right in the loop.
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
Nested for loop - GO Language
package main
import "fmt"
func main() {
for outer := 0; outer < 5; outer++ {
if outer == 3 {
fmt.Println("Breaking out of outer loop")
break // break here
}
fmt.Println("The value of outer is", outer)
for inner := 0; inner < 5; inner++ {
if inner == 2 {
fmt.Println("Breaking out of inner loop")
break // break here
}
Continue…
In this program, we have two loops. While both loops iterate 5 times, each has a
conditional if statement with a break statement. The outer loop will break if the
value of outer equals 3. The inner loop will break if the value of inner is 2.
Switch Statement - GO Language
A switch statement is a shorter way to write a sequence of if - else statements. It runs the
first case whose value is equal to the condition expression.
Go's switch is like the one in C, C++, Java, JavaScript, and PHP, except that Go only
runs the selected case, not all the cases that follow. In effect, the break statement that is
needed at the end of each case in those languages is provided automatically in Go.
Another important difference is that Go's switch cases need not be constants, and the
values involved need not be integers.
Expression Switch
Type Switch
Expression Switch
Expression Switch
Expression switch is similar to switch statement in C, C++, Java language. It
provides an easy way to dispatch execution to different parts of code based on the
value of the expression.
Syntax:
Syntax:
In case of the for loop, continue statement causes the conditional test and
increment portions of the loop to execute.
Syntax
The syntax for a continue statement in Go is as follows −
continue;
Continue…
package main Flow Diagram
import "fmt"
func main() {
/* local variable definition */
var a int = 20
/* do loop execution */
for a < 40 {
if a == 12 {
/* skip the iteration */
a = a + 1;
continue;
}
fmt.Printf("value of a: %d\n", a);
a++;
}
}
goto statement - label