Go Program to Find the Factorial of a Number

1. Introduction

Factorial, often represented with the symbol !, is a mathematical function that multiplies a number by every number below it down to 1. In programming, calculating the factorial of a number is a classic use-case of recursion. In this blog post, we'll dive into how to construct a Go program to compute the factorial of a number submitted by the user.

2. Program Overview

Our Go program intends to:

1. Request the user to input a number.

2. Compute the factorial of the specified number.

3. Showcase the resultant factorial to the user.

3. Code Program

// We kickstart our program with the main package declaration, denoting our application's entry point.
package main

// The fmt package is utilized to handle input and output operations.
import "fmt"

// Recursive function to compute the factorial of an integer.
func factorial(n int) int {
    if n == 0 {
        return 1
    }
    return n * factorial(n-1)
}

// The execution journey of our program begins from the main function.
func main() {
    // An int variable is declared to hold the user's input.
    var number int

    // We prompt the user to supply a number, which is subsequently saved in the number variable.
    fmt.Print("Enter a number to find its factorial: ")
    fmt.Scan(&number)

    // We call the factorial function and present the result to the user.
    fmt.Printf("The factorial of %d is: %d\n", number, factorial(number))
}

Output:

Suppose the user enters the number 5. The output of the program would be:
The factorial of 5 is: 120

4. Step By Step Explanation

1. Package and Import Statements: The journey commences with package main, signifying the start of our program. For I/O functionalities, the fmt package is incorporated.

2. Factorial Function: Before our main function, we declare the factorial function which utilizes recursion. If the input is 0, the factorial is 1. For any other number n, the factorial is n times the factorial of n-1.

3. Variable Initialization: We employ the var keyword to initialize an integer variable, number, which will retain the user's input.

4. Accepting User Input: A prompt is displayed to the user via fmt.Print, and the input is collected and stored in the number variable using fmt.Scan.

5. Calculating and Displaying Factorial: The factorial function is invoked with the user's input, and its result is exhibited using fmt.Printf.

Comments