Chapter Four
Chapter Overview
Title: Fundamentals of Programming
Author: Abey B. (MSc)
Institution: American College of Technology (ACT)
Date: December 15, 2024
Modular Programming
Definition:
Process of subdividing a computer program into separate sub-programs.
Breaks down the design of a program into individual modules.
Modular programming in C++ is done through functions.
Functions
What is a Function?
A block of code that performs a specific task.
Runs only when called.
Each function has a unique name and execution branch.
Takes inputs, processes them, and produces output.
Purpose of Functions:
Combine commonly performed tasks into reusable code blocks.
Example:
int sum(int a, int b) { return a + b; }
Invocation of Functions
Functions can be called from any part of the program.
Arguments: Passed values must match parameter types in function definition.
Benefits of Using Functions
Reduces Code Redundancy:
Avoids rewriting the same code.
Modularity:
Simplifies code management by dividing it into functions.
Function Declaration and Definition
Declaration:
Informs the compiler about the function name, return type, and parameters.
Definition:
Comprises the function header (name, return type, parameters) and function body (code that executes).
Calling a Function:
Syntax:
function_name();
Types of Functions in C++
Built-in Functions:
Predefined functions in libraries, e.g.,
sqrt(),strcat().
User-Defined Functions:
Created by users; definitions made within the program.
Variable Scope
Definition: Scope defines accessibility of variables.
Types:
Local Variables:
Declared within a function; visible only in that function.
Global Variables:
Declared outside any function; accessible from any part of the program.
Scope Resolution Operator
Usage: Accesses a global variable that has the same name as a local variable.
Syntax:
::variable_name.
Function Overloading
Definition: Feature of allowing multiple functions with the same name but different parameters.
Conditions for Overloading:
Different parameter types.
Different number of parameters.
Different sequence of parameters.
Ambiguity in Function Overloading
Occurs when the compiler cannot resolve which overloaded function to call.
Examples of ambiguity include type conversion issues and default arguments.
Recursion
Definition: A function that calls itself.
Process: Executes instructions and calls itself with smaller inputs until a base condition is met.
Types:
Direct Recursion: The function directly calls itself.
Indirect Recursion: The function calls itself through another function.
Example of Recursion
Factorial Calculation: Illustrative program to compute factorial using recursion.
Conclusion
Understanding functions and recursive programming is vital for effective software development and problem solving in programming.