ProgramGuru

else if Statement

Start with Go else if Statement

Use an else if chain when you have more than two mutually exclusive outcomes. Conditions are checked from top to bottom until one matches.

What you’ll learn

  • Build a multi-way choice using else if.
  • Explain short-circuiting of later branches.
  • Order conditions to avoid incorrect matches.

Understand the idea

In Go, write else if as two words. The first true branch executes and the remaining conditions in the chain are not evaluated. An optional final else catches values that matched none of the earlier conditions.

The order of the conditions matters. Put narrow or high-priority cases before broad cases, or a broad condition may consume values that should match a later condition.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for else ifConditions are tried in order until one branch matches.Test >= 90Step 1Otherwise >= 75Step 2Otherwise >= 50Step 3Fallback elseStep 4Conditions are tried in order until one branch matches.
Conditions are tried in order until one branch matches.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func main() {
	score := 82
	if score >= 90 {
		fmt.Println("Grade A")
	} else if score >= 75 {
		fmt.Println("Grade B")
	} else if score >= 50 {
		fmt.Println("Grade C")
	} else {
		fmt.Println("Needs improvement")
	}
}

Output

Grade B

Trace what the program does

With 82, the first test (score >= 90) fails. The next test (score >= 75) succeeds, so the program prints Grade B and skips the rest. You never get multiple grades from this single chain.

Avoid common mistakes

  • If the broad condition score >= 50 comes first, higher scores may be classified incorrectly.
  • elseif is not a Go keyword; write else if.

Try it yourself

Test scores 95, 75, 49 and 50. State which branch each value enters before running the program.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What happens after the first true branch of an else-if chain?
Choose one answer. You can try again.

Answer and explanation

Go skips the remaining branches

Correct. With 82, the first test (score >= 90) fails.

What you should remember

You have practiced Go else if Statement in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Nested if Statements →