Question: Recursion? We're using recursion to ask a user for a number N, then calculate the following items: N! (N factorial) - the product of all

Recursion?

We're using recursion to ask a user for a number "N", then calculate the following items:

N! (N factorial) - the product of all the numbers from 1..N.

The Nth Fibonacci number (1, 1, 2, 3, 5, 8, ... look it up in Wikipedia).

The sum of all numbers between 1 and N.

Create a custom program, recursion.java, that prompts the user to enter a number. Then, using recursion, find the summation, factorial, and the Nth Fibonacci for the number given.

NOTE: make sure your program does not fail if an invalid response is given.

Sample Output:

Enter a positive integer: 5 The product of the numbers from 1 to 5 (5!) is: 120 
The sum of the numbers from 1 to 5 is: 15 
The 5th Fibonacci number is: 5 Deliverables: recursion.java 

This program hangles negative integers but doesn't handle letters, charachters ect.

*********************************************************************************************************************************

import java.util.Scanner;

public class Recursion {

public static void main(String[] args) {

int factorial;

System.out.println("Enter a positive integer");

Scanner sc=new Scanner(System.in);

int n=sc.nextInt();

while(n <=0) {

System.out.println("Invalid Input. Enter a positive integer");

n=sc.nextInt();

}

Recursion f=new Recursion();

factorial=f.fact(n);

System.out.println("The product of the numbers from 1 to "+n+" "+"("+n+") is: "+factorial);

int sum=f.sum(n);

System.out.println("The sum is: "+sum);

int fibonacci =f.fibonacci(n);

System.out.println("The "+n+"th Fibonacci number is: "+fibonacci);

}

int fibonacci(int n) {

if (n <= 1)

return n;

return fibonacci(n-1) + fibonacci(n-2);

}

int sum(int n) {

if (n == 1)

return 1;

else

return n + sum(n-1);

}

int fact(int x) {

if(x > 1)

{

return(x * fact(x - 1));

}

return 1;

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!