如何在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 的更多信息,您可以浏览这些教程。

更新于: 2023年1月11日

221 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.