Functions Lectr01
Functions Lectr01
• Example
cout << sqrt( 900.0 );
• Calls the sqrt (square root) function. The preceding statement would print 30
• The sqrt function takes an argument of type double and returns a result of type
double, as do all functions in the math library
Functions
• Function arguments can be
– Constants
sqrt( 4 );
– Variables
sqrt( x );
– Expressions
sqrt( sqrt( x ) ) ;
sqrt( 3 - 6x );
Recursion Function
• A function that calls itself is known as a recursive function
• Technique is known as recursion
• Provides a way to break complicated problems down into simple
problems which are easier to solve
• Recursion is the process of defining a problem (or the solution to a
problem) in terms of (a simpler version of) itself
• Example: Factorial
n! = n * ( n – 1 ) * ( n – 2 ) * … * 1
• Recursive relationship ( n! = n * ( n – 1 )! )
5! = 5 * 4!
4! = 4 * 3!…
return f( 2 ) + f( 1 )
return f( 1 ) + f( 0 ) return 1
return 1 return 0
Recursion vs. Iteration
• Repetition
• Iteration: explicit loop
• Recursion: repeated function calls
• Termination
• Iteration: loop condition fails
• Recursion: base case recognized
• Both can have infinite loops
• Balance between performance (iteration) and good software
engineering (recursion)
Recursion: Advantage vs Disadvantage
• Recursion makes program elegant
• However, if performance is vital, use loops instead as recursion is
usually much slower.
Functions with Empty Parameter Lists