recursion.java - http://people.cs.pitt.edu/~ramirez/cs401/handouts/recursion.jav
ID: 3571733 • Letter: R
Question
recursion.java - http://people.cs.pitt.edu/~ramirez/cs401/handouts/recursion.javaLab 6 to refer to:
CS401 Lab 12: Recursion Note: Since this is the last lab meeting, you must demonstrate this lab during your lab session this week. Irecommend that you look it over in advance so you will be ready to complete it during your lab meeting. Introduction and Background Recursion is a very valuable programming tool, and most modern programming languages allow it. You will see and implement several interesting recursive algorithms in future courses, but for now we will focus on just the basic ideas involved in recursion. For a detailed introduction to recursion, see the recursion course notes and Chapter 16 of the text. Read over the slides carefully before continuing with this lab, and also look through the text chapter. There are three requirements of recursive algorithms: There must be some recursive case, in which the algorithm "calls itself" There must be some base case. in which no recursive call is made The recursive calls must lead eventually to the base case For example, note the recursive code for the factorial problem (with emor case removed): public static int fact (int N) if (N
Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
public class Lab12 {
public static double max(double[] data){
return max_rec(data, 0);
}
public static double max_rec(double[] data , int loc){
if (loc < data.length) {
return Math.max(data[loc], max_rec(data, loc+1));
} else {
return data[0];
}
}
public static double min(double[] data){
return min_rec(data, 0);
}
public static double min_rec(double[] data , int loc){
if (loc < data.length) {
return Math.min(data[loc], min_rec(data, loc+1));
} else {
return data[0];
}
}
public static double sum(double[] data){
return sum_rec(data, 0);
}
public static double sum_rec(double[] data , int loc){
if(loc == data.length-1)
return data[loc];
return data[loc] + sum_rec(data, loc+1);
}
public static double avg(double[] data){
return avg_rec(data, data.length-1);
}
public static double avg_rec(double[] data , int loc){
double result;
result = (double)data[loc] / (double)data.length;
if (loc == 0)
return result;
else
return result + avg_rec(data, loc-1);
}
public static void main(String[] args) {
double a[] = {1,2,3,4,5};
System.out.println("Max: "+max(a));
System.out.println("Min: "+min(a));
System.out.println("Sum: "+sum(a));
System.out.println("Avg: "+avg(a));
}
}
/*
Sample run:
Max: 5.0
Min: 1.0
Sum: 15.0
Avg: 3.0
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.