CSEN102 Introduction to Computer Science: Lecture 7: Functions

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.


7.1 Introduction to Functions

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.

What is a Function?

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

Why Use Functions?


7.2 Defining and Calling Functions (Conceptual)

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.

Function Definition Structure (Conceptual):

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
}

Function Call (Conceptual):

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

7.3 Parameters and Arguments

Example (Conceptual):

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

7.4 Local and Global Variables

Thank you