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的内容,可以查看这些教程。