1 #include<iostream>
2 usingnamespace std;
3 int i
4 bool isPrime(int number)
5 {
6 int i;
7 for (i=2; i<number; i++)
8 { if(number% i==0)
9 isPrime=false;
10 }
11 if (isPrime==true)
12 cout << "true" << endl;
13 }
14 int main()
15 { int counter=0;
16 int current_number=2;
17 cout<< "First 1000 prime numbers" << endl;
18 while (counter <1000)
19 { if (prime_number(current_number)==true)
20 { cout << current_number << endl;
21 counter++;
22 }
23 current_number++; }
24 return 0;
25 }
26
~
~
when I try to compile it I get an error saying it expects an initializer before bool
what is that? what would my initializer be? Anything else I could do to fix my code?
how can you fix this, when your teacher told you to use "while" not "bool"?
my question : type random number and the answer must be: "This is prime number" or " This isn't prime number"
#include <iostream>
usingnamespace std;
int main()
{
int number;
int i = 2;
cout << "Enter number: ";
cin >> number;
while (i < number)
{
if (number % i == 0)
{
cout << "The number is divisible by " << i
<< " and therefore is not prime";
break;
}
++i;
}
if (i == number)
cout << "The number is prime.";
return 0;
}
This code uses a while statement while getting rid of the bool function.
i starts at 2. The while loop is initially true, since i < number. (if number > 2)
if (number % i == 0) means that if number is divisible by i, then it displays that message, and exits the loop.
If number is not divisible by i, then i increments, and the loop starts again with the next number.
If i goes through all numbers up to numberand number still isn't divisible by i, then i ends up equaling number, and the second if statement becomes true.
The reason the second if statement doesn't execute if number isn't prime is because of the break statement inside the loop, which causes the loop to terminate before i is incremented.