+ 1
how can I accept 10 random numbers for user and then find the sum of their factorial? please help.....
6 Antworten
+ 2
First you use a simple for loop to input int values by using e.g. Scanner and insert them one by one into an int array of size 10.
Then you write your second for loop for executing a factorial for each value in the array.
The second point is our factorial method which looks like following header "fact(int n). It's a method from return type int. I will describe the recursive solution for a factorial algorithm.
It has two base cases. First one: If n equals 1 return 1.
else return n times fact(n-1)
Good Luck
+ 2
You can reduce my solution by executing the factorial function directly after you did an input and add it to your sum variable.
0
@Roman why don't let people try on their own with hints from us without giving them a complete solution in code?!
0
import java.util.Scanner;
public class Program
{
public static int factorial(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
public static void main(String[] args) {
int[] arr = new int[10];
long sum=0;
Scanner inp = new Scanner(System.in);
for(int i=0;i<10;i++){
arr[i] = inp.nextInt();
sum=sum+factorial(arr[i]);
}
System.out.println("sum is : " + sum);
}
}
0
but I need to do it without array...