Contents
Control Statement in Go
if, if-else, Nested-if, if-else-if
Decision-making in programming is analogous to decision-making in real life. In programming, a piece of code executes when a specified condition is met. These constructs are often referred to as Control Flow Statements. In Go programming, control statements are employed to guide the flow of execution in the program based on specified conditions. They allow the program’s flow to advance and branch depending on the program’s state.
The decision-making statements in Go programming include:
if Statement
The if
statement is the simplest form of decision-making. It determines whether a specific block of code will execute, based on whether a given condition evaluates to true. If the condition is true, the corresponding block is executed; otherwise, it is skipped.
Syntax:
if condition {
// Code to execute if
// the condition is true
}
Example:
// Go program to demonstrate
// the usage of the if statement
package main
import "fmt"
func main() {
// Declare a local variable
var num int = 450
// Check the condition using if
if num > 100 {
// This block executes if
// the condition is true
fmt.Printf("num is greater than 100\n")
}
fmt.Printf("The value of num is: %d\n", num)
}
Output:
num is greater than 100
The value of num is: 450
Time Complexity: O(1)
Auxiliary Space: O(1)
if…else Statement
The if
statement handles execution when a condition is true, but what if the condition is false? In such cases, the else
statement provides an alternative block of code to execute.
Syntax:
if condition {
// Executes this block if
// the condition is true
} else {
// Executes this block if
// the condition is false
}
Example:
// Go program to demonstrate
// the use of the if…else statement
package main
import "fmt"
func main() {
// Declare a local variable
var marks int = 900
// Check the condition using if
if marks < 500 {
// This block executes if the
// condition evaluates to true
fmt.Printf("marks are less than 500\n")
} else {
// This block executes if the
// condition evaluates to false
fmt.Printf("marks are 500 or more\n")
}
}
Output:
marks are 500 or more
Time Complexity: O(1)
Auxiliary Space: O(1)
Nested if Statement
In Go, nested if
statements allow placing one if
statement inside another. This enables checking multiple conditions sequentially.
Syntax:
if condition1 {
// Executes if condition1 is true
if condition2 {
// Executes if condition2 is true
}
}
Example:
// Go program to demonstrate
// the use of nested if statements
package main
import "fmt"
func main() {
// Declare two variables
var a int = 250
var b int = 500
// Check the first condition
if a < 300 {
// If condition1 is true,
// check the nested condition
if b < 600 {
// Executes if both conditions are true
fmt.Printf("a is less than 300 and b is less than 600\n")
}
}
}
Output:
a is less than 300 and b is less than 600
Time Complexity: O(1)
Auxiliary Space: O(1)
if..else..if Ladder
When multiple conditions need to be evaluated, the if..else..if
ladder provides a way to do so. The conditions are evaluated sequentially, and as soon as one condition is satisfied, its corresponding block is executed. If none of the conditions are true, the final else
block executes.
Important Points:
- An
if
statement can have zero or oneelse
, which must come after anyelse if
blocks. - An
if
statement can have zero to multipleelse if
blocks, which must appear before theelse
. - Once an
else if
condition is true, no furtherelse if
orelse
blocks are evaluated.
Syntax:
if condition_1 {
// Executes if condition_1 is true
} else if condition_2 {
// Executes if condition_2 is true
} else {
// Executes if none of the conditions are true
}
Example:
// Go program to demonstrate the
// usage of the if..else..if ladder
package main
import "fmt"
func main() {
// Declare a variable
var value int = 150
// Evaluate conditions
if value == 50 {
// Executes if condition1 is true
fmt.Printf("value is 50\n")
} else if value == 100 {
// Executes if condition2 is true
fmt.Printf("value is 100\n")
} else if value == 150 {
// Executes if condition3 is true
fmt.Printf("value is 150\n")
} else {
// Executes if none of the conditions are true
fmt.Printf("value does not match any condition\n")
}
}
Output:
value is 150
Time Complexity: O(1)
Auxiliary Space: O(1)
Loops in Go Language
The Go programming language has only one type of loop: the for
loop. It is a control structure that allows the repetition of a block of code a specific number of times. The for
loop in Go can be used in various forms, as explained below:
1. Simple for
Loop
This is similar to the for
loops in languages like C, C++, Java, and C#.
Syntax:
for initialization; condition; post {
// statements...
}
Initialization: Executes before the loop starts (optional).
Condition: A boolean expression evaluated at the start of each iteration. If
true
, the loop continues; otherwise, it stops.Post statement: Executed after each iteration of the loop.
Example:
// Go program demonstrating a simple for loop
package main
import "fmt"
func main() {
// Using a for loop to print a message 5 times
for i := 0; i < 5; i++ {
fmt.Println("Hello, Go!")
}
}
Output:
Hello, Go!
Hello, Go!
Hello, Go!
Hello, Go!
Hello, Go!
2. Infinite for
Loop
A for
loop can run indefinitely by omitting all three components of the for
loop.
Syntax:
for {
// statements...
}
Example:
// Go program demonstrating an infinite for loop
package main
import "fmt"
func main() {
for {
fmt.Println("This will run forever")
}
}
Output:
This will run forever
This will run forever
This will run forever
... (repeats endlessly)
3. for
Loop as a while
Loop
A for
loop can act like a while
loop by specifying only the condition.
Syntax:
for {
// statements...
}
Example:
// Go program demonstrating a for loop as a while loop
package main
import "fmt"
func main() {
x := 0
for x < 4 {
fmt.Println("Value of x:", x)
x++
}
}
Output:
Value of x: 0
Value of x: 1
Value of x: 2
Value of x: 3
4. Using range
with for
Loop
The range
keyword allows iteration over arrays, slices, strings, maps, or channels.
Syntax:
for index, value := range collection {
// statements...
}
Example:
// Go program demonstrating range with an array
package main
import "fmt"
func main() {
items := []string{"Apple", "Banana", "Cherry"}
for idx, fruit := range items {
fmt.Printf("Index: %d, Fruit: %s\n", idx, fruit)
}
}
Output:
Index: 0, Fruit: Apple
Index: 1, Fruit: Banana
Index: 2, Fruit: Cherry
5. Iterating Over Strings
A for
loop can iterate over Unicode code points in a string using range
.
Syntax:
for index, char := range str {
// statements...
}
Example:
// Go program demonstrating iteration over a string
package main
import "fmt"
func main() {
for i, c := range "GoLang" {
fmt.Printf("Character: %c at Index: %d\n", c, i)
}
}
Output:
Character: G at Index: 0
Character: o at Index: 1
Character: L at Index: 2
Character: a at Index: 3
Character: n at Index: 4
Character: g at Index: 5
6. Iterating Over Maps
The for
loop can iterate over keys and values in a map using range
.
Syntax:
for key, value := range map {
// statements...
}
Example:
// Go program demonstrating iteration over a map
package main
import "fmt"
func main() {
countries := map[string]string{
"IN": "India",
"US": "United States",
"FR": "France",
}
for code, name := range countries {
fmt.Printf("Code: %s, Country: %s\n", code, name)
}
}
Output:
Code: IN, Country: India
Code: US, Country: United States
Code: FR, Country: France
7. Iterating Over Channels
A for
loop can iterate over values sent through a channel until it is closed.
Syntax:
for item := range channel {
// statements...
}
Example:
// Go program demonstrating iteration over a channel
package main
import "fmt"
func main() {
ch := make(chan int)
go func() {
for i := 1; i <= 3; i++ {
ch <- i * 10
}
close(ch)
}()
for val := range ch {
fmt.Println("Received:", val)
}
}
Output:
Received: 10
Received: 20
Received: 30
Switch Statement in Go
In Go, a switch
statement is a versatile branching construct that provides an efficient mechanism to direct execution based on the value or type of an expression. Go supports two primary types of switch statements:
Expression Switch
Type Switch
Example:
package main
import "fmt"
func main() {
day := 3
switch day {
case 1:
fmt.Println("Sunday")
case 2:
fmt.Println("Monday")
case 3:
fmt.Println("Tuesday")
case 4:
fmt.Println("Wednesday")
case 5:
fmt.Println("Thursday")
default:
fmt.Println("Invalid day")
}
}
Output:
switch optionalStatement; optionalExpression {
case expression1:
// Code block
case expression2: // Expression Switch
// Code block
default:
// Code block
}
switch variable := interfaceValue.(type) {
case type1:
// Code block
case type2: // Type Switch
// Code block
default:
// Code block
}
Expression Switch
An Expression Switch evaluates a specific expression and transfers control to a matching case
based on the result of the evaluation. If no expression is provided, the switch
defaults to evaluating true
.
Syntax
switch optionalStatement; optionalExpression {
case expression1:
// Code block
case expression2:
// Code block
default:
// Code block
}
optionalStatement
: An optional single statement, such as variable declaration.optionalExpression
: An optional expression. If omitted, it defaults totrue
.
Example with Optional Statement
Here, we define a variable day
in the optional statement and use it in the switch
evaluation:
package main
import "fmt"
func main() {
switch day := 2; day {
case 1:
fmt.Println("Sunday")
case 2:
fmt.Println("Monday")
case 3:
fmt.Println("Tuesday")
case 4:
fmt.Println("Wednesday")
case 5:
fmt.Println("Thursday")
default:
fmt.Println("Invalid day")
}
}
Output:
Monday
Example with Optional Expression
If no expression is provided, the switch
assumes the expression is true
. This enables the use of conditional logic in case
statements.
package main
import "fmt"
func main() {
day := 5
switch {
case day == 1:
fmt.Println("Sunday")
case day == 2:
fmt.Println("Monday")
case day > 3:
fmt.Println("End of Week")
default:
fmt.Println("Invalid day")
}
}
Output:
End of Week
Type Switch
A Type Switch determines the type of an interface value rather than its actual value. This is particularly helpful when working with variables of unknown or mixed types.
Syntax
switch variable := interfaceValue.(type) {
case type1:
// Code block
case type2:
// Code block
default:
// Code block
}
Example:
package main
import "fmt"
func main() {
var day interface{} = "Tuesday"
switch v := day.(type) {
case int:
fmt.Printf("Day number: %d\n", v)
case string:
switch v {
case "Sunday":
fmt.Println("Start of the week")
case "Tuesday":
fmt.Println("Midweek day")
default:
fmt.Println("Another weekday")
}
default:
fmt.Printf("Unsupported type: %T\n", v)
}
}
Output:
Midweek day
Related Chapters
- Introduction of Go-Lang
- Fundamentals in Go
- Control Statement in Go
- Functions & Methods in Go
- Structures in Go
- Arrays in Go
- Slices in Go
- File Handling in I/O
- Pointers in Go
- Concurrency in Go
- Object Oriented Programming in Go
- Defer and Error Handling in Go
- First Class Functions in Go
- Reflection in Go
- File Handling in Go