Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Function

From Groundhog Learning

A reusable set of instructions that performs a specific task in a program.

Details

Functions allow us to write a set of statements once and reuse it at different points in a program.

For example, in a Pac-man style game, we need to prepare the game board when resetting the level.

It involves several steps:

🤖 Pseudocode

move player to start position
move ghosts to start position
restore all pellets
reset timer

This can happen in many situations:

  • The player loses a life.
  • The player chooses to restart the level.
  • The player advances to the next level.

Instead of repeating this code, we can define a function to group it under a single, recognizable name:

🤖 Pseudocode

function resetLevel
    move player to start position
    move ghosts to start position
    restore all pellets
    reset timer

Now, when we need to reset the level, we call the function and it’ll execute all the instructions inside:

🤖 Pseudocode

resetLevel

Reusing code using functions, makes programs shorter, easier to handle, and less error-prone.

Related Concepts

References