Study resource

Read at your pace, then save it for later.

Unit 5: User-Defined Functions and Recursion in Programming

Section A — 1 Mark Questions

1. What is a user-defined function? [1 Mark]

Answer: A user-defined function is a block of code written by the programmer to perform a specific task, which can be called multiple times throughout the program.

2. What is the purpose of a function prototype? [1 Mark]

Answer: A function prototype declares the function's name, return type, and parameter types to the compiler before the function is actually defined or called.

3. Which keyword is used to send a value back from a function? [1 Mark]

Answer: The return keyword is used to send a value back from a function.

4. What is a recursive function? [1 Mark]

Answer: A recursive function is a function that calls itself directly or indirectly to solve a smaller instance of the same problem.

5. What happens if a base case is omitted in a recursive function? [1 Mark]

Answer: It leads to infinite recursion, eventually causing a stack overflow error.

6. What is the return type of a function that does not return any value? [1 Mark]

Answer: The void return type is used for functions that do not return any value.

7. Can a function return multiple values directly using a single return statement? [1 Mark]

Answer: No, a standard return statement can only return a single value, though multiple values can be returned indirectly using pointers, references, or composite structures like arrays.

8. What are actual arguments? [1 Mark]

Answer: Actual arguments are the values or variables passed to a function during a function call.

9. What are formal arguments? [1 Mark]

Answer: Formal arguments are the variables defined in the function header that receive the values passed during a function call.

10. Identify the category of function that takes inputs and sends back a result. [1 Mark]

Answer: Arguments with return values.

11. Which category of function neither accepts parameters nor returns a value? [1 Mark]

Answer: No arguments and no return values.

12. State the default method by which arrays are passed to functions in most high-level languages. [1 Mark]

Answer: Arrays are passed by reference (passing the base address of the array).

13. Why is the size of an array typically passed along with the array to a function? [1 Mark]

Answer: Because a function receiving an array as a pointer loses size information, so the size is needed to prevent out-of-bounds access.

14. What is a function call? [1 Mark]

Answer: A function call is an expression that invokes a function, transferring control of execution to it.

15. Give an example of a problem best solved using recursion. [1 Mark]

Answer: Calculating the factorial of a number or generating Fibonacci numbers.

16. What is the main benefit of using functions in programming? [1 Mark]

Answer: Code reusability and modularity.

17. Can a function call another function? [1 Mark]

Answer: Yes, function nesting or function chaining allows one function to call another.

18. What does a function definition contain? [1 Mark]

Answer: A function definition contains the function header and the body of executable statements.

19. State whether a recursive function requires a stopping condition. [1 Mark]

Answer: Yes, it requires a base condition to terminate the recursion.

20. What type of value is returned by a function categorized as 'no arguments but returns a value'? [1 Mark]

Answer: It returns a specific data type value (such as int, float, or char) without accepting any input parameters.

Section B — 2/3 Mark Questions

1. Differentiate between actual arguments and formal arguments. [2 Marks]

Answer: Actual arguments are the values or variables passed inside the function call in the calling function, whereas formal arguments are the variables declared in the function header to receive those values. Actual arguments can be constants, variables, or expressions, while formal arguments are always local variables.

2. Explain the category of functions with arguments but no return values with a short description. [2 Marks]

Answer: In this category, the function accepts input data from the calling function through its parameters to perform a task, but it does not send any result back. The return type of such a function is specified as void, and it completes its execution without using a return expression.

3. What is the significance of a function prototype? Give two reasons. [3 Marks]

Answer:

  • It informs the compiler about the function name, return type, and number and type of parameters before the function is called.
  • It enables type checking, allowing the compiler to flag errors if arguments passed do not match the expected types.
  • It allows functions to be defined in any order within a source file, even after they are invoked.

4. Explain how a function can return multiple values using reference or pointer parameters. [3 Marks]

Answer: Since a standard return statement can only return a single value, multiple values can be returned by passing variables by reference or using pointers. When variables are passed by reference, any modifications made to the formal parameters inside the function directly affect the actual variables in the calling function, effectively returning multiple updated values.

5. Write a short note on the base case in recursion. [2 Marks]

Answer: The base case is the terminating condition in a recursive function that stops further recursive calls. Without a base case, the function would continue calling itself indefinitely, consuming all stack memory and resulting in a runtime stack overflow error.

6. Describe what happens when an array is passed to a function. [3 Marks]

Answer: When an array is passed to a function, the base address (memory address of the first element) is passed rather than a copy of the entire array. Because of this pass-by-reference behavior, any changes made to the array elements inside the function are reflected in the original array in the calling function.

7. Explain the category of functions with no arguments and a return value. [2 Marks]

Answer: In this category, the function does not accept any parameters from the calling function. However, it performs some internal processing or input operations and returns a specific value of a defined data type back to the caller using a return statement.

8. What is a multi-function program? Give its structural advantage. [2 Marks]

Answer: A multi-function program is a program divided into several smaller, manageable user-defined functions instead of writing all code inside the main function. Its structural advantage is improved readability, easier debugging, and enhanced code reusability.

9. Compare recursion and iteration in terms of code structure and memory usage. [3 Marks]

Answer:

  • Code Structure: Iteration uses looping constructs like for or while, whereas recursion uses repeated self-function calls with a base condition.
  • Memory Usage: Iteration generally uses constant memory space, while recursion uses additional stack memory for every function call frame.
  • Readability: Recursion can make mathematical or hierarchical problems cleaner to read, while iteration is often more memory efficient.

