Q:

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

belongs to collection: Golang goto Statement Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 numfact,  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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Golang program to calculate the power of a given n... >>
<< Golang program to print the ASCII value of specifi...