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

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete