(in java)
a. Include a good comment when you write the method described below: Write a method factorial which receives a positive integer n and calculates n! (n factorial), defined as follows: n!=1*2*…*(n-1)*n. For example, 5! = 1*2*3*4*5 = 120. The method should return this value to the calling program.
b. Write a driver program (main method) which will read an integer from the console, and pass it to the method to calculate its factorial. The main method then prints the original value and the calculated factorial.
import java.util.Scanner; public class FactorialLoop { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int n; System.out.print("Enter number: "); n = scanner.nextInt(); int res = factorial(n); System.out.println(res); } private static int factorial(int n) { if(n<=0){ return 1; } int res = 1; for(int i = 2;i<=n;i++){ res *= i; } return res; } }
Get Answers For Free
Most questions answered within 1 hours.