Chapter 2
Chapter 2
• Functions enhance the readability of the code by breaking it into logical units.Each function
In summary
• functions play a crucial role in structuring programs, promoting
reusability, enhancing readability, and managing complexity.
• By encapsulating logic within functions, programmers can develop more
organized and maintainable codebases.
• Function Parameters:
• Parameters are variables declared in the function's declaration or
definition.
• They act as placeholders to receive values that are passed into the
function when it is called.
• Parameters are defined within the parentheses following the function
name.
• Function declaration with parameters
• int add(int a, int b);
Saturday, April 5, 202 7
5
Function Arguments
• Arguments are actual values or variables passed to a function when it is
called.
• These values are assigned to the function parameters during the
function call.
• Arguments are provided within the parentheses when calling a function.
• int num1 = 5;
• int num2 = 3;
• int sum = add(num1, num2); // Passing num1 and num2 as arguments to
the add function
Saturday, April 5, 202 8
5
In C++, functions are blocks of code that perform a specific task. They are essential for code organization,
modularity, and reusability.
#include <iostream>
// Function declaration to add two numbers
int add(int a, int b) //parameter
{
return a + b;
}
int main() {
int num1 = 5;
int num2 = 3;
// Function definition to Calling the add function and storing the result in sum
int sum = add(num1, num2);// num1,num2 Arguments
std::cout << "The sum of " << num1 << " and " << num2 << " is: " << sum << std::endl;
return 0;
Saturday, April 5, 202 9
5
}
Calling function by value and reference
• Passing by Value:
• When passing parameters by value, a copy of the argument's value is passed to the function.
• Any modifications made to the parameter within the function do not affect the original argument outside the function.
• Changes made to the parameter are local to the function.
• void incrementByValue(int num) {
• num += 1;
• }
• int main() {
• int number = 5;
• incrementByValue(number); // Passing 'number' by value
• // 'number' remains unchanged here
• return 0;
• }
• Recursion is a programming technique where a function calls itself to solve smaller instances of the same problem.
• It involves breaking down a problem into smaller, simpler subproblems until a base case is reached.
• #include <iostream>
• // Recursive function to calculate the factorial of a number
• int factorial(int n) {
• if (n == 0) {
• return 1; // Base case: factorial of 0 is 1
• } else {
• return n * factorial(n - 1); // Recursive call to calculate factorial
• }}
• int main() {
• int num = 5;
• int result = factorial(num);
• std::cout << "Factorial of " << num << " is: " << result << std::endl;
• return 0; }
Saturday, April 5, 202 12
5