0
0
Goprogramming~10 mins

If–else statement in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - If–else statement
Evaluate condition
Condition true?
NoExecute else block
Yes
Execute if block
End
The program checks a condition. If true, it runs the 'if' block; otherwise, it runs the 'else' block.
Execution Sample
Go
package main
import "fmt"
func main() {
  x := 10
  if x > 5 {
    fmt.Println("x is greater than 5")
  } else {
    fmt.Println("x is 5 or less")
  }
}
This code checks if x is greater than 5 and prints a message accordingly.
Execution Table
StepConditionResultBranch TakenOutput
1x > 5 (10 > 5)trueif block"x is greater than 5" printed
2End of if-elseN/AProgram endsNo further output
💡 Condition true at step 1, so if block executed; program ends after printing.
Variable Tracker
VariableStartAfter Step 1Final
xundefined1010
Key Moments - 2 Insights
Why does the program print "x is greater than 5" and not the else message?
Because at step 1 in the execution table, the condition x > 5 is true (10 > 5), so the if block runs, skipping the else block.
What happens if the condition is false?
If the condition were false, the else block would run instead, as shown in the 'Branch Taken' column for the else path.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the condition result at step 1?
Aundefined
Btrue
Cfalse
Derror
💡 Hint
Check the 'Result' column in the first row of the execution table.
At which step does the program decide which branch to take?
AStep 2
BBefore Step 1
CStep 1
DAfter Step 2
💡 Hint
Look at the 'Condition' and 'Branch Taken' columns in the execution table.
If x was 3 instead of 10, what would the output be according to the execution flow?
A"x is 5 or less"
B"x is greater than 5"
CNo output
DProgram error
💡 Hint
Think about the condition x > 5 and which branch runs when false.
Concept Snapshot
if condition {
  // code runs if condition true
} else {
  // code runs if condition false
}
Checks condition once, runs one block only.
Full Transcript
This visual trace shows how an if-else statement works in Go. The program sets x to 10. It then checks if x is greater than 5. Since 10 is greater than 5, the condition is true, so the program runs the code inside the if block and prints "x is greater than 5". The else block is skipped. The variable x stays 10 throughout. If the condition were false, the else block would run instead. This helps the program choose between two paths based on a condition.