Function Overloading & Recursion

Function Overloading

Function overloading in C++ allows you to define multiple functions with the same name but with different parameter lists. This means that you can have multiple functions with the same name, as long as the parameter types or the number of parameters differ.

#include <iostream>
using namespace std;

int plusFuncInt(int x, int y) {
  return x + y;
}

double plusFuncDouble(double x, double y) {
  return x + y;
}

int main() {
  int myNum1 = plusFuncInt(10, 20);
  double myNum2 = plusFuncDouble(5.3, 4.45);
  cout << "Int: " << myNum1 << "\n";
  cout << "Double: " << myNum2;
  return 0;
}

Output:

Int: 30
Double: 9.75

Recursion

Recursion in programming is a technique where a function calls itself directly or indirectly to solve a problem. In the context of C++, recursion offers a powerful way to solve problems that can be broken down into smaller, similar subproblems.

A recursive function generally consists of two parts:

  1. Base case(s): These are the terminating conditions that define when the recursion should stop. Without proper base cases, the function may end up calling itself indefinitely, resulting in a stack overflow error.
  2. Recursive case(s): These are the cases where the function calls itself with a smaller or simpler version of the original problem.

Example:

#include <iostream>
using namespace std;

int sum(int k) {
  if (k > 0) {
    return k + sum(k - 1);
  } else {
    return 0;
  }
}

int main() {
  int result = sum(10);
  cout <<"result ="<< result;
  return 0;
}

Output:

result = 55

Comment (1)

Leave a Reply

Your email address will not be published.

Need Help?