Home »
Golang »
Golang Find Output Programs
Golang Recursion | Find Output Programs | Set 2
This section contains the Golang recursion find output programs (set 2) with their output and explanations.
Submitted by Nidhi, on August 27, 2021
Program 1:
package main
import "fmt"
func main() {
static num int= 0
fmt.Println("Num: ",num)
num++
if(num==5){
return
}
main()
}
Output:
./prog.go:5:12: syntax error: unexpected num at end of statement
Explanation:
The above program will generate a syntax error because the static keyword is not available in the Go language.
Program 2:
package main
import "fmt"
var num int = 0
var ptr *int = &num
func main() {
fmt.Println("Num: ", *ptr)
*ptr++
if *ptr == 5 {
return
}
main()
}
Output:
Num: 0
Num: 1
Num: 2
Num: 3
Num: 4
Explanation:
Here, we created a global variable num and a pointer ptr. The pointer ptr is initialized with the address of the num variable. Then we called the main() function recursively. Every time value of *ptr increased by 1 and printed value of the num variable. When the value *ptr is equal to 5 then the program gets terminated.
Program 3:
package main
import "fmt"
var num int = 0
var ptr *int = &num
func main() {
fmt.Println("Num: ", *ptr)
*ptr++
if num == 5 {
return
}
main()
}
Output:
Num: 0
Num: 1
Num: 2
Num: 3
Num: 4
Explanation:
Here, we created a global variable num and a pointer ptr. The pointer ptr is initialized with the address of the num variable. Then we called the main() function recursively. Every time value of *ptr increased by 1 and printed value of the num variable. When the value num is equal to 5 then the program gets terminated.
Program 4:
package main
import "fmt"
func fun(n int, p int) int {
if p != 0 {
return (n * fun(n, p-1))
} else {
return 1
}
}
func main() {
var result = 0
result = fun(2, 3)
fmt.Println("Result: ", result)
}
Output:
Result: 8
Explanation:
Here, we created two functions fun() and main(). The fun() is a recursive function, which is used to calculate the power of a specified number and return the result to the calling function.
In the main() function, we called the fun() function with the specified number and printed the result on the screen.
Program 5:
package main
import "fmt"
func fun(n, p int) int {
if p != 0 {
return (n * fun(n, p-1))
} else {
return 1
}
}
func main() {
var result = 0
result = fun(2, 3)
fmt.Println("Result: ", result)
}
Output:
Result: 8
Explanation:
Here, we created two functions fun() and main(). The fun() is a recursive function, which is used to calculate the power of a specified number and return the result to the calling function.
In the main() function, we called the fun() function with the specified number and printed the result on the screen.
Golang Find Output Programs »