×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang nested if statement

By IncludeHelp Last updated : October 05, 2024

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


Comments and Discussions!

Load comments ↻





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