Junior — Middle
Selgitage, mida tähendab rekursiivsete funktsioonide kasutamine programmeerimises ja kuidas need töötavad.
sobes.tech AI
Vastus AI-lt
A recursive function is a function that calls itself to solve a problem. In programming, recursion is used to break down a complex task into simpler sub-tasks of the same type.
Working principle:
- The function calls itself with a modified argument, bringing the solution closer to the base case.
- The base case is the condition under which recursion ends to prevent infinite calls.
Example in Go — calculating the factorial of a number:
package main
import "fmt"
func factorial(n int) int {
if n == 0 {
return 1 // base case
}
return n * factorial(n-1) // recursive call
}
func main() {
fmt.Println(factorial(5)) // 120
}
Recursion is useful for working with trees, graphs, task division, but requires caution to avoid stack overflow.