I started learning to program with C++ for about a month ago. I'm following the book C++: A beginner's guide second edition, and use it about half an hour every day. It's very fun!
I've reached the end of module 2 of the book, and one of the summary questions asked me how I could make a program that would show all the prime numbers from 1-100. I tried for a long time to think of a way to do it, but didn't manage to think of anything. I checked the answers:
// a program that finds all of the prime numbers between 1 and 100
#include <iostream>
usingnamespace std;
int main()
{
int i, j;
bool isprime;
for(i = 1; i <= 100; i++)
{
isprime = true;
// see if the number is evenly divisable
for(j = 2; j <= i/2; j++)
// if it is, then it is not prime
if((i % j) == 0)
isprime = false;
if(isprime)
cout << i << "is prime.\n";
}
return 0;
}
Now, I understand all of the parts of this program, but I just can't see how it actually works. Could someone explain in detail how the last part of the program works?
I'll try to go through it, and see where I fall off.
The first for statement starts out at i=1 and adds +1 if it is not 100. isprime is then equal to true for the moment.
the second for statement sets j=2 and adds +1 if it is less than or equal to the sum of i/2 (why? what does it gain by adding +1 to j?).
If the second for statement is activated, then the first if statement is also activated. This one checks if there is any remainder of i / j. If it has a remainder, then it will not be equal to 0, and therefore, isprime will remain true. Which is odd, considering the point of a prime number is that it doesn't have a remainder.. If the remainder was 0 however, isprime would be set to false, which makes no sense.