Programming Practice Course
Week 4: Functions and Modular
Programming
Presented by: Isaac Muckson Sesay
Week Objectives
• - Understand the concept of functions and
their importance.
• - Learn how to define and call functions.
• - Explore the benefits of modular
programming.
• - Implement programs using reusable
functions.
What is a Function?
• - A function is a reusable block of code designed to
perform a specific task.
• - Helps in breaking down complex problems into
smaller, manageable parts.
• - Example:
• ```c
• int add(int a, int b) {
• return a + b;
• }
• ```
Benefits of Using Functions
• - Code reusability: Write once, use multiple
times.
• - Improved readability and maintenance.
• - Easier testing and debugging.
• - Facilitates modular programming.
Function Definition
• - A function is defined with the following syntax:
• ```c
• return_type function_name(parameters) {
• // Function body
• }
• ```
• - Example:
• ```c
• int square(int num) {
• return num * num;
• }
• ```
Function Call
• - A function is executed by calling it.
• - Syntax:
• ```c
• function_name(arguments);
• ```
• - Example:
• ```c
• int result = square(5);
• printf("Result: %d", result);
• ```
Function Parameters
• - Parameters are inputs passed to a function.
• - Can be of any data type.
• - Example:
• ```c
• int add(int a, int b) {
• return a + b;
• }
• ```
Return Values
• - Functions can return values to the caller.
• - Use the `return` keyword to specify the value to
return.
• - Example:
• ```c
• int multiply(int a, int b) {
• return a * b;
• }
• ```
Modular Programming
• - Divides a program into separate,
independent modules.
• - Each module performs a specific function.
• - Promotes reusability and collaboration.
• - Example: Using multiple functions for
different tasks.
Practice Exercise 1
• - Problem: Write a function to calculate the
area of a circle.
• - Steps:
• 1. Define a function `float area(float radius)`.
• 2. Use the formula `area = pi * radius *
radius`.
• 3. Call the function and display the result.
Practice Exercise 2
• - Problem: Create a program with the
following functions:
• 1. `int add(int a, int b)`
• 2. `int subtract(int a, int b)`
• 3. `int multiply(int a, int b)`
• 4. `float divide(int a, int b)`
• - Test these functions with user inputs.
Wrap-Up and Q&A
• - Summary of functions and modular
programming.
• - Questions or challenges faced?
• - Prepare for Week 5: Arrays and Strings.