The if statement in Go is used to test the condition. If it evaluates to true, the body of the statement is executed. If it evaluates to false, if block is skipped.
Syntax :
- if(boolean_expression) {
-
- }
Go if example
- package main
- import "fmt"
- func main() {
-
- var a int = 10
-
- if( a % 2==0 ) {
- fmt.Printf("a is even number" )
- }
- }
Output:
Go if-else
The if-else is used to test the condition. If condition is true, if block is executed otherwise else block is executed.
Syntax :
- if(boolean_expression) {
-
- } else {
-
- }
Go if-else example
- package main
- import "fmt"
- func main() {
-
- var a int = 10;
-
- if ( a%2 == 0 ) {
-
- fmt.Printf("a is even\n");
- } else {
-
- fmt.Printf("a is odd\n");
- }
- fmt.Printf("value of a is : %d\n", a);
- }
Output:
a is even
value of a is : 10
Go If-else example: with input from user
- func main() {
- fmt.Print("Enter number: ")
- var input int
- fmt.Scanln(&input)
- fmt.Print(input)
-
- if( input % 2==0 ) {
-
- fmt.Printf(" is even\n" );
- } else {
-
- fmt.Printf(" is odd\n" );
- }
- }
Output:
Enter number: 10
10 is even
Go If else-if chain
The Go if else-if chain is used to execute one statement from multiple conditions.
We can have N numbers of if-else statement. It has no limit.
The curly braces{ } are mandatory in if-else statement even if you have one statement in it. The else-if and else keyword must be on the same line after the closing curly brace }.
Go If else-if chain Example
-
- package main
- import "fmt"
- func main() {
- fmt.Print("Enter text: ")
- var input int
- fmt.Scanln(&input)
- if (input < 0 || input > 100) {
- fmt.Print("Please enter valid no")
- } else if (input >= 0 && input < 50 ) {
- fmt.Print(" Fail")
- } else if (input >= 50 && input < 60) {
- fmt.Print(" D Grade")
- } else if (input >= 60 && input < 70 ) {
- fmt.Print(" C Grade")
- } else if (input >= 70 && input < 80) {
- fmt.Print(" B Grade")
- } else if (input >= 80 && input < 90 ) {
- fmt.Print(" A Grade")
- } else if (input >= 90 && input <= 100) {
- fmt.Print(" A+ Grade")
- }
- }
Output:
Go Nested if-else
We can also nest the if-else statement to execute one statement from multiple conditions.
Syntax
- if( boolean_expression 1) {
-
- if(boolean_expression 2) {
-
- }
- }
nested if-else example
- package main
- import "fmt"
- func main() {
-
- var x int = 10
- var y int = 20
-
- if( x >=10 ) {
-
- if( y >= 10 ) {
-
- fmt.Printf("Inside nested If Statement \n" );
- }
- }
- fmt.Printf("Value of x is : %d\n", x );
- fmt.Printf("Value of y is : %d\n", y );
- }
Output:
Inside nested If Statement
Value of x is : 10
Value of y is : 20
No comments:
Post a Comment