For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:
Programming languages instructs the computer to make decisions on certain conditions. These decisions are made if and only if the pre-defined conditions are either true or false depending on the programmers mind. For making these types of decisions conditional statements are used.
Following are the Golang Conditional statements:
if
statement - executes some code only if one condition is true.
If condition {
//perform some instruction
}
if....else
statement - executes some code if the condition is true and executes another code if that condition is false.
if condition {
//do some instructions
}else {
//do some instructions
if....else....if
statement - executes different codes for more than two conditions.
If condition1 {
//do some instructions
}else if condition2 {
//do some instructions
}else {
do some instructions
}
We are using fmt println()
function for printing the string to the output screen. Here we are showing how to implement condition statements in the Go language. Here we are using a condition statement if-else
. Using this check the number 11 is odd or even by finding 11%2. And also check the number 15 is divisible by 3 or not. Here the variable n is assigned with 7 and checking that the number is less than 10 and print the corresponding statement. Given below are the steps which are used in the Go program.
STEP 1: Import the package fmt
STEP 2: Use condition statement if-else
to check whether (11%2=0)
STEP 3: If true print it as even else the number is odd using fmt.println()
STEP 4: Again use if
statement to check whether (15%3=0)
STEP 5: Use if
to check (n := 7; n < 0) and print corresponding statement
STEP 6: Use else
if
to check (n < 10) and print corresponding statement
package main
import "fmt"
func main() {
if 11%2 == 0 {
fmt.Println("11 is even")
} else {
fmt.Println("11 is odd")
}
if 15%3 == 0 {
fmt.Println("15 is divisible by 3")
}
if n := 7; n < 0 {
fmt.Println(n, "is negative")
} else if n < 10 {
fmt.Println(n, "has 1 digit")
} else {
fmt.Println(n, "has multiple digits")
}
}
11 is odd 15 is divisible by 3 7 has 1 digit