Can any one please explain the for statement in this code, I understand the initialization of i=2 and the increment of i=i+1, but I dont understand the conditional test of i<(num/2)+1. The program displays all the factors of a number entered by the user. I don't understand why you need the +1 and the num/2. Thanks

#include <stdio.h>
int main()

       int num, i;
         printf("Please enter number: ");
         scanf("%d", &num);
         for(i=2; i<(num/2)+1; i=i+1)
               if((num%i)==0) printf("%d\n", i);
  return 0;


This line only loops until half of the number. That's because when you're determining factors for a number, anything larger than the number divided by 2 obvioulsy can't go evenly into the number. So to save time it cuts the number of loops it has to do in half.

For example:

The factors of 52 are:

As you can see, 26 is the last factor. And 26 happens to be 52 divided by 2.

[edit]Well, technically 52 and 1 are also factors, which is something the program fails to print[/edit]

By the way:

for(i=2; i<(num/2)+1; i=i+1)

A better way to increment a variable is simply to use the post/pre-increment operator:

for(i=2; i<(num/2)+1; i++)

Thank you for helping me, as I said before the community of programmers at daniweb are the most helpful and respectful by far, Thanks again

Just a minor point, better use ++variable instead of using variable++. If done so prevents the creation of a temporary variable. This is a normal hack used by all programmers.

• Pre-increment(++a) - Increment the value of variable and then use it.

• Post-increment (a++) - Use the value of variable and then increment it.

Since we just want the value of variable to be incremented, just use pre-increment.

commented: Thanks for the info :) - joeprogrammer +6

Thanks for the advice ~S.O.S~

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.