Go Program to Find the Largest Among Three Numbers

1. Introduction

Determining the largest among a set of numbers is a fundamental programming problem that helps beginners understand conditional structures. In this guide, we'll create a Go program to identify the largest number among the three provided inputs.

2. Program Overview

Our Go program is architected to:

1. Request the user to input three distinct numbers.

2. Evaluate and identify the largest among the three numbers.

3. Present the determined largest number to the user.

3. Code Program

// Initiation of our Go program is marked by the main package declaration.
package main

// We integrate the fmt package for managing input and output operations.
import "fmt"

// Function to ascertain the largest among three integers.
func findLargest(x, y, z int) int {
    if x > y {
        if x > z {
            return x
        } else {
            return z
        }
    } else {
        if y > z {
            return y
        } else {
            return z
        }
    }
}

// The main function is the entryway to our program's execution.
func main() {
    var a, b, c int

    // We solicit the user to provide three numbers.
    fmt.Print("Enter three numbers separated by spaces: ")
    fmt.Scan(&a, &b, &c)

    // The largest among the three numbers is determined and then displayed.
    fmt.Printf("The largest number among %d, %d, and %d is: %d\n", a, b, c, findLargest(a, b, c))
}

Output:

For instance, if the user provides the numbers 12, 29, 7, the output of the program would be:
The largest number among 12, 29, and 7 is: 29

4. Step By Step Explanation

1. Package and Import Directives: We initiate with package main indicating our program's start. The fmt package is adopted for I/O functionalities.

2. Function to Determine the Largest Number: The findLargest function takes in three integers. Through nested conditional statements, it discerns the largest among them.

3. Variable Initialization: Three integer variables (a, b, c) are declared to capture the user's input.

4. Gathering User Input: Using fmt.Print, a prompt is rendered, and the user's input is gathered using fmt.Scan.

5. Computing and Showcasing the Result: The findLargest function is summoned with the user's inputs, and the outcome is presented using fmt.Printf.

Continue Learning with Java Guides

Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.

By Ramesh Fadatare - Udemy Instructor Partner

Comments