A
for
loop is pretty simple - it comes in four parts:
for (a; b; c) d
Where:
a
initialises the loop and sets up to run. This is executed once, and once only each time you code reaches the
for
b
is run immediately before the body of the loop code (
d
) is executed, and if it evaluates to
true
then the body is executed. If it doesn't, then teh loop is exited.
c
is run immediately after the body of the loop code (
d
) is executed to set up for the next iteration.
d
is the body of the loop, and is teh code that is executred once each time the loop goes round.
So if a was
int i = 0
b was
i < 3
c was
i++
then the loop body would execute three times, once for i = 0; then i=1; then finally for i = 2
And you would get
a
Set i to 0
b
Is i < 3? Yes - continue with loop
d
Execute body
c
Add one to i
b
Is i < 3? Yes - continue with loop
d
Execute body
c
Add one to i
b
Is i < 3? Yes - continue with loop
d
Execute body
c
Add one to i
b
Is i < 3? No - exit loop.
In your case,
c
is
i < num
which is making sure that you prime test stops when the value reaches the number ("
i <= num
" won't help, because by definition, all numbers are divisible by themselves)
As to why you might use
i <= num / i
Think about it with an example.
Assume num is 41, and your test sequence is:
i num / i
2 20
3 13
4 10
5 8
6 6
7 5
Once you have got to 6 x 6, there is no point in further testing: because by definition you have already tested for divisibility by 5, 4, 3, and 2!