COMP1000 Week 6
- Introduction to Functions:
- Functions are named blocks of code designed to perform specific tasks.
- The execution of code jumps to the function when it's called and returns upon completion.
- How Functions Work:
- When a function is called, the program control shifts to the function's code block.
- After the function completes its task, control returns to the line immediately following the function call.
- Structure of a Function:
- Functions typically consist of three main parts:
- Return Type
- Function Name
- Parameters
- Return Type:
- Specifies the type of value the function will return after execution.
- Can be
void if the function does not return any value. - If a data type is specified (e.g.,
int, float, string), a return statement is required.
- Function Name:
- A user-defined name for the function, similar to variable names.
- Used to call or invoke the function in the code.
- Parameters:
- Values passed into the function, specified within parentheses.
- The number and type of parameters must match the function definition when the function is called.
- Parameters are optional; a function may have no parameters.
- Writing a Function:
- Example: A function that prints "hello".
- Return type:
void (since it only prints and doesn't return a value). - Name:
sayHello. - No parameters.
- Body:
println("hello").
- Function Definition vs. Function Call:
- Definition: The actual code of the function, defining what it does.
- Call: Invoking the function by its name to execute its code.
- Passing Values to Functions:
- Values are passed as parameters in the function call.
- These values are used within the function to perform operations.
- Returning Values from Functions:
- If a function has a return type (not
void), it must return a value of that type. - The
return statement specifies the value to be returned.
- Example: Function to Add Two Numbers:
- Takes two numbers as parameters.
- Adds the numbers together.
- Returns the sum.
- Code:
int addNumbers(int a, int b) {int sum = a + b;return sum;}
- Importance of Return Type:
- The data type of the returned variable must match the return type specified in the function declaration.
- Variable Scope:
- Variables declared inside a function are local to that function.
- They cannot be accessed outside the function unless returned.
- Advantages of Using Functions:
- Modularity: Breaks down code into manageable, reusable blocks.
- Code Reusability: Allows the same code to be used multiple times.
- Readability: Makes code easier to understand and maintain.