This lecture for CSEN102: Introduction to Computer Science, given by Milad Ghantous, PhD, introduces the concept of functions in programming and their importance for structuring complex programs.
As programs grow larger and more complex, it becomes essential for programmers to structure their code in a way that is more readable, manageable, and reusable. Functions (also known as methods, subroutines, or procedures in different programming contexts) are fundamental building blocks that help achieve this modularity and organization.
A function is a self-contained block of code that performs a specific task. It can take inputs (called arguments or parameters), perform computations, and produce an output (a return value).
Before a function can be used, it must be defined. A function definition specifies the function's name, its parameters, and the code it executes. After definition, the function can be called (executed) from other parts of the program.
return_type function_name(parameter1_type parameter1, parameter2_type parameter2, ...) {
// Body of the function
// Code to perform the task
return value; // Optional: returns a value of return_type
}
return_type: The data type of the value that the function will return. If the function does not return any value, a `void` return type is used (in languages like C++).function_name: A unique identifier for the function.parameters: Variables that receive values passed to the function when it is called. These are optional.function body: The set of statements that define what the function does.return statement: Used to send a value back to the caller and terminate the function.To use a function, you call it by its name, providing the necessary arguments (actual values for the parameters).
// Example of calling a function that returns a value
result = function_name(argument1, argument2);
// Example of calling a function that does not return a value
function_name(argument1, argument2);
// Function Definition
int add(int a, int b) { // 'a' and 'b' are parameters
return a + b;
}
// Function Call
int sum = add(5, 3); // 5 and 3 are arguments
Thank you