c++ func 2
c++ func 2
Recursivity
In many programming languages including C++, it is possible to call a function from a same
function. This function is known as recursive function and this programming technique is
known as recursion.
In recursion, a function calls itself but you shouldn't assume these two functions are same
function. They are different functions although they have same name.
Local variables: Local variables are variables defined inside a function and has scope
only inside that function. In recursion, a function call itself but these two functions are
different functions (You can imagine these functions are function1 and function 2. The
local variables inside function1 and function2 are also different and can only be accessed
within that function.Consider this example to find factorial of a number using recursion
shown below.
For example, in order to obtain the factorial of a number (n!) the mathematical formula would
be: n! = n * (n-1) * (n-2) * (n-3) ... * 1
More concretely, 5! (factorial of 5) would be: 5! = 5 * 4 * 3 * 2 * 1 = 120
And a recursive function to calculate this in C++ as shown below :
// factorial calculator
#include <iostream>
using namespace std;
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
else
return 1;}
int main ()
{ long number = 9;
cout << number << "! = " << factorial (number)<<endl;
system(“pause”);
return 0;
}
1
Eng:Alhadi
FACULTY OF ELECTONICS TECHNOLOGY
#include <iostream>
#include <stdlib.h>
system("PAUSE");
return 0;
2
Eng:Alhadi
FACULTY OF ELECTONICS TECHNOLOGY
In C++ programming, two functions can have same identifier(name) if either number of
arguments or type of arguments passed to functions are different. These types of functions
having similar name are called overloaded functions.
type of argument or numbers of argument passed). Two functions shown below are not
overloaded functions because they only have same number of arguments and arguments in both
functions are of type int.
/* Both functions has same number of argument and same type of argument*/
/* Hence, functions mentioned below are not overloaded functions. */
/* Compiler shows error in this case. */
#include <iostream>
#include <stdlib.h>
#include<conio.h>
using namespace std;
int main(void)
{
print(5);
print(500.689);
print("Hello libya");
getch();
return 0;
}
4
Eng:Alhadi
FACULTY OF ELECTONICS TECHNOLOGY
#include <iostream>
using namespace std;
void test(int);
void test(float);
void test(int, float);
int main() {
int a = 5;
float b = 5.5;
test(a); //call function test with int argument
test(b); //call function test with float argument
test(a, b); //call function test with int and float argument
system("pause");
return 0;
}
#include <iostream>
using namespace std;
5
Eng:Alhadi
FACULTY OF ELECTONICS TECHNOLOGY
6
Eng:Alhadi