You are on page 1of 3

Function overloading example

// Program to compute absolute value


// Works for both int and float

#include <iostream>
using namespace std;

// function with float type parameter


float absoluteValue(float number) {
if (number < 0.0)
number = -number;
return number;
}

// function with int type parameter


int absoluteValue(int number) {
if (number < 0)
number = -number;
return number;
}

int main() {
int x;
float y;
cout << "Please enter the value of x\n";
cin >> x;
cout << "Please enter the value of y\n";
cin >> y;

// call function with int type parameter


cout << "Absolute value of " <<x << " is "<<absoluteValue(x)
<< endl;

// call function with float type parameter


cout << "Absolute value of "<<y<<" is " << absoluteValue(y) <<
endl;
return 0;
}
Recursion Example

#include <iostream>
using namespace std;
int fact(int);
int main() {
int n;
cout<<"Pleade enter the value of n\n";
cin >> n;
cout << "Factorial of " << n << " is " << fact(n);
return 0;
}

int fact(int n) {
if ((n == 0) || (n == 1))
return 1;
else
return n * fact(n - 1);
}

Febonacci
#include <iostream>
using namespace std;
int fib(int x) {
if ((x == 1) || (x == 0)) {
return(x);
}
else {
return(fib(x - 1) + fib(x - 2));
}
}
int main() {
int x, i = 0;
cout << "Enter the number of terms of series : ";
cin >> x;
cout << "Fibonnaci Series : ";
while (i < x) {
cout << " " << fib(i);
i++;
}
return 0;
}

You might also like