Laboratory 2:
FUNCTIONS AND RECURSION
OBJECTIVES
Understand the concepts of functions in C, including declaration, definition, and
function calls.
Learn how to use function prototypes and return values correctly.
Distinguish between pass-by-value and pass-by-reference using pointers.
Understand the principles of recursion and identify the base case.
Compare iterative and recursive approaches to problem solving.
Develop modular programming skills by decomposing problems into smaller
functions.
Apply functions and recursion to solve practical computational and data-
processing problems.
PREPARATION FOR LAB 2
Finish Lab 0 at home.
REFERENCE
Department of Electronics Page | 1
Computer System and Programming Laboratory (Advanced Program)
Laboratory 2:
FUNCTIONS AND RECURSION
EXPERIMENT 1
Objective: Become familiar with the basic concept of functions, including how to declare,
define, and call a simple function with no parameters and no return value (void).
Requirements:
- Write a C program that defines a function: void printLab2(int n)
- When called, this function prints the line: "Computer Systems and Programming
Languages – Lab 2" along with the student’s name to the screen n times.
- In the main() function below, input the value of n and call the function printLab2.
Check:
1. Compile and run the program. Record how many lines of the message are printed.
2. Move the entire function definition void printLab2 (int n) { ... } to a position
immediately below the main() function. Compile the program again. Does the
compiler produce any errors or warnings?
Department of Electronics Page | 2
Computer System and Programming Laboratory (Advanced Program)
Laboratory 2:
FUNCTIONS AND RECURSION
EXPERIMENT 2
Objective: Develop a deep understanding of the default pass-by-value mechanism in C
with loops. Explore the difference in value accumulation when modifying the original
variable using the pass-by-reference using pointers.
Requirements:
Create a new C file, copy the following source code, then compile and run the program:
#include <stdio.h>
void addTen(int x) {
x = x + 10;
}
int main() {
int a = 5;
printf("Before the loop, a = %d\n\n", a);
for (int i = 1; i <= 3; i++) {
printf("--- Iteration %d ---\n", i);
addTen(a);
printf(" >> a = %d \n \n", a);
}
return 0;
}
Check:
1. Run the program and observe the output. Does the value of a in main() change?
2. Modify the function declaration to void addTen(int *x). Inside the function, increase the
value using the statement *x = *x + 10;. In main(), change the call from addTen(a); to
addTen(&a);. Run the program again. How does the value of a in main() change over
the three iterations (does it accumulate)?
Department of Electronics Page | 3
Computer System and Programming Laboratory (Advanced Program)
Laboratory 2:
FUNCTIONS AND RECURSION
EXPERIMENT 3
Objective: Understand how to declare a function prototype and obtain the return value
of a function using the return statement.
Requirements:
1. Write a program that asks the user to input two integers and finds the larger number
using a user-defined function.
2. At the beginning of the program (immediately below the #include directives and
before main(), declare the function prototype: int findMax(int a, int b);
3. Define the function findMax below the main() function. This function compares a and
b, then uses the return statement to return the larger value. In the main() function,
input two integers a and b from the keyboard. Call the function findMax, store the
returned result in a variable, and print the result to the screen.
Example:
Input:
a = 15, b = 20
Output:
>> The largest number is: 20
Check:
1. Remove the prototype declaration int findMax(int a, int b); at the beginning of the
program and compile again. Does the compiler produce any warnings or errors? What
is the output displayed on the screen?
Department of Electronics Page | 4
Computer System and Programming Laboratory (Advanced Program)
Laboratory 2:
FUNCTIONS AND RECURSION
2. Remove the return ...; statement inside the function findMax() and run the program
again. What warning does the C compiler produce? When executed, what value is
printed as the largest number?
Department of Electronics Page | 5
Computer System and Programming Laboratory (Advanced Program)
Laboratory 2:
FUNCTIONS AND RECURSION
EXPERIMENT 4
Objective: Introduce and become familiar with recursive functions.
Requirements:
Write a program that computes the factorial of a positive integer ( !) using a recursive
function, with the following prototype: long factorial(int n); and display the result on the
screen
Example:
Input:
n=5
Output:
5! = 120
Check:
1. Draw the algorithm flowchart and write the program to solve the problem above.
What is the base case (stopping condition) of the recursive function?
2. Disable the code segment containing the base case and run the program again.
Observe what happens in the terminal. Provide your comments.
3. Run the program and input = 20. Is the printed result correct? Explain the reason
Department of Electronics Page | 6
Computer System and Programming Laboratory (Advanced Program)
Laboratory 2:
FUNCTIONS AND RECURSION
EXPERIMENT 5
Objective: Convert a problem from an iterative approach to a recursive approach.
Requirements:
Solve the problem of computing using two methods: Using a for loop and using a
recursive function.
Check:
1. Draw the algorithm flowcharts for both methods.
2. What result is printed when = 3 and = 4? What is the base case (stopping
condition) of the recursive algorithm, and how many times does the function call itself
before reaching this condition?
3. Try entering a negative exponent (e.g., = −2). What outputs are produced by the
two methods? Add appropriate conditional statements to support negative exponents
in both approaches.
Department of Electronics Page | 7
Computer System and Programming Laboratory (Advanced Program)
Laboratory 2:
FUNCTIONS AND RECURSION
EXPERIMENT 6
Objective: Decompose a complex algorithm into multiple smaller functions to process
digit data and perform operations on individual digits.
Requirements:
Starting from any four-digit integer (with the condition that not all four digits are
identical, e.g., 1111), repeatedly perform the following operation:
- From the largest number by arranging the digits in descending order.
- From the smallest number by arranging the digits in ascending order.
- Subtract the smaller number from the larger number.
- Repeat the process until the result converges to 6174.
Write a C program that verifies this rule. The program should prompt the user to enter a
four-digit number and display the entire sequence of steps until the number converges
to the Kaprekar constant.
Example:
Input:
Enter a four-digit number: 3524
Output:
5432 - 2345 = 3087
8730 - 0378 = 8352
8532 - 2358 = 6174
Kaprekar constant reached after 3 steps!
Department of Electronics Page | 8
Computer System and Programming Laboratory (Advanced Program)
Laboratory 2:
FUNCTIONS AND RECURSION
Check:
1. Draw the algorithm flowchart for the problem and write a program to solve it.
2. If all the logic currently implemented in the helper functions were merged directly
into the loop inside main(), what would the source code look like? Discuss how this
change would affect code readability and maintainability.
Department of Electronics Page | 9
Computer System and Programming Laboratory (Advanced Program)
Laboratory 2:
FUNCTIONS AND RECURSION
EXPERIMENT 7
Objective: Apply recursion combined with nested loops to handle complex output
formatting.
Requirements:
In mathematics, Pascal’s Triangle is a triangular array of binomial coefficients. The value
of an element at row n and column (denoted as ( , ), the combination of choose )
is equal to the sum of the two elements directly above it.
The recursive formula is:
( , ) = ( − 1, − 1) + ( − 1, )
Write a C program to print the first N rows of Pascal’s Triangle.
Example:
Input:
Enter the height of Pascal's Triangle: 5
Output:
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Department of Electronics Page | 10
Computer System and Programming Laboratory (Advanced Program)
Laboratory 2:
FUNCTIONS AND RECURSION
Check:
1. Draw the algorithm flowchart. What is the base case (stopping condition) of the
recursive algorithm? For the input value 5, count how many times the base case is
reached during the computation.
2. Run the program with input 35. How is the execution speed? Based on this
observation, investigate the concept of overlapping subproblems and identify
situations in which recursion should not be used.
Department of Electronics Page | 11
Computer System and Programming Laboratory (Advanced Program)
Laboratory 2:
FUNCTIONS AND RECURSION
EXPERIMENT 8
Objective: Construct auxiliary recursive functions (helper functions) and integrate them
into a branching recursive function.
Requirements:
Given a positive integer ( > 1) and a real number x, write a C program to compute
the value of the following nested expression ( , ). The program must use: one recursive
function to evaluate the expression, one function to compute powers, and one function
to compute factorials:
( , ) = 1! +
2! −
3! + 4!−. . .
where the final term is: ( )!
Check:
1. Enter input values and display the computed result.
2. Repeatedly calling the factorial and power functions at each step is computationally
expensive. In your opinion, if additional accumulated values are passed as parameters
to the recursive function, for example:
double calculateS(double x, int i, int n,
double current_fact,
double current_pow);
Is it possible to eliminate the two auxiliary recursive functions? Present the logical idea
behind this approach.
Department of Electronics Page | 12
Computer System and Programming Laboratory (Advanced Program)
Laboratory 2:
FUNCTIONS AND RECURSION
EXPERIMENT 9
Objective: Use functions with parameters and a void function (no return value) to
perform basic data analysis. Separate computation logic from output logic.
Requirements:
Write a program to calculate a person’s Body Mass Index (BMI). The program must be
designed using two independent functions:
- A function to compute BMI, which takes weight (kg) and height (m) as inputs and
returns the BMI value using the formula:
ℎ
=
ℎ ℎ
- A function that receives the computed BMI value and prints the corresponding
classification:
BMI < 18.5: "Underweight";
18.5 <= BMI < 24.9: "Normal";
BMI >= 25.0: "Overweight".
Check:
1. Draw the algorithm flowchart, write the program and explain the obtained result.
2. In the function calculateBMI, if the user accidentally enters a height value of 0, what
error will occur (division by zero)? How can you handle this error using a return
statement before the division takes place?
Department of Electronics Page | 13
Computer System and Programming Laboratory (Advanced Program)
Laboratory 2:
FUNCTIONS AND RECURSION
EXPERIMENT 10
Objective: Apply programming techniques to solve an optimization problem using a
greedy strategy.
Requirements:
- The ATM contains banknotes of the following denominations: 500k, 200k, 100k, and
50k (thousand VND), with a limited number of notes available for each denomination.
When a user withdraws an amount , the system must prioritize dispensing the
largest denominations first so that the total number of banknotes is minimized, while
also not exceeding the available quantity of each denomination.
- Write a program to simulate an ATM cash dispensing system. The program should
prompt the user to enter the withdrawal amount and display the banknotes
dispensed.
Example:
Input:
Enter the amount to withdraw (in thousand VND): 850
Output:
Dispense 1 note of 500k
Dispense 1 note of 200k
Dispense 1 note of 100k
Dispense 1 note of 50k
Transaction completed!
Check:
1. Draw the algorithm flowchart, write the program solving the problem above.
Department of Electronics Page | 14
Computer System and Programming Laboratory (Advanced Program)