here iam trying to get the factorial of N of numbers entered by the user , the problem is I want to display the output after entering all of the inputs,
my code here display the output like this:
2 "N of numbers"
5 "first input"
120 "output of first input"
3 "second input"
6 "output of second input"
and I want it to be like this:
2 "N of numbers"
5 "first input"
3 "second input"
120 " output of first"
6 "output of second"
public class NewMain {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
for (int i = 0; i < N; i++) {
int F = 1;
int num = in.nextInt();
for (int j = num; j > 0; j--) {
F = F * j;
}
System.out.println(F);
}
}
}
>Solution :
One option is to save the inputs to an array or list, and then loop over it and print all the results once the input is done. E.g.:
int[] inputs = new int[N];
for (int i = 0; i < N; i++) {
inputs[i] = in.nextInt();
}
for (int i = 0; i < N; i++) {
int F = 1;
for (int j = inputs[i]; j > 0; j--) {
F = F * j;
}
System.out.println(input[i] + "! = " + F);
}