Go - Factorial Program using loop

We can find the factorial of a number n by multiplying it with its predecessors up to 1. For example, if we have to find factorial of 4, the equation will look like this:
  4! = 4*3*2*1 = 24.
We can find the factorial of a number n by multiplying it with its predecessors up to 1. For example, if we have to find factorial of 4, the equation will look like this:


Example 1. Go program to find factorial of a given number,

package main

import "fmt"

func main() {
number := 5
fmt.Println("Factorial of the number:", Factorial(number))
}

func Factorial(number int) int {
fact := 1
for i := 1; i <= number; i++ {
fact *= i
}
return fact
}

Output:




Example 2. Go program to find factorial of a number from standard input,

package main

import "fmt"

func main() {
var number int
fmt.Println("Enter an integer value : ")

_, err := fmt.Scanf("%d", &number)

if err != nil {
fmt.Println(err)
}

fmt.Println("Factorial of the number:", Factorial(number))
}

func Factorial(number int) int {
fact := 1
for i := 1; i <= number; i++ {
fact *= i
}
return fact
}

Output:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example