This section contains the Golang recursion find output programs (set 1) with their output and explanations.
Program 1:
package main
import "fmt"
func calculateFactorial(num int)int{
if (num == 0)
return 1;
return num*calculateFactorial(num-1);
}
func main() {
var num = 5;
var fact= 0;
fact = calculateFactorial(num);
fmt.Println("Factorial is: ",fact);
}
Program 2:
package main
import "fmt"
func calculateFactorial(num int) int {
if num == 0 {
return 1
}
return num * calculateFactorial(num-1)
}
func main() {
var num = 5
var fact = 0
fact = calculateFactorial(num)
fmt.Println("Factorial is: ", fact)
}
Program 3:
package main
import "fmt"
func calculateFactorial(num int) int {
if num == 0 {
return 1
}
return num * calculateFactorial(num-1)
}
func main() {
var num = 5
var ptr *int = &num
var fact = 0
fact = calculateFactorial(*ptr)
fmt.Println("Factorial is: ", fact)
}
Program 4:
package main
import "fmt"
func main() {
var num = 0
fmt.Println("Num: ", num)
num++
if num == 5 {
return
}
main()
}
Program 5:
package main
import "fmt"
var num = 0
func main() {
fmt.Println("Num: ", num)
num++
if num == 5 {
return
}
main()
}
Answer Program 1:
Output:
Explanation:
The above program will generate syntax errors because we did not use curly braces with the if statement.
Answer Program 2:
Output:
Explanation:
Here, we created a recursive function calculate factorial() to calculate the factorial of a given number. Then we called recursive function from main() function and printed the result on the screen.
Answer Program 3:
Output:
Explanation:
Here, we created two functions main() and calculateFactorial(). The calculateFactorial() is used to calculate the factorial of the specified number.
In the main() function, we created variable num and an integer pointer ptr. Then we initialized the pointer ptr with the address of variable num. After that, we called the calculateFactorial() function by passing the pointer and get the result.
Answer Program 4:
Output:
Explanation:
Here, we called the main() function recursively. Every time a new num variable is created and initialized with 0. That's why the if condition will never be true. Then it will print "Num 0" infinite times.
Answer Program 5:
Output:
Explanation:
Here, we created a global variable num initialized with 0, and called the main() function recursively. Every time value of num increased by 1 and print value of the num variable. When the value num is equal to 5 then the program gets terminated.
need an explanation for this answer? contact us directly to get an explanation for this answer