From loop to nested loops?

I have this program that returns a factorial N. For example, if you enter 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); 
        }         
    }
}

      

+2


a source to share


4 answers


If written as nested loops, it would look like this:

for (int i = 1; i < N; ++i)
{
    int factorial = 1;
    for (int j = 1; j <= i; ++j) {
         factorial *= j;
    }
    System.out.println(i + "! = " + factorial); 
}

      

Result:



Enter a number : 10
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880

      

This program gives the same result as yours, it takes longer. That you are already good. Note also that the factorial function grows very quickly, so it int

will be too small to hold the result even for a moderately large N.

If you want to include 10!

in the result, you need to change the condition for i < N

to i <= N

.

+2


a source


Now you are calculating your factorial gradually. Just recalculate it from scratch every time. Keep in mind that what you have now is better than what I am posting, but it suits your requirements.



public class TwoForLoops
{   
    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 = 1;
            for(int j = 1; j <= i; j++)
            {
                 factorial *= j;         
            }
            System.out.println(i + "! = " + factorial);         
        } 
    }
}

      

+1


a source


Instead of just calculating everything in a linear fashion, you can consider an inner loop that will do something like what you have in the outer loop. Is this what you are trying to achieve?

0


a source


Do you think of recursion as a nested loop?

public long factorial(int n)
{
    if (n <= 1)
        return 1;
    else
        return n * factorial(n - 1);
}

public static void main(String [] args)
{
    //print factorials of numbers 1 to 10
    for(int i = 1; i <= 10; i++)
        System.out.println(factorial(i));
}

      

0


a source







All Articles