Recursion

Go Functions: Recursion #

A recursive function is a function that calls itself. Recursion is useful for problems that can be broken down into smaller, similar problems. Every recursive function needs a stop condition to prevent infinite recursion.


Example 1: Counting with Recursion #

In this example, testcount() calls itself until the variable x reaches 11:

package main
import "fmt"

func testcount(x int) int {
    if x == 11 {
        return 0
    }
    fmt.Println(x)
    return testcount(x + 1)
}

func main(){
    testcount(1)
}

Result:

1
2
3
4
5
6
7
8
9
10

Explanation:

  • The function prints x and then calls itself with x + 1.
  • The recursion stops when x == 11.
  • Recursion allows looping through data without using a traditional for loop.

Example 2: Factorial Using Recursion #

Here, factorial_recursion() calculates the factorial of a number:

package main
import "fmt"

func factorial_recursion(x float64) (y float64) {
    if x > 0 {
        y = x * factorial_recursion(x-1)
    } else {
        y = 1
    }
    return
}

func main() {
    fmt.Println(factorial_recursion(4))
}

Result:

24

Explanation:

  • The function multiplies x by the factorial of x-1.
  • When x reaches 0, the recursion stops and returns 1.
  • The final result is 4 * 3 * 2 * 1 = 24.

Tips for Recursive Functions #

  • Always include a stop condition to avoid infinite loops.
  • Recursive functions can be memory and CPU intensive, so test carefully.
  • They are particularly useful for mathematical problems and data structures like trees and linked lists.
  • Experimenting and modifying recursion examples helps understand how they work.

Recursion can be an elegant and powerful tool when used correctly in Go programs.