Tutorial 12: Series 1 Excercise 2 - Recursion

extends Node2D

# Recursive function using factorial as example

const NUM: int = 8

func _ready():
 print("Using Function 1 - " + str(NUM) +
    "! Factorial is: " + str(factorial_one(NUM)))
 print("Using Function 2 - " + str(NUM) +
    "! Factorial is: " + str(factorial_two(NUM)))

# Standard function recursion
func factorial_one(n):
 if n == 0:
  return 1
 else:
  return n * factorial_one(n - 1)

# Using Ternary-if, one-liner
func factorial_two(n): return 1 if n == 0 else n * factorial_two(n - 1)

Output:

     Using Function 1 - 8! Factorial is: 40320
     Using Function 2 - 8! Factorial is: 40320

The GDScript code above shows how to use recursive function in Godot. For simplicity, we'll solve the factorial of a number. You can download the code here.

In this tutorial, it shows two factorial functions which derives the same results, the standard implementation and the other one uses ternary-if to shorten the code.

A recursive function calls itself during its execution. Thus, enabling the function to repeat itself many times.

This is the last tutorial for this basic series. In the next series, it will be all about arrays.

Related Posts:

  • Tutorial 5: Basic Functions in GDScript Part 2 GDScript for Determining an Even or Odd Number This is the second part of the function tutorial. Please study the previous tutorials before studying this one; it builds from the concepts of the past tutorials 1 to 4. The… Read More
  • Tutorial 7: Basic Match Statement in GDScript GDScript Match Statement The Godot match statement is the equivalent of switch statement in other programming languages. It's a cleaner way of handling conditional statements. If a match statement can handle my conditions… Read More
  • Tutorial 8: Basic For Loop in GDScript GDScript of Basic For Loop In this example, it shows the basic uses of a for loop statement. One is to increment and the other decrements the value of 'n'. There are other usages but for now let's tackle the common ones. … Read More
  • Tutorial 6: Basic Conditional Statements in GDScript GDScript of Basic Conditional Statements The basic GDScript conditional statements shown above is pretty much straightforward. It simply uses the if, elif and else statements. You can download the source code here. In th… Read More
  • Tutorial 9: Basic While Loop in GDScript GDScript While Loop The GDScript above shows the basic uses of while loop to increment and decrement values. In this example the decrement operator -= is introduced. You can download the source code here. In this tutoria… Read More

0 comments:

Post a Comment

© 2020 by Emman Lijesta, all rights reserved. Powered by Blogger.