March R. Smith - University of St Thomas - Minnesota QMCS 130: Today’s Class More about FunctionsMore about Functions RecursionRecursion
March R. Smith - University of St Thomas - Minnesota A Simple Function int add (int a, int b) { return (a + b); } x = add (1, 1); => x = 1 + 1;
March R. Smith - University of St Thomas - Minnesota Points about Functions “Substitutes” the parameters into the definition“Substitutes” the parameters into the definition Then we “run” the definitionThen we “run” the definition The result is substituted for the function callThe result is substituted for the function call Functions can call themsleves!Functions can call themsleves! You can use function calls as parameters:You can use function calls as parameters: –X = add(1, add(2, add(3, 4))) Which MeansWhich Means –X = add(1, add(2, 3 + 4))), or –X = add(1, ), or X =
March R. Smith - University of St Thomas - Minnesota Let’s calculate “Factorial” Definition:Definition: For X < 2, Factorial(X) = 1,For X < 2, Factorial(X) = 1, For X > 1, Factorial(X) = X * Factorial(X-1)For X > 1, Factorial(X) = X * Factorial(X-1) What is Factorial (4) ?What is Factorial (4) ? Factorial(4) =Factorial(4) = –= 4 * Factorial (3) –= 4 * 3 * Factorial(2) –= 4 * 3 * 2 * Factorial(1) –= 4 * 3 * 2 * 1
March R. Smith - University of St Thomas - Minnesota Factorial as a Function For X < 2, Factorial(X) = 1,For X < 2, Factorial(X) = 1, For X > 1, Factorial(X) = X * Factorial(X-1)For X > 1, Factorial(X) = X * Factorial(X-1) Can we write this in C?Can we write this in C? What statements do we need?What statements do we need?
March R. Smith - University of St Thomas - Minnesota Let’s try writing it out.
March R. Smith - University of St Thomas - Minnesota Fibonacci Numbers Fib(x)Fib(x) –For X < 3, Fib(X) = 1 –For X > 2, Fib(X) = Fib(X-1)+Fib(X-2) Fib(6) =Fib(6) = –= Fib(5) + Fib(4) –= (Fib(4)+Fib(3))+(Fib(3)+Fib(2)) –… etc.
March R. Smith - University of St Thomas - Minnesota Fibonacci in C … should be obvious!… should be obvious!
March R. Smith - University of St Thomas - Minnesota Creative Commons License This work is licensed under the Creative Commons Attribution-Share Alike 3.0 United States License. To view a copy of this license, visit sa/3.0/us/ or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.