+ 1

how can I accept 10 random numbers for user and then find the sum of their factorial? please help.....

2nd Jan 2017, 10:09 AM
Soumya
Soumya - avatar
6 odpowiedzi
+ 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
2nd Jan 2017, 10:27 AM
Andreas K
Andreas K - avatar
+ 2
You can reduce my solution by executing the factorial function directly after you did an input and add it to your sum variable.
2nd Jan 2017, 3:27 PM
Andreas K
Andreas K - avatar
2nd Jan 2017, 10:24 AM
Roman Gräf
Roman Gräf - avatar
0
@Roman why don't let people try on their own with hints from us without giving them a complete solution in code?!
2nd Jan 2017, 10:33 AM
Andreas K
Andreas K - avatar
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); } }
2nd Jan 2017, 10:36 AM
Leonida17st
Leonida17st - avatar
0
but I need to do it without array...
2nd Jan 2017, 3:25 PM
Soumya
Soumya - avatar