0

I have this code in a function, but when it runs it does a long pause and then it says:

$floating point exception 

I am assuming this is due to multiple conditions in the for loop, but I don't know why it is wrong. Any ideas?

int i,j,number=5; for (i = 2; (i < number || j==1); i++) { if (number%i==0) { j = 1; } } 
2
  • 1
    What are the types of i, j, and number? Commented Jul 16, 2011 at 18:11
  • 3
    Post a minimal compilable example that reproduces the error! Commented Jul 16, 2011 at 18:12

4 Answers 4

7

floating point exception - This means there's an arithmetic error.

It looks like you're trying to stop the loop with j, but what you're actually doing is continuing the loop forever (because once you get j==1 the or condition is always true).
What then happens is you loop i through all the Integer values back to 0 and get the exception.

What I think you want to do is :

for (i = 2; (i < number); i++) { if (number%i==0) { j = 1; break; } } 
Sign up to request clarification or add additional context in comments.

1 Comment

@EO You don't have to use the Break, you could change the loop condition (but i think it's less expressive of the intention): for (i = 2, j=0; (i < number && j!=1); i++)
2

Remember that the condition is for the loop to continue, not for it to end.

It's difficult to look at your code and see intuitively what you're trying to do. Although you could fix this by flipping some logic around (you meant (i < number && j != 1)), it's best to stop and use break inside the loop instead. The logic will be far clearer, and then you won't make errors like this.

Comments

1

Once you set j to 1 the loop will go on forever. If you want to stop the loop when the if condition is true use break.

Comments

0

You will get into an infinite loop when the if-statement is reached. This will cause the error. You probably wanted to stop the loop if j == 1? Then you had to write

for (i = 2; (i < number || j!=1); i++) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.