Hi. I read that the for function is a loop function. But, in reading up about the types of defined functions, I've come across the use of the for function to determine whether a number is prime or not. Here is the code (from programiz.com):
What I'm not sure about is how the function works in this example - as to a loop action. If I set n to 12 (keyboard-in 12), then "i" initially will have the value of 2 I believe. In that case, "i" will be smaller than 6 (12/2) and the test turns out true. So, "i" is incremented to 3 and the code below the for function runs. When printf() right at the end executes, I believe the program goes back to main() at line 7. Which again calls the function checkPrimeNumber(). Of course, that sets things in motion again and again the program halts until an integer is entered in from the keyboard and Enter is pressed. I see that whatever "i" is, it gets reset to 2 again as the for function again executes.
So, it looks like as it is, the code that is below the for function only executes once after a keyboeard entry. But of course, "I" only got to the value of 3, so I'm wondering (not withstanding what I've just said) what stopped the for function continuing to run the code below it. I see that normally "I" would get to 7, at which point the test would result in false and stop the for function from running the code below it. I hope my thinking makes some sense.
Thanks. Rich
Code:
#include <stdio.h>
void checkPrimeNumber();
int main()
{
checkPrimeNumber(); // no argument is passed to prime()
return 0;
}
// return type of the function is void because no value is returned from the function
void checkPrimeNumber()
{
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2; i <= n/2; ++i)
{
if(n%i == 0)
{
flag = 1;
}
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
}
So, it looks like as it is, the code that is below the for function only executes once after a keyboeard entry. But of course, "I" only got to the value of 3, so I'm wondering (not withstanding what I've just said) what stopped the for function continuing to run the code below it. I see that normally "I" would get to 7, at which point the test would result in false and stop the for function from running the code below it. I hope my thinking makes some sense.
Last edited: