Golang程序创建一个简单的递归函数

如何在Golang中创建一个简单的递归函数

在本教程中,我们将看到如何在算法和实例的帮助下编写一个简单的递归函数Golang。在第一个例子中,我们将按升序打印从1到N的数字,同样,在另一个例子中,我们将按降序打印从1到N的数字。

在编程方面,如果我们在同一个函数中调用该函数并有一个基础条件,那么该函数就是一个递归函数。每当基础条件得到满足时,函数的调用就会停止,我们开始回滚到调用该函数的最后一步。

语法

func functionName(arguments) returnType {

   // Base condition
   // Function calling according to the logic
}

示例 1

在这个例子中,我们将看到递归函数在Golang中按升序打印前10个数字。

package main
import (

   // fmt package provides the function to print anything
   "fmt"
)
func printAscendingOrder(number int) {

   // base condition of the function whenever the number becomes zero the function calls will stop
   if number == 0 {
      return
   }

   // calling the function within the function to make it recursive also, passing the number one lesser than the current value
   printAscendingOrder(number - 1)

   // printing the value of the number in
   // the current function calling the state
   fmt.Printf("%d ", number)
}
func main() {

   // declaring the variable
   var number int

   // initializing the variable
   number = 10
   fmt.Println("Golang program to print the number in ascending order with the help of a simple recursive function.")

   // calling the recursive function
   printAscendingOrder(number)
   fmt.Println()
}

输出

Golang program to print the number in ascending order with the help of a simple recursive function.
1 2 3 4 5 6 7 8 9 10

示例 2

在这个例子中,我们将看到递归函数在Golang中按降序打印前10个数字。

package main
import (

   // fmt package provides the function to print anything
   "fmt"
)
func printDescendingOrder(number int) {

   // base condition of the function whenever the number becomes zero the function calls will stop
   if number == 0 {
      return
   }

   // printing the value of the number in the current function calling the state
   fmt.Printf("%d ", number)

   // calling the function within the function to make it recursive also, passing the number one lesser than the current value
   printDescendingOrder(number - 1)
}
func main() {

   // declaring the variable
   var number int

   // initializing the variable
   number = 10
   fmt.Println("Golang program to print the number in descending order with the help of a simple recursive function.")

   // calling the recursive function
   printDescendingOrder(number)
   fmt.Println()
}

输出

Golang program to print the number in descending order with the help of a simple recursive function.
10 9 8 7 6 5 4 3 2 1

结论

这就是在Golang中创建一个简单的递归函数的方法,有两个例子,我们按升序和降序打印了从1到N的数字。要了解更多关于Golang的知识,你可以探索这些教程。