CSC 245 Recursion Lab

A lab assignment on recursion principles and algorithm design.

Lucy Gray
Contributor
4.0
43
5 months ago
Preview (2 of 4 Pages)
100%
Purchase to unlock

Loading document content...

Preview Mode

Sign in to access the full document!

CSC 245 Recursion Lab

Page 1

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 n x m 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);

Page 2

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 n x m 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);

Study Now!

XY-Copilot AI
Unlimited Access
Secure Payment
Instant Access
24/7 Support
Document Chat

Document Details

Related Documents

View all