This is a approach for Weather a number is prime or not
QUESTION:
int main()
{
int i, num, b;
printf("ENTER A NUMBER : \n");
scanf("%d", &num);
for (i = 2; i <= num - 1; i++)
{
if (num % i == 0)
break;
}
if (i == num)
printf("PRIME");
else
printf("NOT A PRIME");
return 0;
}
How will the value of i will be incremented if loop is completed..The condition for stopping is num-1 then how in next statement value of i will be == num
Ex: if i enter 5 loop will run till 4 and value of i will be 4 then how will it will be == num..
Hope question is understood.
>Solution :
The body of the for loop is executed as long as the test condition is true. That means, when the loop stops executing because of the test condition (rather than because of the break), the test condition is false.
Therefore, when the loop ends this way, i <= num - 1 is false. Since num is 5, that means i <= 4 is false, which occurs when i has become 5.