Algorithm
Code Examples
#1 Simple if statement in Golang Programming
Code -
Golang Programming
// Program to display a number if it is positive
package main
import "fmt"
func main() {
number := 15
// true if number is less than 0
if number > 0 {
fmt.Printf("%d is a positive number\n", number)
}
fmt.Println("Out of the loop")
}
Copy The Code &
Try With Live Editor
Output
The positive number is 15
Out of the loop
Out of the loop
#2 if...else statement in Golang Programming
Code -
Golang Programming
package main
import "fmt"
func main() {
number := 10
// checks if number is greater than 0
if number > 0 {
fmt.Printf("%d is a positive number\n", number)
} else {
fmt.Printf("%d is a negative number\n", number)
}
}
Copy The Code &
Try With Live Editor
Output
10 is a positive number
#3 if...if else ladder statement in Golang Programming
Code -
Golang Programming
// Program to relate two integers using =, > or < symbol
package main
import "fmt"
func main() {
number1 := 12
number2 := 20
if number1 == number2 {
fmt.Printf("Result: %d == %d", number1, number2)
} else if number1 > number2 {
fmt.Printf("Result: %d > %d", number1, number2)
} else {
fmt.Printf("Result: %d < %d", number1, number2)
}
}
Copy The Code &
Try With Live Editor
Output
Result: 12 < 20
#4 Nested if statement in Golang Programming
Code -
Golang Programming
package main
import "fmt"
func main() {
number1 := 12
number2 := 20
// outer if statement
if number1 >= number2 {
// inner if statement
if number1 == number2 {
fmt.Printf("Result: %d == %d", number1, number2)
// inner else statement
} else {
fmt.Printf("Result: %d > %d", number1, number2)
}
// outer else statement
} else {
fmt.Printf("Result: %d < %d", number1, number2)
}
}
Copy The Code &
Try With Live Editor
Output
Result: 12 < 20
Demonstration
Go if else - Go Lang Programming