×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang if-else statement

Last Updated : April 19, 2025

Golang if else statement

The if-else statement is used to execute two blocks based on the condition. The if statement contains the condition, if the condition is true then the true-block (set of statements of if block) will be executed, if the condition is not true then the false-block (set of the statements of else block) will be executed.

Syntax

if(condition){
    // true-block
}else{
    // false-block
}

or 

if condition {
    // true-block
}else{
    // false-block
}

Flow chart

Go if-else statement

Example 1

Input the age of a person and check whether the person is eligible for voting or not.

In this program, we will use the if-else statement to check whether the person is eligible for voting or not.

// Golang program to demonstrate the
// example of the if else statement

package main

import "fmt"

func main() {
	var age int

	fmt.Print("Input the age: ")
	fmt.Scanf("%d", &age)

	if age >= 18 {
		fmt.Println("Person is eligible for voting.")
	} else {
		fmt.Println("Person is not eligible for voting.")
	}
}

Output

RUN 1:
Input the age: 32
Person is eligible for voting.

RUN 2:
Input the age: 12
Person is not eligible for voting.

Example 2

Input an integer value to check whether the given number is positive or negative.

In this program, we will use the if-else statement to check whether the given number is positive or negative.

// Golang program to demonstrate the
// example of the if else statement

package main

import "fmt"

func main() {
	var num int

	fmt.Print("Input an integer number: ")
	fmt.Scanf("%d", &num)

	if num >= 0 {
		fmt.Println("Number is positive.")
	} else {
		fmt.Println("Number is negative.")
	}
}

Output

RUN 1:
Input an integer number: 108
Number is positive.

RUN 2:
Input an integer number: -10
Number is negative.

Go If-Else Statement Exercise

Select the correct option to complete each statement about if-else statements in Go.

  1. The ___ keyword is used to specify an alternative block of code when the condition in an if statement is false.
  2. In Go, the else block is always executed when the if condition evaluates to ___.
  3. The else block can only be used ___ the if statement in Go.

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.