Raphael
Raphael

Reputation: 161

For loop confused as to which value to consider

I have this loop here:

while(n != 0)
    {
        ld = n % 10;
        System.out.println(ld);

        for ( i=1; i <= ld; i++)
        {
            f = f * i;
        }

        System.out.println(f);

        n /= 10;
    }

Let us consider a number, say 123. Now, this loop calculates the factorial of 3 accurately, but when it restarts to calculate the factorial of 2, the for loop gets confused as to which value to take for the variable ld. Is there any solution to this?

Upvotes: -1

Views: 60

Answers (4)

skprime
skprime

Reputation: 55

Most important:

  1. Now our loop resets f to 1 every "repeat".

Additional:

  1. Added int i = 1 to for loop.
  2. You can use f *= 1; instead of f = f * 1;
  3. Changed n != 0 to n > 0 for more safety .

    while(n > 0) {

    ld = n % 10;

    System.out.println(ld);
    
    f = 1;   
    
    
    for(int i = 1; i <= ld; i++)
    {
        f *= i;
    }
    
    System.out.println(f);
    
    
    n /= 10;   
    

    }

Upvotes: 1

Zia
Zia

Reputation: 1011

You may look in to this code,code is ok just need to set the value for f inside the loop for each digit for given number.

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
    int ld;
        int n=123;

    while(n != 0)
    {
            int f=1;
        ld = n % 10;
        System.out.println(ld);

        for ( int i=1; i <= ld; i++)
        {
            f = f * i;
        }

        System.out.println(f);

        n /= 10;
    }
    }
}

output are as

3
6
2
2
1
1

Upvotes: 1

RockAndRoll
RockAndRoll

Reputation: 2277

You need to reset f once you are done with one number. Add f = 1; when you enter in while loop.

Solution

      while(n != 0)
        {
            ld = n % 10;
            f = 1;// add this
            System.out.println(ld);

            for (int i=1; i <= ld; i++)
            {
                f = f * i;
            }

            System.out.println(f);

            n /= 10;
        }

Upvotes: 1

Eran
Eran

Reputation: 393846

The problem is not ld. You forgot to resetf in each iteration.

while(n != 0)
{
    ld = n % 10;
    System.out.println(ld);
    f = 1; // reset f
    for ( i=1; i <= ld; i++)
    {
        f = f * i;
    }

    System.out.println(f);

    n /= 10;
}

Output :

3
6 // factorial of 3
2
2 // factorial of 2
1
1 // factorial of 1

Upvotes: 3

Related Questions