Go if else programs teach your code to make decisions, such as “is this number even?” or “did the student pass?”. In this post, you will write fourteen classic decision programs with their exact output, including even or odd, largest of three, leap year and a grade calculator. After that, you will practice the if/else interview questions that test Go’s strict syntax rules.
This post builds on our Go basic math programs, because most conditions compare numbers. For the theory behind if, else and switch, read Go conditional statements explained. Every program here was tested on Go 1.27.
What are Go If Else Programs?
Go if else programs check a condition and run different code depending on the answer. A condition is any expression that gives true or false, such as age >= 18.
Think of a traffic signal. If the light is green, you go. Else if it is yellow, you slow down. Else, you stop. Your program does the same thing with if, else if and else.
Why Go If Else Programs Matter
Almost every program makes choices, so Go if else programs appear everywhere. For example, an app shows an error if a password is wrong, gives a discount if the cart is big enough, and blocks a payment if the balance is low. These are also the first logic questions in most coding rounds.
- Validation: check that input is in range before you use it.
- Business rules: apply tax slabs, discounts and grades.
- Interviews: even/odd, leap year and largest of three are asked again and again.
How Go If Else Programs Work
In Go if else programs, Go checks each condition from top to bottom. It runs the first block whose condition is true and skips the rest. If no condition is true, it runs the else block, when there is one.

