It is easy to test:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <cstdio>
int main()
{
int num = 7;
int x;
for ( x = 2; x <= num / 2; x = x + 1) {
printf( "within loop: %d\n", x);
}
printf( "After loop: %d\n", x);
return 0;
}
|
Produces:
within loop: 2
within loop: 3
After loop: 4 |
In other words,
1. The loop first initializes x with with value 2
2. Since 2 <= 3 (remember: 7/2==3) the loop body prints "within loop: 2" and x is incremented to 3
3. Since 3 <= 3 the loop body again prints "within loop: 3" and x is incremented to 4
4. The 4 <= 3 is not true and the loop ends without changing the x any more.
5. Line 11 prints "After loop: 4"
Note that
1 2 3
|
for ( x = 2; x <= num / 2; x = x + 1) {
printf( "within loop: %d\n", x);
}
|
could be written
1 2 3 4
|
for ( x = 2; x <= num / 2; ) {
printf( "within loop: %d\n", x);
x = x + 1;
}
|
and also
1 2 3 4 5
|
x = 2;
while ( x <= num / 2 ) {
printf( "within loop: %d\n", x);
x = x + 1;
}
|
Further note that there is are
compound assignment operators.
+=
is one of them.
Furthermore, there are pre- and post-increment and -decrement operators.
The following three lines do the same operation:
1 2 3
|
x = x + 1;
x += 1;
++x;
|
Why divide num by 2?
The loop tests whether value i is a divisor of num.
How many values are there that are larger than num/2 and can divide num?
Num itself, of course, because num/num==1, but are there other values?
If there were such value X, then num/X must be less than 2 but more than 1 and there is no such integer.
In other words: we know analytically that it is pointless to test values that are greater than num/2.