0
0
Goprogramming~5 mins

Else–if ladder in Go

Choose your learning style9 modes available
Introduction
An else-if ladder helps you check many conditions one by one and run code for the first true condition.
When you want to choose between many options based on different conditions.
When you need to assign grades based on marks scored.
When you want to print different messages for different age groups.
When you want to check multiple ranges of values and act accordingly.
Syntax
Go
if condition1 {
    // code to run if condition1 is true
} else if condition2 {
    // code to run if condition2 is true
} else if condition3 {
    // code to run if condition3 is true
} else {
    // code to run if none of the above conditions are true
}
Conditions are checked from top to bottom. The first true condition runs its code and skips the rest.
The else block is optional and runs if no conditions are true.
Examples
Checks score and prints grade based on ranges.
Go
if score >= 90 {
    fmt.Println("Grade A")
} else if score >= 75 {
    fmt.Println("Grade B")
} else if score >= 60 {
    fmt.Println("Grade C")
} else {
    fmt.Println("Fail")
}
Prints age group based on age value.
Go
if age < 13 {
    fmt.Println("Child")
} else if age < 20 {
    fmt.Println("Teenager")
} else if age < 60 {
    fmt.Println("Adult")
} else {
    fmt.Println("Senior")
}
Sample Program
This program checks the temperature and prints a message based on the temperature range using else-if ladder.
Go
package main

import "fmt"

func main() {
    var temp int = 30

    if temp > 40 {
        fmt.Println("It's very hot today.")
    } else if temp > 30 {
        fmt.Println("It's warm today.")
    } else if temp >= 20 {
        fmt.Println("It's nice today.")
    } else {
        fmt.Println("It's cold today.")
    }
}
OutputSuccess
Important Notes
Make sure conditions do not overlap in a way that causes confusion.
Use else if ladder to keep code clean instead of many separate if statements.
Summary
Else-if ladder lets you check multiple conditions one after another.
Only the first true condition's code runs, others are skipped.
Use else for a default action if no conditions match.