CSC 245 Recursion Lab
A lab assignment on recursion principles and algorithm design.
Lucy Gray
Contributor
4.2
47
about 1 month ago
Preview (2 of 4)
Sign in to access the full document!
CSC 245 Recursion Lab
For each of the following, write recursive functions to complete the stated tasks. Test your functions by
letting your main function call the recursive function and report the results.
1. Given an array of n integer values, compute the sum of the values.
Answer:
/***
* Q1
*
* @param n
* @return
*/
public static int sum(int n) {
if (n == 0) {
return 0;
} else
return (n + sum(n - 1));
}
2. Output the following patterns:
a.
**********
********** (an nxm rectangle)
**********
**********
Answer:
/***
* 2. a function
*
* @param n
* @param m
* @return
*/
public static String rectangle(int n, int m) {
if (n == 0) {
return " ";
}
for (int i = 0; i < m; i++) {
System.out.print("*");
}
System.out.println();
return rectangle(n - 1, m);
For each of the following, write recursive functions to complete the stated tasks. Test your functions by
letting your main function call the recursive function and report the results.
1. Given an array of n integer values, compute the sum of the values.
Answer:
/***
* Q1
*
* @param n
* @return
*/
public static int sum(int n) {
if (n == 0) {
return 0;
} else
return (n + sum(n - 1));
}
2. Output the following patterns:
a.
**********
********** (an nxm rectangle)
**********
**********
Answer:
/***
* 2. a function
*
* @param n
* @param m
* @return
*/
public static String rectangle(int n, int m) {
if (n == 0) {
return " ";
}
for (int i = 0; i < m; i++) {
System.out.print("*");
}
System.out.println();
return rectangle(n - 1, m);
Preview Mode
Sign in to access the full document!
100%
Study Now!
XY-Copilot AI
Unlimited Access
Secure Payment
Instant Access
24/7 Support
Document Chat
Document Details
University
University of Notre Dame
Subject
Information Technology