0

I am doing a factorial question with java loop, it asks 1+1/2!+1/3!+...+1/n!, n is positive, I am using "while" to make it, but the code is run with nothing :

    public static void main(String[] args) {

    double sum=0,a=1;
    int n=Integer.parseInt(args[0]);
    while(n>0){

        a=a*n;
        sum=sum+1.0/a;
    }
    System.out.print(sum);

}

please help:)

2
  • 1
    How about decreasing n? Commented Aug 28, 2013 at 13:56
  • n will not decreased in the while loop. Commented Aug 28, 2013 at 13:57

4 Answers 4

6
while(n>0){
    a=a*n;
    sum=sum+1.0/a;
}

When do you change n? You don't. The condition will be always satisfied and you'll never exit the loop. Consider changing the value of n in the body of the loop.

 Iteration |   n
-----------+--------
     1     |   n      > 0 ? Yes
     2     |   n      > 0 ? Yes
     3     |   n      > 0 ? Yes
    ...    |
    ...    |
  Forever  |   n      > 0 ? Yes
Sign up to request clarification or add additional context in comments.

5 Comments

thanks Maroun, but the n is defined as long as it is a positive number, how can I achieve it if there is no maximum limit for n?
What exactly are you trying to achieve?
@WangPeiTheDancer how about decreasing the value of n? for example: n--;
but I am using command line arguments input to control n, so for example if n=3, is it not 1+1/1*2+1/1*2*3?
@WangPeiTheDancer You can set another variable to have the value of n, say i = n and perform the loop i times.
1

As others have pointed out, your original while loop never ends, because the value of n never changes, meaning that the while condition will always be true (assuming the original value was greater than zero).

Is this possibly what you are trying to achieve?

public static void main(String[] args)
{
    double sum = 0, a = 1;
    int n = Integer.parseInt(args[0]);
    for ( int i = 1; i <= n; i++ )
    {
        a *= i;
        sum = sum + (1.0 / a);
    }
    System.out.print(sum);
}

1 Comment

Hi munyul, yes, I tried this, it is what i want, thanks mate, I am bit lost in loop
0

Your code is equal to :

while(true){

    a=a*n;
    sum=sum+1.0/a;
}

You don't change n value ,n must be <=0 to break your loop.

1 Comment

it's more like if you wrapped the while(true) in an if(n>0)
0

Why not try a for loop let's say

public static void main(String[] args) {

    double sum=0;
    int  n=Integer.parseInt(args[0]);
    for(double a=1;a<=n;a++){

        sum=sum+1.0/a;
    }
    System.out.print(sum);

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.