This lecture for CSEN102: Introduction to Computer Science, given by Milad Ghantous, PhD, introduces the concept of functions in programming, their purpose, and how to define and use them.
A function (also known as a subroutine, procedure, or method in different programming contexts) is a block of organized, reusable code that is used to perform a single, related action. Functions provide a way to break down complex problems into smaller, manageable sub-problems, making programs easier to design, write, debug, and maintain.
Every function typically has a definition and can be called (executed) from other parts of the program.
This involves specifying the function's name, its parameters (inputs), and the block of code it executes. The syntax for defining functions varies by programming language.
return_type function_name(parameter1_type parameter1, parameter2_type parameter2, ...) {
// Body of the function
// Instructions to be executed when the function is called
return value; // Optional: returns a value to the caller
}
To execute the code within a function, you "call" or "invoke" it by its name, followed by parentheses containing any necessary arguments (actual values passed to the parameters).
// Assuming a function defined like: int add(int a, int b) { return a + b; }
int result = add(5, 3); // Calling the 'add' function with arguments 5 and 3
// 'result' will now hold the value 8
// Function definition with parameters 'num1' and 'num2'
void greet(string name) {
cout << "Hello, " << name << "!" << endl;
}
// Function call with argument "Alice"
greet("Alice"); // "Alice" is the argument passed to the 'name' parameter
Functions can optionally return a value to the part of the code that called them. The `return` statement is used to send a value back. If a function doesn't return a value, its return type is often specified as `void` (in languages like C++ or Java).
int multiply(int x, int y) {
int product = x * y;
return product; // Returns the calculated product
}
int myProduct = multiply(4, 5); // myProduct will be 20