DAY 3 - Conditional Statements & Loops
Go Control Flow — If, Else, Switch & Loops
Control flow allows us to execute specific blocks of code based on certain conditions.
Go provides several ways to handle control flow such as if, else, switch, and for loops.
If and Else Statements
The basic structure of an if statement in Go:
if condition {
// execute this block if condition is true
} else {
// execute this block if condition is false
}
Important Note:
In Go, the else must be on the same line as the closing } of the if block.
Otherwise, you’ll get a syntax error.
❌ Incorrect:
if condition {
// code
}
else {
// code
}
Correct:
if condition {
// code
} else {
// code
}
Else If Ladder
You can use multiple conditions using else if.
if condition1 {
// executes if condition1 is true
} else if condition2 {
// executes if condition1 is false and condition2 is true
} else {
// executes if all above conditions are false
}
Nested If Statements
You can also use if statements inside another if block.
if condition {
if subCondition {
// executes if both conditions are true
} else {
// executes if main condition is true but subCondition is false
}
}
Switch Statement
The switch statement in Go is used to execute one block of code out of many, based on the value of an expression.
Basic Example
package main
import "fmt"
func main() {
day := "Monday"
switch day {
case "Monday":
fmt.Println("Start of the week!")
case "Friday":
fmt.Println("Weekend is coming!")
default:
fmt.Println("It's a regular day.")
}
}
Multiple Case Values (OR Condition)
You can use comma-separated values to handle multiple matches.
switch day {
case "Saturday", "Sunday":
fmt.Println("It's the weekend!")
default:
fmt.Println("It's a weekday.")
}
Expressionless Switch (Similar to IF-ELSE Chain)
When no value is provided after switch, each case acts as a condition.
num := 45
switch {
case num < 0:
fmt.Println("Negative number")
case num == 0:
fmt.Println("Zero")
case num > 0 && num < 100:
fmt.Println("Positive number below 100")
default:
fmt.Println("Large positive number")
}
Here we used logical AND (&&) and OR (||) operators inside the conditions.
Loops in Go
Go has only one loop keyword — for, but it’s extremely versatile.
You can use it in multiple ways to achieve different loop behaviors.
Classic For Loop
for i := 0; i < 5; i++ {
fmt.Println("Iteration:", i)
}
Here:
i := 0→ initializationi < 5→ conditioni++→ increment step
While-like Loop
If you skip the initialization and increment, it behaves like a while loop.
i := 0
for i < 5 {
fmt.Println("Value:", i)
i++
}
Infinite Loop
If you remove all three statements, it runs infinitely until you break it manually.
for {
fmt.Println("Running forever...")
break // use break to stop
}
Loop with range (Iterating over Arrays, Slices, Maps, Strings)
➤ Over a Slice:
nums := []int{10, 20, 30}
for index, value := range nums {
fmt.Println("Index:", index, "Value:", value)
}
If you dont wan't to use the index value, simple you can replace indev with _
➤ Over a Map:
person := map[string]string{"name": "Siva", "role": "Developer"}
for key, value := range person {
fmt.Println(key, ":", value)
}
➤ Over a String:
word := "GoLang"
for index, char := range word {
fmt.Printf("Index: %d, Char: %c\n", index, char)
}
Using break and continue
break→ stops the loop immediatelycontinue→ skips to the next iteration
for i := 1; i <= 5; i++ {
if i == 3 {
continue // skip iteration when i = 3
}
if i == 5 {
break // stop loop when i = 5
}
fmt.Println(i)
}
Summary
| Concept | Description |
if, else if, else | Conditional branching |
switch | Simplifies multi-condition logic |
for | The only loop in Go (handles all types) |
range | Iterates over collections |
break / continue | Control loop flow |
Example Program Combining All
package main
import "fmt"
func main() {
nums := []int{10, 25, 50, 100}
for _, n := range nums {
switch {
case n < 20:
fmt.Println(n, "is small")
case n >= 20 && n < 80:
fmt.Println(n, "is medium")
default:
fmt.Println(n, "is large")
}
}
}
Output:
10 is small
25 is medium
50 is medium
100 is large