Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Control Flow (if, for, switch)

7. Control Flow (if, for, switch)

Control flow statements are essential in programming to make decisions, repeat tasks, and handle different cases. In Go, you have 'if', 'for', and 'switch' statements to control the flow of your program. Let's explore each of these in detail with examples.

1. if Statement:

The 'if' statement is used to execute a block of code if a certain condition is true.

if condition {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}

 

Example:
age := 18

if age >= 18 {
fmt.Println("You are an adult.")
} else {
fmt.Println("You are not yet an adult.")
}

 

2. for Loop:

The 'for' loop is used to repeatedly execute a block of code as long as a certain condition is true.

for initialization; condition; post {
    // Code to repeat
}
 
Example:
for i := 0; i < 5; i++ {
fmt.Println(i)
}

 

3. switch Statement:

The 'switch' statement is used to evaluate an expression and choose a case to execute based on its value.

switch expression {
case value1:
// Code to execute if expression == value1
case value2:
// Code to execute if expression == value2
default:
// Code to execute if no case matches
}

 

Example:
day := "Wednesday"

switch day {
case "Monday":
fmt.Println("It's the start of the week.")
case "Friday":
fmt.Println("It's almost the weekend!")
default:
fmt.Println("It's another day.")
}

 

4. The 'break' and 'continue' Statements:

Inside loops, you can use the 'break' statement to immediately exit the loop and the 'continue' statement to skip the current iteration and proceed to the next.

Example:
for i := 0; i < 10; i++ {
if i == 5 {
break // Exit the loop when i == 5
}
fmt.Println(i)
}

 

for i := 0; i < 10; i++ {
if i == 5 {
continue // Skip iteration when i == 5
}
fmt.Println(i)
}

 

These control flow statements are fundamental to writing structured and logical programs. They allow you to make decisions, repeat tasks, and handle various cases efficiently. By using 'if', 'for', and 'switch' effectively, you can create programs that perform complex logic and respond to different situations.