Subroutines are reusable blocks of code that perform specific tasks. They are fundamental building blocks for structuring and organizing programs, making them easier to understand, debug, and maintain. There are two main types of subroutines: procedures and functions.
Procedures are subroutines that perform a specific action without returning a value. They are often used to encapsulate common tasks that are performed multiple times within a program.
Example:
procedure greetUser(name)
print("Hello, " + name + "!")
end procedure
greetUser("Alice")
greetUser("Bob")
This example defines a procedure called greetUser
that takes a name as input and prints a greeting message. The procedure is called twice with different names, demonstrating its reusability.
Functions are similar to procedures, but they return a value after performing their task. They are often used to calculate results or provide data that can be used elsewhere in the program.
Example:
function sum(a, b)
return a + b
end function
result = sum(5, 3)
print(result) // Output: 8
This example defines a function called sum
that takes two numbers as input and returns their sum. The function is called with specific arguments, and its return value is stored in the result
variable, which is then printed to the console.
By understanding the concepts of procedures and functions, you can leverage the power of subroutines to create more efficient, maintainable, and robust programs.