Respuesta :

Answer:

Written in Java

import java.util.*;

public class Main {

  public static int fact(int n) {

     if (n == 1)

        return n;

     else

        return n * fact(n - 1);

  }

  public static void main(String[] args) {

     int num;

     Scanner input = new Scanner(System.in);

     char tryagain = 'y';

     while(tryagain == 'y'){

     System.out.print("Number: ");

     num = input.nextInt();

     System.out.println(num+"! = "+ fact(num));

     System.out.print("Try another input? y/n : ");

     tryagain = input.next().charAt(0);

}        

  }

}

Explanation:

The static method is defines here

  public static int fact(int n) {

This checks if n is 1. If yes, it returns 1

     if (n == 1)

        return n;

If otherwise, it returns the factorial of n, recursively

     else

        return n * fact(n - 1);

  }

The main method starts here. Where the user can continue executing different values of n. The program keep prompting user to try again for another number until user signals for stoppage

  public static void main(String[] args) {

This declares num as integer

     int num;

     Scanner input = new Scanner(System.in);

This initializes tryagain as y

     char tryagain = 'y';

This checks if user wants to check the factorial of a number

     while(tryagain == 'y'){

This prompts user for input

     System.out.print("Number: ");

This gets user input

     num = input.nextInt();

This passes user input to the function and also prints the result

     System.out.println(num+"! = "+ fact(num));

This prompts user to try again for another value

     System.out.print("Try another input? y/n : ");

This gets user response

     tryagain = input.next().charAt(0);

}        

Ver imagen MrRoyal
ACCESS MORE