Skip to main content
Master Go’s control flow structures through practical exercises covering conditionals, switches, and loops.

If Statements

Practice decision-making with if statements and conditional logic.
Objective: Use if-else statements to categorize agesPrint different messages based on age ranges.Expected Output:
  • Age > 60: “Getting older”
  • Age > 30: “Getting wiser”
  • Age > 20: “Adulthood”
  • Age > 10: “Young blood”
  • Otherwise: “Booting up”
Key Concepts:
  • If-else chains
  • Comparison operators
  • Order of conditions matters
Approach:
age := 35
if age > 60 {
    fmt.Println("Getting older")
} else if age > 30 {
    fmt.Println("Getting wiser")
}
// Continue the chain...
Objective: Refactor complex if statementsSimplify nested or complex if statements for better readability.Key Concepts:
  • Code simplification
  • Logical operators
  • Guard clauses
Approach: Look for opportunities to:
  • Combine conditions with && or ||
  • Use early returns
  • Eliminate unnecessary nesting
Objective: Validate command-line argumentsCheck if the correct number of arguments are provided.Key Concepts:
  • Length checking
  • Input validation
  • Error messages
Approach:
if len(os.Args) < 2 {
    fmt.Println("Please provide an argument")
    return
}
Objective: Classify charactersDetermine if a given character is a vowel or consonant.Key Concepts:
  • Character comparison
  • Multiple conditions
  • String indexing
Approach:
  1. Get first character from input
  2. Compare against vowels (a, e, i, o, u)
  3. Use || for multiple vowel checks

Error Handling with If

Learn to handle errors gracefully using if statements.
Objective: Parse and validate ratingsConvert string ratings to numbers and validate them.Key Concepts:
  • strconv package
  • Error checking
  • Input validation
Approach:
rating, err := strconv.Atoi(input)
if err != nil {
    fmt.Println("Invalid rating")
    return
}
Objective: Check number parity with error handlingDetermine if a number is odd or even, handling invalid input.Key Concepts:
  • Modulo operator %
  • Error handling pattern
  • Type conversion
Approach:
num, err := strconv.Atoi(os.Args[1])
if err != nil {
    fmt.Println("Not a valid number")
    return
}
if num%2 == 0 {
    fmt.Println("Even")
} else {
    fmt.Println("Odd")
}
Objective: Determine if a year is a leap yearImplement leap year logic with proper input validation.Rules:
  • Divisible by 4: leap year
  • EXCEPT divisible by 100: not a leap year
  • EXCEPT divisible by 400: leap year
Approach:
year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)
Objective: Refactor leap year logicMake the leap year checker more concise and readable.Key Concepts:
  • Boolean expressions
  • Operator precedence
  • Code clarity
Approach: Combine all conditions into a single, clear boolean expression.
Objective: Calculate days for any monthReturn the number of days in a given month, considering leap years.Key Concepts:
  • Multiple conditions
  • Combining if statements
  • Edge cases
Approach:
  1. Check for 30-day months
  2. Check for 31-day months
  3. Handle February with leap year logic

Switch Statements

Use switch statements for cleaner multi-way branching.
Objective: Classify earthquake magnitudesDescribe earthquake effects based on Richter scale values.Key Concepts:
  • Switch with expressions
  • Case ranges
  • Fallthrough behavior
Approach:
switch {
case magnitude < 2.0:
    fmt.Println("Micro")
case magnitude < 3.0:
    fmt.Println("Minor")
case magnitude < 4.0:
    fmt.Println("Light")
// Continue...
}
Objective: Enhanced Richter scale classifierAdd more granular classifications and descriptions.Approach: Expand the previous exercise with more detailed magnitude ranges and descriptions.
Objective: Unit conversion toolCreate a unit converter using switch statements.Key Concepts:
  • Switch on strings
  • Case matching
  • Conversion formulas
Approach:
switch unit {
case "km":
    // Convert to miles
case "mi":
    // Convert to kilometers
case "c":
    // Convert Celsius to Fahrenheit
}
Objective: String operations based on commandsPerform different string operations based on input commands.Operations:
  • Uppercase
  • Lowercase
  • Reverse
  • Length
Approach: Use switch to match command strings and apply the corresponding operation.
Objective: Reimplement days-in-month using switchUse a switch statement instead of if-else for cleaner code.Approach:
switch month {
case 1, 3, 5, 7, 8, 10, 12:
    days = 31
case 4, 6, 9, 11:
    days = 30
case 2:
    // Handle February with leap year
}

Loops

Master iteration with Go’s versatile for loop.

Basic Loops

Objective: Calculate sum using a basic loopSum numbers from 1 to 10 using a for loop.Approach:
sum := 0
for i := 1; i <= 10; i++ {
    sum += i
}
Objective: Add detailed output to loopPrint each step of the summation process.Approach: Print the current number and running total in each iteration.
Objective: Sum with user-provided limitSum numbers from 1 to N where N comes from input.Approach:
  1. Parse N from command-line argument
  2. Loop from 1 to N
  3. Calculate and print sum
Objective: Process only even numbersPrint or sum only even numbers in a range.Approach:
for i := 0; i <= 20; i += 2 {
    fmt.Println(i)
}
// Or use modulo:
for i := 0; i <= 20; i++ {
    if i%2 == 0 {
        fmt.Println(i)
    }
}

Loop Control

Objective: Exit loops early with breakUse break to stop a loop when a condition is met.Key Concepts:
  • Break statement
  • Loop termination
  • Conditional exit
Approach:
for i := 0; i < 100; i++ {
    if i == 50 {
        break
    }
    fmt.Println(i)
}
Objective: Control infinite loopsCreate and properly exit an infinite loop.Approach:
for {
    // Do work
    if shouldExit {
        break
    }
}

Multiplication Table

Objective: Generate multiplication tablesCreate a multiplication table for any given number.Approach:
num := 5
for i := 1; i <= 10; i++ {
    fmt.Printf("%d x %d = %d\n", num, i, num*i)
}
Objective: Generate multiple operation tablesCreate tables for addition, subtraction, multiplication, and division.Approach: Use nested loops or multiple loops for different operations.

Advanced Loop Exercises

Objective: Build a number guessing gameCreate a game where the player guesses a random number.Key Concepts:
  • Random numbers
  • User input in loops
  • Win conditions
Sub-exercises:
  • First Turn Winner: Check if player wins on first try
  • Random Messages: Show different messages for guesses
  • Double Guesses: Track guess attempts
  • Verbose Mode: Add detailed output
  • Enough Picks: Limit number of guesses
  • Dynamic Difficulty: Adjust range based on performance
Objective: Search for words in textFind and count occurrences of words in a string.Key Concepts:
  • String iteration
  • Pattern matching
  • Substring comparison
Approach: Loop through text and compare substrings to target word.
Objective: Find prime numbersGenerate prime numbers using nested loops.Key Concepts:
  • Prime number algorithm
  • Nested loops
  • Optimization techniques
Approach:
  1. Loop through numbers
  2. For each number, check divisibility
  3. Print if prime

Loop Best Practices

Performance Tips:
  • Use break to exit early when possible
  • Avoid unnecessary iterations
  • Consider loop scope for variable declarations
  • Use range loops for slices when appropriate (covered in Data Structures)

Next Steps

Data Structures

Work with arrays, slices, maps, and structs

Functions

Learn to write reusable functions

Build docs developers (and LLMs) love