Reputation: 355
I made a recursive method to calculate factorials, but in the main method I have used a for loop to calculate the list of factorials. Is there a way to calculate a list of factorials without using a loop in the main method?
Code:
public class FactInt {
public static void main(String[] args) {
for (int n = 1; n < 11; n++)
System.out.println(factorial(n));
}
//Calculates the factorial of integer n
public static int factorial(int n) {
if (n == 0)
return 1;
else
return n*factorial(n-1);
}
}
Upvotes: 0
Views: 17179
Reputation: 1691
Use recursion again like this!
public class FactInt {
public static void main(String[] args) {
factorialList(1, 10);
}
//Calculates the factorial of integer n
public static int factorial(int n) {
if (n == 0)
return 1;
else
return n*factorial(n-1);
}
public static void factorialList(int min, int max) {
if (min != max)
factorialList(min, max-1);
System.out.println(factorial(max));
}
}
Upvotes: 0
Reputation: 26157
Actually I would want to say you can't or more like well why would you, but well if you really want to, you could do it like this.
public class FactInt {
public static void main(String[] args) {
factorial(10);
}
//Calculates the factorial of integer n
public static int factorial(int n) {
final int calc;
if (n == 0) { calc = 1; }
else { calc = n * factorial(n - 1); }
System.out.println(calc);
return calc;
}
}
Upvotes: 0
Reputation: 1315
Create a method say getFactorial(int num) as follows. Move your for loop inside that method and call that method from main.
public static void main(String[] args) {
int num = 11;
getFactorial(num);
}
public static void getFactorial(int num){
for (int n = 1; n < num; n++)
System.out.println(factorial(n));
}
//Calculates the factorial of integer n
public static int factorial(int n) {
if (n == 0)
return 1;
else
return n*factorial(n-1);
}
Upvotes: 0
Reputation: 178263
I don't know why you don't want to use a loop, but here's a couple ideas:
Unroll the loop yourself.
System.out.println(factorial(1));
System.out.println(factorial(2));
// ...
System.out.println(factorial(11));
Make another recursive method and call it from main
.
public static void factorials(int n)
{
if (n >= 11) return;
System.out.println(factorial(n));
factorials(n + 1);
}
Upvotes: 0
Reputation: 56536
It depends on exactly what you mean by "calculate a list", but this prints the same thing:
public static void main(String[] args) {
factorial(10);
}
//Calculates the factorial of integer n
public static int factorial(int n) {
if (n == 0)
return 1;
else {
int newVal = n*factorial(n-1);
System.out.println(newVal);
return newVal;
}
}
Upvotes: 8