0% found this document useful (0 votes)
23 views

Function Overloading Example

The document contains code examples demonstrating function overloading, recursion, and the Fibonacci sequence. The function overloading example defines two absoluteValue functions, one that takes an integer and one that takes a float, to calculate the absolute value. The recursion example defines a fact function that recursively calculates factorials. The Fibonacci example defines a fib function that recursively calculates Fibonacci numbers and prints the first x numbers of the sequence.

Uploaded by

ezedin ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Function Overloading Example

The document contains code examples demonstrating function overloading, recursion, and the Fibonacci sequence. The function overloading example defines two absoluteValue functions, one that takes an integer and one that takes a float, to calculate the absolute value. The recursion example defines a fact function that recursively calculates factorials. The Fibonacci example defines a fib function that recursively calculates Fibonacci numbers and prints the first x numbers of the sequence.

Uploaded by

ezedin ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 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