1. Engineering
  2. Computer Science
  3. create a class called recursive with two methods public static...

Question: create a class called recursive with two methods public static...

Question details

Create a class called Recursive with two methods:

public static int fact (int n)

public static int sum(int n)

Implement fact() so that it computes the factorial of its parameter n. E.g., fact(3) should return 6, since 3! = 1 * 2 * 3 = 6. The implementation must be recursive.

Implement sum() so that it computes the sum of the integers from 1 to n inclusive. E.g., sum(5) should return 15=1+2+3+4+5. The implementation must be recursive.

Create a main method that will test fact() and sum(). It should call fact() and sum() with different arguments to show that they work. The factorial and sum computed for each of the different arguments should be printed out to the screen. Each function should be called with 3 times with different arguments, and one of the times the argument should be a 1.

Here is my code for the 2 methods:


public class Recursive
{
public static int fact (int n)
{
int result;
if(n==1)
result = 1;
else
result = fact(n-1) * n;
return result;
}

public static int sum(int n)
{
int result;
if(n==1)
result = 1;
else
result = n*(n+1)/2;
return result;
}
}

But how do I write a main method that will call those with different arguments?

Thanks!

Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution