Golang program to calculate the factorial of a given number using goto statement

Here, we are going to learn how to calculate the factorial of a given number using goto statement in Golang (Go Language)?
Submitted by Nidhi, on March 01, 2021 [Last updated : March 03, 2023]

Golang goto Statement Example – Calculate the factorial of a given number

Problem Solution:

In this program, we will read an integer number from the user and then calculate the factorial of the given number and print the result on the console screen.

Golang code to calculate the factorial of a given number using goto statement

Program/Source Code:

The source code to calculate the factorial of a given number using the goto statement is given below. The given program is compiled and executed successfully.

// Golang program to calculate the factorial of a
// given number using the goto statement

package main

import "fmt"

func main() {
	var num int = 0
	var fact int = 1

	fmt.Print("Enter Number: ")
	fmt.Scanf("%d", &num)

	if num < 0 {
		fmt.Print("Factorial of negative number doesn't exist.")
	} else {
		if num == 0 {
			fact = 1
		} else {
		MyLbl:
			fact = fact * num

			num = num - 1

			if num > 1 {
				goto MyLbl
			}
		}
		fmt.Printf("Factorial is: %d", fact)
	}
}

Output:

RUN 1:
Enter Number: 7
Factorial is: 5040

RUN 2:
Enter Number: 1
Factorial is: 1

RUN 3:
Enter Number: -1
Factorial of negative number doesn't exist. 

RUN 4:
Enter Number: 0
Factorial is: 1

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.

In the main() function, we created two variables num, fact,  which are initialized with 0, 1 respectively, and also created a label MyLbl.

fact=fact*num
        
num=num-1
        
if(num>1){
    goto MyLbl
}
fmt.Printf("Factorial is: %d",fact)

In the above code, we multiply the num with fact and assigned the result into the fact variable. We decreased the value of the num variable by 1 till it reaches 1 using the goto statement. At last, we printed the calculated factorial on the console screen.

Golang goto Statement Programs »





Comments and Discussions!

Load comments ↻





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