I have this program that returns a factorial of N. For example, when entering 4,,, it will give 1! , 2! , 3!
How could I convert this to use nested loops?
public class OneForLoop
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number : ");
int N = input.nextInt();
int factorial = 1;
for(int i = 1; i < N; i++)
{
factorial *= i;
System.out.println(i + "! = " + factorial);
}
}
}
If written as nested loops it would look like this:
Result:
This program gives the same result as yours, it just takes longer to do so. What you have already is fine. Note also that the factorial function grows very quickly so an
intwill be too small to hold the result for even moderately large N.If you want to include
10!in the result you need to change the condition fori < Ntoi <= N.