Академический Документы
Профессиональный Документы
Культура Документы
OBJECTIVES
1. To construct programs modularly from small pieces called functions. 2. To create new functions. 3. To use the mechanism to pass information between functions. 4. To understand recursive functions (functions that call themselves).
THEORY Function in C
A function is a complete and independent program which is used (or invoked) by the main program or other subprograms. A subprogram receives values called arguments from a calling program, performs calculations and returns the results to the calling program.
A function may belong to any one of the following categories: 1. Functions with no arguments and no return values. 2. Functions with arguments and no return values. 3. Functions with arguments and return values.
Recursion
Recursive function is a function that calls itself. When a function calls another function and that second function calls the third function then this kind of a function is called nesting of functions. But a recursive function is the function that calls itself repeatedly
PART C : RECURSION
EXERCISE 1. From procedures of Part A, answer these question: I. What is type of square function? -integer. II. Based on the function theory above, which category is square function belong to? -Function definition. III. In your opinion, what is the advantage of return value? -It will make the calculation occur outside from main function. IV. Main function has called the square function in this program. Is it called by reference or called by value? Explain your answer. -Call by reference,because it will change the original variable value.
2. From procedures of Part B,answer these questions: I. What void function means? -Function doesnt have any return value and if in parameter,functiondoesn,t have any parameter value. II. Which category is loop function belongs to? -Function definition. III. In your opinion,why loop function did not has any parameter compared to square function? -Because loop function dont get any value from calling function in main function. 3. Observe the following partial program. Answer the questions below: long factorial(long n) { if (n == 0 || n == 1) return 1; else return n * factorial(n - 1); }
i.
ii.
State 2 differences between function declaration and function definition. FUNCTION DEFINITION Have statement written in body. Can be placed above or below main function. FUNCTION DECLARATION Dont have statement Must write above main function.
iii.
Is this function has any parameter? Explain why. -Yes, because it is use to take the value that send from calling function in main Function.
iv.
In your opinion, discuss the benefit of recursion. -Recursion function is function that can make the nested function because it call itself during its operation.
4. Define a function called calculator that calculates sum of ten numbers that have been given by the user. Write a complete program and test the result.