Create a java class with main() function to implement and test the \'myRecursive
ID: 3820426 • Letter: C
Question
Create a java class with main() function to implement and test the 'myRecursiveFunction()', factorial(), and exp() functions. Due today 4/18/2017 Create a java class with main() function to implement and test a recursive summation function(). Due today 4/25/2017 eL, CS231, assignments, HW21: attach the following: A pdf files with screen captures showing the compilation and execution results. PDF File names: CS231_lastname-firstname_HW21.pdf A zipped directory of all the java source files. File names: CS231_lastnamc-firstname_HW21.zipExplanation / Answer
ans 1:
class JavaTest {
static int n1 = 0, n2 = 1, n3 = 0;
public static void main(String[] args) {
// myRecursiveFunction to calculate the fibonicci series
int count = 9;
System.out.print("Fibonicci series : " + n1 + " " + n2);// printing 1st and 2nd numbers of series
myRecursiveFunction(count - 2);// n-2 because 2 numbers are already
// printed
// factorial to calculate the factorial of the given number
int number = 5;// number to calculate factorial
int fact = factorial(number);
System.out.println(" Factorial of " + number + " is: " + fact);
// calculating the exp using the Math utility functions
double x = 5;
double y = 0.5;
// print e raised at x and y
System.out.println("Math.exp(" + x + ")=" + Math.exp(x));
System.out.println("Math.exp(" + y + ")=" + Math.exp(y));
}
public static void myRecursiveFunction(int count) {
if (count > 0) {
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" " + n3);
myRecursiveFunction(count - 1);
}
}
public static int factorial(int number) {
int fact = 1;
for (int i = 1; i <= number; i++) {
fact = fact * i;
}
return fact;
}
}
output:
Fibonicci series : 0 1 1 2 3 5 8 13 21
Factorial of 5 is: 120
Math.exp(5.0)=148.4131591025766
Math.exp(0.5)=1.6487212707001282
--------------------------------------------------------------
ans2:
class FactorialTest {
public static void main(String args[]) {
int i, fact = 1;
int number = 5;// number to calculate factorial
fact = factorial(number);
System.out.println("Factorial of " + number + " is: " + fact);
}
// calculate factorial of the given number using recursion
public static int factorial(int n) {
if (n == 0)
return 1;
else
return (n * factorial(n - 1));
}
}
output:
Factorial of 5 is: 120
-----------------------------------------------------------------
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.