C++ Program Demonstrating Functions, Overloading, and Recursion

Implement Functions in C++, Including Function Overloading and Recursion

In C++, functions play a vital role in structuring code into reusable blocks. They make programs modular, readable, and maintainable. Two powerful concepts related to functions in C++ are **function overloading** and **recursion**. In this blog post, we will understand both concepts and see them in action through a C++ program.

🔹 What is a Function in C++?
A function is a block of code that performs a specific task. It can be:
  • Built-in (like `main()`, `cout()`, etc.)
  • User-defined (created by the programmer)
🔹 Function Overloading
Function overloading means defining multiple functions with the same name but different parameter types or numbers. The compiler automatically determines which function to invoke based on the argument list.
Example:
int add(int a, int b);
float add(float a, float b);

🔹 Recursion
Recursion is a process in which a function calls itself directly or indirectly. It is often used to solve problems that can be broken down into smaller, repetitive tasks (e.g., factorial, Fibonacci, etc.).

✅ C++ Program Demonstrating Functions, Overloading, and Recursion
#include <iostream>
using namespace std;
// Function Overloading
int multiply(int a, int b) {
    return a * b;
}
float multiply(float a, float b) {
    return a * b;
}
// Recursive function to calculate factorial
int factorial(int n) {
    if (n == 0 || n == 1)
        return 1;
    else
        return n * factorial(n - 1);
}
// Main function
int main() {
    int int1 = 4, int2 = 5;
    float float1 = 2.5f, float2 = 4.0f;
    // Function overloading demonstration
    cout << "Multiplication of integers: " << multiply(int1, int2) << endl;
    cout << "Multiplication of floats: " << multiply(float1, float2) << endl;
    // Recursion demonstration
    int number;
    cout << "\nEnter a number to calculate factorial: ";
    cin >> number;
    if (number < 0)
        cout << "Factorial is not defined for negative numbers.";
    else
        cout << "Factorial of " << number << " is " << factorial(number) << endl;
    return 0;
}

🔍 Output Example
If the user inputs `5`, the output will be:
  • Multiplication of integers: 20
  • Multiplication of floats: 10
  • Enter a number to calculate factorial: 5
  • Factorial of 5 is 120
📝 Explanation
1. Function Overloading:
  • Two `multiply()` functions are defined: one for `int`, one for `float`.
  • The compiler selects the correct one based on the data type.
2. Recursive Function:
  • `factorial()` calls itself with `n - 1` until it reaches 1 or 0.
  • Base case: if `n == 0 || n == 1`, return 1.
  • Recursive case: `n * factorial(n - 1)`

Comments