What's the difference when using numeric literal in termination expression of a for statement?
Asked Answered
J

1

2

Why does this piece of code:

String value = JOptionPane.showInputDialog("Enter x"); //Input = 100
int x = Integer.parseInt(value);
double result = 1;

for (int i = 1; i <= x; i++) //used variable "x" here
{
    result += (x * 1.0) / fact(i);
    x *= x;
}

public static int fact(int n) {
    int fact = 1;
    for (int i = 1; i <= n; i++) {
        fact *= i;
    }
    return fact;
}

work differently from this one?

String value = JOptionPane.showInputDialog("Enter x"); //Input = 100
int x = Integer.parseInt(value);   
double result = 1;

for (int i = 1; i <= 100; i++) //and here I used the value "100"
{
    result += (x * 1.0) / fact(i);
    x *= x;
}

public static int fact(int n) {
    int fact = 1;
    for (int i = 1; i <= n; i++) {
        fact *= i;
    }
    return fact;
}

The only change that I made was using the value 100 instead of using the variable x in my termination expression!

When I run the first code, I get:

9.479341033333334E7

However, for the second one I always get

NaN

Why?

Jarid answered 16/8, 2015 at 23:28 Comment(2)
Well, because x changes mid-loop in the first one.Tuberculosis
You might want to throw a comment in there to point at where the difference is. People whip through these questions, so it's in your interest to make your issue jump out at readers.Indirection
C
2

The difference between the two snippets is this:

for (int i = 1; i <= x; i++) {

vs.

for (int i = 1; i <= 100; i++) {

In the first case, x gets much larger every time! Eventually, it will stop when x overflows and becomes 0, which will be much sooner than in the second case. For an explanation as to why this results in 0 instead of some other random number, see: Why does this multiplication integer overflow result in zero?

In the second case, when i = 34, fact(n) will return 0, so the double division is (0 * 1.0) /0 which results in NaN. Any double, when added to NaN, becomes NaN, which is why the second snippet results in NaN. See: In Java, what does NaN mean?

Claudette answered 16/8, 2015 at 23:40 Comment(4)
x overflows and becomes 0 are you sure it will become 0 and not a negative?Giacomo
@LuiggiMendoza Yes, because I ran it. I'll be honest, I wasn't sure why.Claudette
Interesting, but knowing why it became 0 is outside of the quesiton. Good job done here.Giacomo
@LuiggiMendoza I figured out why it results in 0, and wrote it up hereClaudette

© 2022 - 2024 — McMap. All rights reserved.