Introduction to Functions
•Functions are reusable blocks of code that
perform a specific task.
• They help in code modularity and organization.
• Example:
• int add(int a, int b) {
• return a + b;
• }
2.
Why Use Functionsin C++?
• • Avoids code repetition
• • Improves readability and maintainability
• • Enhances debugging and testing
• • Encourages modular programming
• Example:
• Instead of writing the same logic multiple times, use a function:
• void greet() {
• cout << "Hello, World!";
• }
3.
Types of Functions
•• Built-in Functions (e.g., sqrt(), pow())
• • User-defined Functions
• • Recursive Functions
• Example of built-in function:
• double result = sqrt(25); // result = 5
4.
Function Declaration, Definition,
andCalling
• • Declaration: Specifies the function prototype
• • Definition: Contains the function body
• • Calling: Executes the function
• Example:
• // Declaration
• int multiply(int, int);
• // Definition
• int multiply(int x, int y) {
• return x * y;
• }
• // Calling
• int result = multiply(4, 5); // result = 20
5.
Function Parameters andReturn
Values
• • Functions can take parameters and return
values.
• • If no return value is needed, use 'void'.
• Example:
• int square(int num) {
• return num * num;
• }
• int result = square(6); // result = 36
6.
Pass by Valuevs. Pass by Reference
• • Pass by Value: Function gets a copy of the argument.
• • Pass by Reference: Function gets a reference to the actual argument.
• Example:
• void modify(int &x) {
• x += 10;
• }
• int num = 5;
• modify(num);
• // num is now 15
7.
Function Overloading
• •Multiple functions with the same name but different
parameters.
• Example:
• int add(int a, int b) {
• return a + b;
• }
• double add(double a, double b) {
• return a + b;
• }
8.
Inline Functions
• •Used for small functions to reduce function
call overhead.
• • Defined using the 'inline' keyword.
• Example:
• inline int cube(int x) {
• return x * x * x;
• }
9.
Recursive Functions inDepth
• • A function that calls itself.
• • Used for problems like factorial calculation,
Fibonacci series, etc.
• Example:
• int factorial(int n) {
• if (n == 0) return 1;
• return n * factorial(n - 1);
• }
10.
Best Practices inUsing Functions
• • Keep functions short and focused.
• • Use meaningful names.
• • Avoid global variables.
• • Document functions properly.
• Example:
• // Bad function naming
• void f() {...}
• // Good function naming
• void calculateArea() {...}
11.
Conclusion & Q&A
•Functions improve code reusability,
readability, and maintainability.
• Use functions wisely to write efficient C++
programs.
• Any Questions?