I know a for loop has the form..
for (expr1 ; expr2; expr3) statement
The loop body is the statement, correct?
my book shows this example
Suppose we're writing a program that checks whether a number is prime. Our plan is to write a for stmt that divides n by the numbers between 2 and - 1. We can break out of the loop as soon as any division is found, there's no need to try the remaining possibilities. After the loop has terminated, we can use an if statement to determine whether termination was premature (hence n isn't prime) or nomal (n is prime):
The book says that the break is useful for writing loops that exit in the middle of the body rather than at the beginning or end. But in the above example, isn't the loop body the statement if (n %d ==0) ??? If so, how can it be considered that the break is exiting in the middle of the loop? It appears to me that the loop is terminated because break comes after the complete statement.
Of course I'm probably wrong and the book is right, but why? That's the way it looks to me. I don't see a compound statement up there, it would have to be separated by commas.
Thanks
for (expr1 ; expr2; expr3) statement
The loop body is the statement, correct?
my book shows this example
Suppose we're writing a program that checks whether a number is prime. Our plan is to write a for stmt that divides n by the numbers between 2 and - 1. We can break out of the loop as soon as any division is found, there's no need to try the remaining possibilities. After the loop has terminated, we can use an if statement to determine whether termination was premature (hence n isn't prime) or nomal (n is prime):
Code:
for(d = 2 ; d < n; d++)
if (n % d ==0) break ;
if (d < n)
printf ("%d is divisible by %d\n", n, d) ;
else
printf ("%d is prime\n", n) ;
The book says that the break is useful for writing loops that exit in the middle of the body rather than at the beginning or end. But in the above example, isn't the loop body the statement if (n %d ==0) ??? If so, how can it be considered that the break is exiting in the middle of the loop? It appears to me that the loop is terminated because break comes after the complete statement.
Of course I'm probably wrong and the book is right, but why? That's the way it looks to me. I don't see a compound statement up there, it would have to be separated by commas.
Thanks