Go has a few strict rules for if. The table below sums them up.
| Rule | Correct | Wrong |
|---|---|---|
| Braces are required | if x > 0 { … } | if x > 0 fmt.Println(x) |
| No brackets needed | if x > 0 { | if (x > 0) { works but gofmt removes them |
| else on the same line as } | } else { | } then else on a new line |
| Condition must be bool | if count > 0 { | if count { |
| Optional short statement | if n := 5; n > 0 { | Using n after the if block |
Number Checks in Go If Else Programs
Let’s begin with the number checks that every beginner should know. These Go if else programs are the base for all later logic.
Program 1: Pass or Fail
This is the simplest of all Go if else programs. If the marks are 40 or more, the student passes. Otherwise, the student fails.
package main
import "fmt"
func main() {
marks := 65 // := creates a variable and sets its value
// if runs the first block when the condition is true
if marks >= 40 {
fmt.Println("Marks:", marks)
fmt.Println("Result: Pass")
} else {
// else runs when the condition is false
fmt.Println("Marks:", marks)
fmt.Println("Result: Fail")
}
}
Marks: 65
Result: Pass
Go checks marks >= 40, and 65 is bigger than 40, so the condition is true. That is why the first block runs and the else block is skipped. Change marks to 30 and run it again to see the other branch.
Program 2: Even or Odd
A number is even when it leaves no remainder after division by 2.
package main
import "fmt"
func main() {
numbers := []int{7, 10, 0, -3} // a slice is a list of values
// range gives each number in turn; _ skips its position
for _, number := range numbers {
if number%2 == 0 { // % gives the remainder
fmt.Println(number, "is even")
} else {
fmt.Println(number, "is odd")
}
}
}
7 is odd
10 is even
0 is even
-3 is odd
The loop takes one number at a time and finds the remainder after dividing by 2. If the remainder is 0, the number is even. For -3, Go gives -3 % 2 = -1, which is not 0, so the else branch runs. That is why we compare with 0, not with 1.
Program 3: Positive, Negative or Zero
Here we need three branches, so we use else if.
package main
import "fmt"
func main() {
numbers := []int{15, -8, 0}
for _, number := range numbers {
if number > 0 {
fmt.Println(number, "is positive")
} else if number < 0 { // checked only when the first test is false
fmt.Println(number, "is negative")
} else {
fmt.Println(number, "is zero")
}
}
}
15 is positive
-8 is negative
0 is zero
Go first asks if the number is above 0. If not, it asks if it is below 0. When both answers are no, the only choice left is zero, so the else block runs.
Program 4: Largest of Three Numbers
This is a top interview question. We use &&, which means both conditions must be true.
package main
import "fmt"
func main() {
first, second, third := 42, 87, 63
// && means "and": both sides must be true
if first >= second && first >= third {
fmt.Println("Largest:", first)
} else if second >= first && second >= third {
fmt.Println("Largest:", second)
} else {
fmt.Println("Largest:", third)
}
// Go 1.21+ has a built-in max that does the same job
fmt.Println("Using max():", max(first, second, third))
}
Largest: 87
Using max(): 87
The program checks if first beats both others, then if second does. If neither wins, third must be the largest. We use >= instead of >, so equal numbers still give an answer. In real code, the built-in max does the same job in one line.
Program 5: Leap Year Check
A year is a leap year if it divides by 4 but not by 100, or if it divides by 400.
package main
import "fmt"
func main() {
years := []int{2024, 1900, 2000, 2026}
for _, year := range years {
// Step 1: divisible by 4 but not by 100 (!= means "not equal")
normalLeap := year%4 == 0 && year%100 != 0
// Step 2: or divisible by 400
centuryLeap := year%400 == 0
// || means "or": one true side is enough
if normalLeap || centuryLeap {
fmt.Println(year, "is a leap year")
} else {
fmt.Println(year, "is not a leap year")
}
}
}
2024 is a leap year
1900 is not a leap year
2000 is a leap year
2026 is not a leap year
We split the rule into two named true or false values, so each part is easy to read. Then the if checks whether either one is true. 1900 divides by 100 but not by 400, so it is not a leap year. Many people get this one wrong, so test it every time.
Program 6: Divisible by 5 and 11
This program checks two remainders at once with &&.
package main
import "fmt"
func main() {
numbers := []int{55, 110, 25}
for _, number := range numbers {
if number%5 == 0 && number%11 == 0 {
fmt.Println(number, "is divisible by both 5 and 11")
} else {
fmt.Println(number, "is not divisible by both")
}
}
}
55 is divisible by both 5 and 11
110 is divisible by both 5 and 11
25 is not divisible by both
A number divides evenly when its remainder is 0. The && makes sure both remainders are 0. 25 divides by 5 but not by 11, so it goes to the else branch.
Real-Life Go If Else Programs
These Go if else programs use the same ideas for everyday rules.
Program 7: Grade Calculator
The order of conditions matters here. We check the highest range first.
package main
import "fmt"
func main() {
allMarks := []int{92, 76, 58, 35}
for _, marks := range allMarks {
var grade string // starts as an empty string ""
if marks >= 90 {
grade = "A"
} else if marks >= 75 {
grade = "B"
} else if marks >= 50 {
grade = "C"
} else {
grade = "Fail"
}
fmt.Printf("Marks %d: Grade %s\n", marks, grade) // %d prints a number, %s a string
}
}
Marks 92: Grade A
Marks 76: Grade B
Marks 58: Grade C
Marks 35: Grade Fail
For each mark, Go walks down the chain and stops at the first true check. Since 92 also passes marks >= 75, putting that check first would give the wrong grade. Always go from the strictest rule to the loosest.
Program 8: Voting Eligibility with a Short Statement
Go lets you run a short statement before the condition. The variable you create lives only inside the if and else blocks.
package main
import "fmt"
func main() {
birthYear := 2010
// The part before ; runs first and creates age.
// The part after ; is the condition.
if age := 2026 - birthYear; age >= 18 {
fmt.Println("Age", age, "- can vote")
} else {
yearsLeft := 18 - age
fmt.Println("Age", age, "- can vote in", yearsLeft, "years")
}
}
Age 16 - can vote in 2 years
First, Go works out age as 16. Then it checks age >= 18, which is false, so the else block runs. age exists in both branches, but after the closing brace it is gone.
Program 9: Vowel or Consonant
This program checks a letter. strings.ContainsRune saves us from writing five || checks.
package main
import (
"fmt"
"strings"
"unicode" // unicode has helpers for letters and digits
)
func main() {
// A rune is a single character, written in single quotes
letters := []rune{'a', 'G', 'E', '7'}
for _, letter := range letters {
lower := unicode.ToLower(letter) // 'G' becomes 'g'
if !unicode.IsLetter(letter) { // ! means "not"
fmt.Printf("%c is not a letter\n", letter) // %c prints a character
} else if strings.ContainsRune("aeiou", lower) {
fmt.Printf("%c is a vowel\n", letter)
} else {
fmt.Printf("%c is a consonant\n", letter)
}
}
}
a is a vowel
G is a consonant
E is a vowel
7 is not a letter
First, the program rules out anything that is not a letter, such as ‘7’. Next, it looks for the small letter inside “aeiou”. unicode.ToLower makes the check work for capital letters too.
Program 10: Profit or Loss
This program compares two prices and reports the result.
package main
import "fmt"
func main() {
costPrice := 1200.0
sellingPrice := 1350.0
if sellingPrice > costPrice {
profit := sellingPrice - costPrice
profitPercent := profit / costPrice * 100
fmt.Printf("Profit: %.2f (%.1f%%)\n", profit, profitPercent) // %% prints a % sign
} else if sellingPrice < costPrice {
loss := costPrice - sellingPrice
fmt.Printf("Loss: %.2f\n", loss)
} else {
fmt.Println("No profit, no loss")
}
}
Profit: 150.00 (12.5%)
Go compares the selling price with the cost price. Here it is higher, so the program finds the profit and its percentage. Each branch only calculates what it needs.
Program 11: Free Delivery Check
Many shops give free delivery above a certain cart value. Go if else programs handle rules like this one easily.
package main
import "fmt"
func main() {
cartTotals := []int{350, 499, 500, 1200} // cart values in rupees
freeDeliveryLimit := 500
deliveryCharge := 40
for _, cartTotal := range cartTotals {
if cartTotal >= freeDeliveryLimit {
fmt.Println("Cart", cartTotal, "- free delivery, pay", cartTotal)
} else {
amountToPay := cartTotal + deliveryCharge
fmt.Println("Cart", cartTotal, "- delivery", deliveryCharge, "pay", amountToPay)
}
}
}
Cart 350 - delivery 40 pay 390
Cart 499 - delivery 40 pay 539
Cart 500 - free delivery, pay 500
Cart 1200 - free delivery, pay 1200
For each cart, Go compares the total with the limit of 500. A cart of 500 or more skips the charge. Smaller carts go to the else block, which adds 40 rupees. Look at 499 and 500 to see how >= treats the exact limit.
Program 12: Triangle Check and Type
Three sides make a triangle only if each pair adds up to more than the third side.
package main
import "fmt"
func main() {
sideA, sideB, sideC := 5, 5, 8
// Step 1: can these sides form a triangle at all?
if sideA+sideB <= sideC || sideA+sideC <= sideB || sideB+sideC <= sideA {
fmt.Println("Not a valid triangle")
} else if sideA == sideB && sideB == sideC { // Step 2: all three equal
fmt.Println("Equilateral triangle")
} else if sideA == sideB || sideB == sideC || sideA == sideC { // Step 3: two equal
fmt.Println("Isosceles triangle")
} else {
fmt.Println("Scalene triangle")
}
}
Isosceles triangle
First, the program rejects sides that cannot meet. Then it checks whether all three sides match, and then whether two match. Here 5 and 5 are equal, so the triangle is isosceles.
Program 13: ATM Withdrawal Rules
Real rules often need nested checks. Here we use early returns instead, which keeps the code flat.
package main
import "fmt"
// withdraw checks the ATM rules and prints the result
func withdraw(balance int, amount int) {
if amount <= 0 {
fmt.Println("Enter a valid amount")
return // stop here and leave the function
}
if amount%100 != 0 {
fmt.Println("Amount must be in multiples of 100")
return
}
if amount > balance {
fmt.Println("Insufficient balance")
return
}
balanceLeft := balance - amount
fmt.Println("Please collect", amount, "- balance left:", balanceLeft)
}
func main() {
withdraw(5000, 1500)
withdraw(5000, 250)
withdraw(5000, 9000)
}
Please collect 1500 - balance left: 3500
Amount must be in multiples of 100
Insufficient balance
Each check returns as soon as it fails. Only an amount that passes all three checks reaches the last two lines. This “guard clause” style is very common in Go code.
Program 14: Character Type Check
This program sorts each character of a string into a group.
package main
import (
"fmt"
"unicode"
)
func main() {
// range over a string gives one character (rune) at a time
for _, character := range "aZ5 #" {
if unicode.IsUpper(character) {
fmt.Printf("%q is uppercase\n", character) // %q prints it in quotes
} else if unicode.IsLower(character) {
fmt.Printf("%q is lowercase\n", character)
} else if unicode.IsDigit(character) {
fmt.Printf("%q is a digit\n", character)
} else if unicode.IsSpace(character) {
fmt.Printf("%q is a space\n", character)
} else {
fmt.Printf("%q is a symbol\n", character)
}
}
}
'a' is lowercase
'Z' is uppercase
'5' is a digit
' ' is a space
'#' is a symbol
The loop takes each character and tries the checks in order. The unicode package answers each question for us. Anything that fails every check ends up as a symbol.
Go If Else Programs vs switch
When you have many branches that compare one value, switch is often cleaner. The diagram and table below compare the two.

| Feature | if else | switch |
|---|---|---|
| Best for | Ranges and mixed conditions | Many fixed values |
| Readability with 5+ cases | Gets long | Stays clean |
| Needs break | No | No, Go breaks automatically |
| Short statement | Yes | Yes |
| Example | marks >= 90 | case “Mon”, “Tue” |
So use if else for checks like “marks above 75”, and switch for menus or day names. We build switch programs later in this level.
Common Mistakes in Go If Else Programs
- else on a new line: Go needs
} else {on one line, or the code does not compile. - Non-bool conditions:
if count {fails, because Go does not treat numbers as true or false. - Wrong order of ranges: check
>= 90before>= 75, or every high score gets the lower grade. - Using = instead of ==:
if marks = 5is a compile error, which protects you from a classic bug. - Deep nesting: many levels of
ifare hard to read, so return early instead.
Best Practices for Go If Else Programs
- Return early for errors, so the main path stays on the left edge.
- Use the short statement form to keep temporary variables out of the rest of the function.
- Order conditions from most to least specific, so every value lands in the right branch.
- Let gofmt remove brackets around conditions, because Go style does not use them.
- Switch to switch when one value has many possible matches.
Go If Else Programs Interview Questions and Answers
Interviewers use Go if else programs to test both logic and syntax. Each program is complete, with real output from Go 1.27.
Syntax Questions on Go If Else Programs
Q1. Why does this program not compile?
package main
import "fmt"
func main() {
number := 5
if number > 3 {
fmt.Println("big")
}
else {
fmt.Println("small")
}
}
syntax error: unexpected keyword else, expected }
Go adds a semicolon at the end of a line that ends with }. So the if statement ends there, and the lonely else is an error. Always write } else { on one line.
Q2. Why does this program not compile?
package main
import "fmt"
func main() {
count := 3
if count { // count is an int, not true or false
fmt.Println("has items")
}
}
non-boolean condition in if statement
In Go, an if condition must be a bool. Write if count > 0 instead. Go never treats 0 as false like C does.
Q3. Does Go have a ternary operator like a ? b : c?
No. The Go team left it out to keep code easy to read. Use a short if else instead, or write a small helper function.
Q4. Why does this program not compile?
package main
import "fmt"
func main() {
if number := 10; number > 5 {
fmt.Println("inside:", number)
}
fmt.Println("outside:", number) // number does not exist here
}
undefined: number
A variable made in the if short statement only lives inside that if and its else blocks. Outside, it does not exist.
Q5. Can you write an if without braces for one line?
No. Braces are always required in Go, even for a single statement. This rule removes a whole class of bugs found in other languages.
Go If Else Programs: Logic and Output Questions
Q6. What does this program print?
package main
import "fmt"
// check prints its name and always returns false
func check(name string) bool {
fmt.Println("checking", name)
return false
}
func main() {
if check("A") && check("B") {
fmt.Println("both true")
}
if check("C") || check("D") {
fmt.Println("one true")
}
}
checking A
checking C
checking D
&& stops as soon as the left side is false, so “B” is never checked. || only stops when the left side is true, so both “C” and “D” run. This is called short-circuit evaluation.
Q7. What does this program print?
package main
import "fmt"
func main() {
value := 10
// This := makes a NEW value that exists only inside the if
if value := 5; value > 3 {
fmt.Println("inner value:", value)
}
fmt.Println("outer value:", value)
}
inner value: 5
outer value: 10
The value inside the if is a new variable that hides the outer one. This is called shadowing. The outer value keeps its old number, 10.
Q8. What does this program print?
package main
import "fmt"
func main() {
score := 75
if score > 50 {
fmt.Println("pass")
} else if score > 70 {
fmt.Println("distinction")
}
}
pass
The first true branch wins, and Go skips the rest. Since 75 > 50 is true, “distinction” never prints, even though it is also true.
Q9. How do you compare two strings without caring about case?
package main
import (
"fmt"
"strings"
)
func main() {
input := "YES"
// EqualFold compares two strings and ignores capital letters
if strings.EqualFold(input, "yes") {
fmt.Println("confirmed")
}
fmt.Println(input == "yes") // == cares about case
}
confirmed
false
== is case-sensitive, so “YES” is not equal to “yes”. strings.EqualFold ignores case.
Q10. What does this program print?
package main
import "fmt"
func main() {
first, second := 3, 7
if first > second {
fmt.Println("first is bigger")
} else if first == second {
fmt.Println("equal")
} else if second-first > 3 {
fmt.Println("far")
} else {
fmt.Println("near")
}
}
far
The first two checks are false. Then 7 – 3 is 4, which is greater than 3, so “far” prints.
Q11. How do you check if a number is between 1 and 100?
Combine two comparisons with &&: if number >= 1 && number <= 100. Go does not allow the math style 1 <= number <= 100.
Q12. What does this program print?
package main
import "fmt"
func main() {
number := 0
if number > 0 {
fmt.Println("positive")
}
if number == 0 {
fmt.Println("zero")
}
if number >= 0 {
fmt.Println("not negative")
}
}
zero
not negative
These are three separate if statements, not one chain. So Go checks all three, and two of them are true.
Clean Code Questions
Q13. How can you write an if inside a function that returns a value?
package main
import "fmt"
// sign returns a word that describes the number
func sign(number int) string {
if number > 0 {
return "positive"
}
if number < 0 {
return "negative"
}
return "zero"
}
func main() {
fmt.Println(sign(9), sign(-2), sign(0))
}
positive negative zero
There is no else here, because each return leaves the function. Go linters often suggest this style.
Q14. How do you check an error with if in one line?
Use the short statement form, as in if err := doWork(); err != nil { ... }. Here err is the error value, and nil means “no error”. This pattern appears in almost every Go file.
Q15. What does this program print?
package main
import "fmt"
func main() {
var name string // a string starts as "" (empty)
if name == "" {
fmt.Println("name is empty")
}
var ok bool // ok is a common Go name for a true or false result; it starts as false
if !ok {
fmt.Println("ok is false")
}
}
name is empty
ok is false
Uninitialized variables get zero values. A string starts as “” and a bool starts as false, so both checks pass.
Q16. Should you compare floats with == in an if?
Usually no, because of rounding errors. Check that the difference is tiny instead, as in if math.Abs(first-second) < 1e-9.
Q17. What does this program print?
package main
import "fmt"
func main() {
temperature := 31
if temperature > 30 {
fmt.Println("hot")
// An if inside another if is called a nested if
if temperature > 40 {
fmt.Println("very hot")
} else {
fmt.Println("but bearable")
}
}
}
hot
but bearable
The outer condition is true, so Go enters it. Inside, 31 is not above 40, so the inner else runs.
Practice Task
This task mixes the ideas from all the Go if else programs above. Write a program that takes an electricity bill in units and prints the amount: the first 100 units cost 5 rupees each, the next 100 cost 7 each, and anything above 200 costs 10 each. Hint: use if else from the highest slab down and add the parts.
Official Resources
Quick Recap
- Go if else programs run the first branch whose condition is true.
- Conditions must be bool, braces are required and
} else {must be on one line. - The short statement form,
if x := f(); x > 0, keeps variables local. &&and||stop early, which is called short-circuit evaluation.- Order range checks from strictest to loosest, and return early to avoid deep nesting.
What’s Next?
Next, your programs learn to repeat work. Read Go loop programs with output, where we print tables, factorials and Fibonacci numbers. For the theory of loops, see Go for loops explained with examples.


