KembaraXtra-Computer Science - Functions
1. What are Functions?
Definition: A function is a reusable block of code that performs a specific task.
Purpose:
- Avoid code duplication.
- Promote code reusability.
- Improve code organization and readability.
Terminology: Functions may also be called subroutines, procedures, or methods (slight differences in meaning may exist depending on the language).
DRY Principle: Functions adhere to the "Don't Repeat Yourself" (DRY) principle by reducing duplicative code.
Encapsulation: Functions encapsulate internal details, providing an interface (inputs and outputs) for usage. Users don't need to know the inner workings.
2. Defining Functions
Definition: Creating a function and specifying its behavior.
Elements of a Function Definition:
- Name: A unique identifier for the function.
- Parameters (Inputs): Values passed to the function when it is called.
- Body: The code block containing the instructions the function executes.
- Return Value (Output): The value the function sends back to the caller (optional).
Example (C):
double areaOfCircle(double radius) {
double area = 3.14 * radius * radius;
return area;
}
double: Return type (floating-point number).
areaOfCircle: Function name.
double radius: Input parameter (radius of the circle).
{ ... }: Function body.
return area: Returns the calculated area.
Example (Python):
def area_of_circle(radius):
area = 3.14 * radius * radius
return area
def: Keyword to define a function.
- Type declarations are not required in Python.
3. Calling Functions
Definition: Executing a defined function.
Process:
- The calling code invokes the function.
- Parameters are passed (if any).
- Control is transferred to the function.
- The function executes its code.
- The function returns control (and a return value, if any) to the caller.
Example (C):
double area1 = areaOfCircle(2.0);
double area2 = areaOfCircle(38.6);
Example (Python):
area1 = area_of_circle(2.0)
area2 = area_of_circle(38.6)
The returned value can be stored in a variable or ignored (though ignoring the return value might not be useful, depending on the function).
4. Using Libraries
Definition: Leveraging pre-written functions provided by programming languages or third-party developers.
Standard Library: A set of functions included with a programming language.
Examples: Printing to the console, file operations, text processing.
C and Python both have standard libraries. Python's is known to be extensive.
Additional Libraries: Libraries created by developers and shared for others to use.
Package Managers: Tools for managing and distributing libraries (packages).
- Python: pip (widely used).
- C: Multiple package managers exist, but none are universally adopted.