-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursive-function.go
More file actions
43 lines (33 loc) · 857 Bytes
/
recursive-function.go
File metadata and controls
43 lines (33 loc) · 857 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package main
import "fmt"
// same as other language we can create recursive function
// to call itself until the base condition met
func factorialLoop(value int) int {
if value < 0 {
return -1 // Factorial is not defined for negative numbers
} else if value == 0 {
return 1 // Factorial of 0 is 1
} else if value == 1 {
return 1 // Factorial of 1 is 1
}
result := 1
// if the number greater than 1 so we loop to multiply those number
for number := value; number > 1; number-- {
result *= number
}
return result
}
func factorialRecursive(value int) int {
if value <= 1 {
return 1
} else {
return value * factorialRecursive(value-1)
}
}
func main() {
// factorial recursive result
result := factorialRecursive(5)
fmt.Println("Recursive result :", result)
result = factorialLoop(5)
fmt.Println("Loop result :", result)
}