228k views
5 votes
Create another method: getFactorial(int num) that calculates a Product of same numbers, that Sum does for summing them up. (1,2,3 ... num) Make sure you use FOR loop in it, and make sure that you pass a number such as 4, or 5, or 6, or 7 that you get from a Scanner, and then send it as a parameter while calling getFactorial(...) method from main().

1 Answer

2 votes

Answer:

The program in Java is as follows;

import java.util.*;

public class Main{

public static int getFactorial(int num){

int fact = 1;

for(int i =1;i<=num;i++){

fact*=i;

}

return fact;

}

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

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

int num = input.nextInt();

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

Step-by-step explanation:

The method begins here

public static int getFactorial(int num){

This initializes the factorial to 1

int fact = 1;

This iterates through each digit of the number

for(int i =1;i<=num;i++){

Each of the digits are then multiplied together

fact*=i; }

This returns the calculated factorial

return fact; }

The main begins here

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

This prompts the user for number

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

This gets input from the user

int num = input.nextInt();

This passes the number to the function and also print the factorial

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

User Portevent
by
7.6k points