10. Why must the size of an array be explicitly passed along with the array pointer to a function? [2 Marks]

Answer: When an array is passed to a function, it decays into a pointer to its first element, losing its total size information. Therefore, the function has no way of knowing how many elements the array contains unless the size is explicitly passed as a separate argument.

Section C — 5 Marks Questions

1. Explain the four major categories of user-defined functions based on arguments and return values with suitable descriptions for each. [5 Marks]

Answer:

Introduction

Functions are building blocks of modular programming. Based on whether they accept parameters and whether they return values, user-defined functions are broadly classified into four categories.

Categories of Functions

  • No arguments and no return values: In this type, the function neither receives any data from the calling function nor sends any value back. It simply performs a standalone task and returns control using a void return type.
  • Arguments but no return values: The function accepts input values through parameters from the caller to perform operations, but it does not return a final computed result. Any output is typically displayed inside the function itself.
  • Arguments with return values: This is a highly versatile category where the function accepts input parameters, processes them, and returns a computed result back to the calling function using a return statement.
  • No arguments but returns a value: The function does not take any input parameters from the caller, but it generates or reads a value (such as reading user input) and returns that value to the calling function.

Conclusion

Choosing the correct category depends entirely on the specific logic and data flow required between the calling environment and the sub-task.

2. Explain the concept of recursion with an example, detailing how recursive calls and base cases operate. [5 Marks]

Answer:

Introduction

Recursion is a programming technique where a function calls itself to solve a smaller sub-problem of the same type. It provides an elegant solution to problems that can be naturally broken down into repetitive similar steps.

Working Mechanism

A recursive function consists of two primary components: the base case and the recursive step.

  • Base Case: The condition under which the function stops calling itself. It prevents infinite loops and terminates the recursion.
  • Recursive Step: The part of the function where it calls itself with a modified argument, bringing it closer to the base case.

Example

Consider the calculation of factorial where factorial(n) = n × factorial(n - 1) with the base case factorial(0) = 1. When calculating factorial(3), the function calls factorial(2), which calls factorial(1), which calls factorial(0). Once the base case returns 1, the previous calls resolve sequentially: 1 × 1 = 1, then 2 × 1 = 2, and finally 3 × 2 = 6.

Conclusion

Recursion simplifies complex mathematical definitions into concise code, but proper care must be taken to ensure every recursive path eventually hits a valid base case.

3. Discuss the process of passing arrays to functions, explaining how array elements are accessed and modified within the function. [5 Marks]

Answer:

Introduction

In programming, arrays can be passed as arguments to user-defined functions to perform operations such as searching, sorting, traversing, or updating elements without duplicating large blocks of memory.

Mechanism of Passing Arrays

When an array name is passed to a function, the compiler does not copy all the elements. Instead, it passes the base address (memory address of the first element). This means the function operates directly on the original memory location.

Key Points

  • Pass by Reference: Any modification made to an array element inside the function is permanently reflected in the original array.
  • Parameter Declaration: In the function definition, the parameter is declared using empty brackets [] or as a pointer type.
  • Size Transmission: Because array decay occurs and size information is lost, the total number of elements must be passed as an additional integer argument.

Example

A function can accept an array of integers and its size to calculate the sum of all elements. By iterating through the array using a loop from index 0 to size - 1, the function accesses each element via its address offset.

Conclusion

Passing arrays by reference is efficient because it avoids memory overhead, but programmers must be cautious as unintended modifications inside the function will alter the original data.

4. Explain the complete anatomy of a multi-function program, detailing function definition, function prototypes, function calls, and return values. [5 Marks]

Answer:

Introduction: A multi-function program breaks down a large monolithic task into smaller, manageable user-defined functions, promoting modular programming, code readability, and reusability.

Key Components

  • Function Prototype: A declaration placed before usage that tells the compiler about the function name, return type, and parameter list.
  • Function Call: An expression in the main program or another function that invokes the sub-function, transferring control and passing actual arguments.
  • Function Definition: The actual body of the function containing local variable declarations and executable statements that perform the specific computation.
  • Return Statement: A mechanism to exit the function and send a computed result back to the point of call, matching the declared return type.

Execution Flow

When execution reaches a function call, control pauses in the calling function, jumps to the called function definition, executes its statements, and returns back to the caller once a return statement or the end of the function is reached.

Conclusion

Mastering multi-function program structure allows developers to write clean, organized, and easily maintainable software systems.

5. Compare recursion and iteration, and explain when to choose one over the other in software design. [5 Marks]

Answer:

Introduction

Both iteration and recursion are fundamental control mechanisms used to repeat a set of instructions. However, they approach repetitive tasks using completely different architectural paradigms.

Comparison

FeatureIterationRecursion
MechanismUses loops (for, while)Uses self-referencing function calls
TerminationLoop condition becomes falseBase case is reached
Memory UsageConstant auxiliary memoryStack memory grows with each call
SpeedGenerally faster due to no overheadSlower due to function call overhead

When to Choose

  • Use Iteration When: Memory efficiency is critical, performance is a priority, and the problem can be easily modeled using standard loops.
  • Use Recursion When: The problem naturally exhibits self-similar hierarchical structures, such as tree traversals, graph algorithms, or mathematical sequences like Fibonacci and factorial.

Conclusion

While recursion offers cleaner and more intuitive code for specific complex problems, iteration is generally preferred in production environments where system resource optimization is paramount.


xxx

Did this help you understand better?

Your feedback improves the quality of this resource for everyone.