200k views
1 vote
Write a function in Java called factorial() that will take a positive integer as input and returns its factorial as output.

1 Answer

9 votes

Answer:

The function is as follows:

public static int factorial(int n){

int fact = 1;

for(int i=2;i<=n;i++){

fact*=i;

}

return fact;

}

Step-by-step explanation:

This line defines the function

public static int factorial(int n){

This declares and initializes variable fact to 1

int fact = 1;

This iterates from 2 to n

for(int i=2;i<=n;i++){

This line multiplies all integers from 1 to n

fact*=i;

}

This returns the factorial

return fact;

}

User Nikos Athanasiou
by
4.5k points