|
-
December 29th, 2010, 07:23 PM
#1
I dont get this specific FOR loop.
I'm having trouble understanding a program that displays all prime numbers between 1 and 100. I know there are many ways of writing this, maybe easier, but I am having trouble understanding this one which is a sample bit of practice code from a book:
Code:
#include <iostream>
using namespace std;
int main()
{
int i, j;
bool isprime;
for(i=1; i < 100; i++)
{
isprime = true;
for(j=2; j <= i/2; j++)
if((i%j) == 0) isprime = false;
if(isprime)
cout << i << " is prime.\n";
}
system("PAUSE");
return 0;
}
The first For statement, I understand. That goes through all the numbers between 1 & 100.
This statement is used to reset the variable isprime back to true if it was set to false later on in the program.
Code:
for(j=2; j <= i/2; j++)
This is the statement that I am having trouble with. I'm not sure if its the mathematics that I don't understand or the code itself. Why is it that J is initialised to 2? And what is the condition j<=i/2 for? The other thing I noticed with this statement is that there are no curly braces '{ }' following it. I was under the impression that if the condition in the for statement is true, then there it would execute whatever is in the braces. If its false, it would bypass the content within the braces and execute the next statement outside the braces. But in this example there aren't any braces following it! The first FOR loop does have curly braces following it. Am I missing something here, theoretically?
Code:
if((i%j) == 0) isprime = false;
My understanding of the above statement is that if the division yields no remainder, set isprime to false
Code:
if(isprime)
cout << i << " is prime.\n";
The above statement says that if isprime is TRUE, print "<i>is prime"
Can anyone help me understand this? Thanks in advance.
Last edited by fsdama; December 29th, 2010 at 07:26 PM.
Reason: Thanking.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|