Hi everyone! Stumbled upon this problem from jumping into c++ that asks to write program to generate prime number. I have already written the code with another approach(that doesn't use function and instead, uses two loops.) my code can be found here.( cpp.sh/3vho )
but i can't seem to understand one part of the code shown in the book
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
(just for reference and big picture, the entire code shown in the book is here.
later again shown only the part which i don't understand)
the entire code is:
#include <iostream>
// note the use of function prototypes
bool isDivisible (int number, int divisor);
bool isPrime (int number);
using namespace std;
int main ()
{
for ( int i = 0; i < 100; i++ )
{
if ( isPrime( i ) )
{
cout << i << endl;
}
}
}
bool isPrime (int number)
{
for ( int i = 2; i < number; i++)
{
if ( isDivisible( number, i ) )
{
return false;
}
}
return true;
}
bool isDivisible (int number, int divisor)
{
return number % divisor == 0;
}
|
NOw what i don't understand:
1 2 3 4 5 6 7 8 9 10 11
|
bool isPrime (int number)
{
for ( int i = 2; i < number; i++)
{
if ( isDivisible( number, i ) )
{
return false; //tag 1. don't understand this part
}
}
return true; //tag 2. don't understand this part as well
}
|
1.when the number being tested is divisible (i.e returns true by isDivisible test), then what is the significance of "return false;" in the body of if statement(see tag 1.)
2.in the body of isPrime, but outside 'for' loop, "return true;" is stated.
(see tag 2)won't the "return true;" be executed for all numbers tested in the
isPrime function so that all the numbers tested in the isPrime function return true and thus, print the entire number from 1 to 99.
I hope I could make u understand what i mean. if u didn't understand my question please say so, and i will try to be more explicit.
Any help would be highly appreciated.