CSEN102 Introduction to Computer Science: Lecture 9: Functions

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.


9.1 What are Functions?

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.

Why Use Functions?


9.2 Defining and Calling Functions

Every function typically has a definition and can be called (executed) from other parts of the program.

Function Definition:

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.

Conceptual Structure:

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
}

Function Call:

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).

Conceptual Example:

// 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

9.3 Function Parameters and Arguments

Example:

// 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

9.4 Return Values

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).

Example:

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