Go if-else if-else Conditional Statements

Conditional statements are used to execute certain code blocks only if certain conditions are met. Here are some examples of conditional statements in Go along with their outputs:

  1. If statement: The if statement is used to execute a block of code only if a certain condition is true. Here’s an example:
package main

import "fmt"

func main() {
    x := 10

    if x > 5 {
        fmt.Println("x is greater than 5")
    }
}

Output:

x is greater than 5
  1. If-else statement: The if-else statement is used to execute one block of code if a condition is true, and another block of code if the condition is false. Here’s an example:
package main

import "fmt"

func main() {
    x := 10

    if x > 5 {
        fmt.Println("x is greater than 5")
    } else {
        fmt.Println("x is less than or equal to 5")
    }
}

Output:

x is greater than 5
  1. Else-if statement: The else-if statement is used to execute one block of code if a condition is true, and another block of code if another condition is true. Here’s an example:
package main

import "fmt"

func main() {
    x := 10

    if x > 5 {
        fmt.Println("x is greater than 5")
    } else if x < 5 {
        fmt.Println("x is less than 5")
    } else {
        fmt.Println("x is equal to 5")
    }
}

Output:

x is greater than 5

Complete code example:

package main

import "fmt"

func main() {
    x := 10

    if x > 100 {
        fmt.Println("x is greater than 100")
    } else if x > 50 {
        fmt.Println("x is greater than 50 but less than or equal to 100")
    } else if x > 25 {
        fmt.Println("x is greater than 25 but less than or equal to 50")
    } else {
        fmt.Println("x is less than or equal to 25")
    }
}

Output:

x is less than or equal to 25

In the example above, the if statement is used to check if x is greater than 100. If the condition is true, the first block of code is executed. If the condition is false, the else-if statement checks if x is greater than 50 but less than or equal to 100. If the condition is true, the second block of code is executed. If the condition is false, the second else-if statement checks if x is greater than 25 but less than or equal to 50. If the condition is true, the third block of code is executed. If all the conditions are false, the else statement is executed and the fourth block of code is executed.

Follow us on social media
Follow Author