×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go Nested If Statements

Last Updated : April 19, 2025

Golang nested if statement

Golang allows nested if statement, the nested if statement refers to the if statement within the if or else statement. The nested if statement means an if statement within the another if statement. In the below syntax, if condition1 is true then Block-1 and condion2 will be executed.

Syntax

if (condition1) {
   // Block-1   
   if (condition2) {
      // Block-2
   }
}

or 
if condition1 {
   // Block-1   
   if condition2 {
      // Block-2
   }
}

Flow chart

Go nested if statement

Example

Input three numbers and find the largest among them.

In this program, we will use nested if to find the largest among the given three numbers.

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

package main

import "fmt"

func main() {
	var a, b, c, large int

	fmt.Print("Enter first number: ")
	fmt.Scanf("%d", &a)
	fmt.Print("Enter second number: ")
	fmt.Scanf("%d", &b)
	fmt.Print("Enter third number: ")
	fmt.Scanf("%d", &c)
	
	if a > b {
		if a > c {
			large = a
		} else {
			large = c
		}
	} else {
		if b > c {
			large = b
		} else {
			large = c
		}
	}
	fmt.Println("Largest number is ", large)
}

Output

RUN 1:
Enter first number: 10
Enter second number: 20
Enter third number: 15
Largest number is  20

RUN 2:
Enter first number: 20
Enter second number: 10
Enter third number: 15
Largest number is  20

RUN 3:
Enter first number: 15
Enter second number: 15
Enter third number: 20
Largest number is  20

RUN 4:
Enter first number: 15
Enter second number: 20
Enter third number: 15
Largest number is  20

Go Nested If Statement Exercise

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

  1. A nested if statement is an ___ statement inside another if statement.
  2. In Go, a nested if statement can be used to check ___ conditions within the outer if statement.
  3. The condition in a nested if statement is checked ___ the outer if condition is true.

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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