#include %26lt;iostream.h%26gt;
int main() {
int num, num2,a,b;
do{
cout %26lt;%26lt; "Enter a value in the range of 1 to 100: ";
cin %26gt;%26gt; num;
if(num %26lt; 1 || num %26gt; 100)
cout %26lt;%26lt; "Out of range; Please try again... " %26lt;%26lt; endl
%26lt;%26lt; endl;
}while (num %26lt; 1 || num %26gt; 100);
int counter = 0;
for (a = 0; a %26lt;= num; a++){
}
for (b = 1; b %26lt; a; b++){
if (a % b == 0)
counter++;
if (counter == 1)
cout%26lt;%26lt; "The prime numbers are " %26lt;%26lt; a %26lt;%26lt; " ";
}
return 0;
}
Enter a value from 1 to 100: -5
Out of range; Please try again...
Enter a value from 1 to 100: 200
Out of range; Please try again...
Enter a value from 1 to 100: 101
Out of range; Please try again...
Enter a value from 1 to 100: 45
The prime numbers are:
1 2 3 5 7 11 13 17 19 23 29 31 37 41 43
This is what the output supposed to look like, but when I ran my code, the prime number output does not come out right. can anyone help me fix the problem?
What is wrong with my c++ code?
Here is a cleaner version of your code:
#include %26lt;iostream.h%26gt;
// The following functions works on positive integers greater
// than zero only
bool isPrime(int number);
int main()
{
int num= 0;
do
{
cout %26lt;%26lt; "Enter a value in the range of 1 to 100: ";
cin %26gt;%26gt; num;
if(num %26lt; 1 || num %26gt; 100)
cout %26lt;%26lt; "Out of range; Please try again... " %26lt;%26lt; endl
%26lt;%26lt; endl;
}while(num%26lt; 1 || num %26gt; 100);
cout%26lt;%26lt; "The prime numbers are: " %26lt;%26lt; endl;
for(int i = 1; i %26lt; num; i++)
{
if(isPrime(i))
cout %26lt;%26lt; i %26lt;%26lt; " ";
}
cout %26lt;%26lt; endl;
return 0;
}
bool isPrime(int number)
{
for(int i = 2; i %26lt; number - 1; i++)
{
if((number % i) == 0)
return false;
}
return true;
}
Reply:heres the problem with your code. you wrote:
int counter = 0;
for (a = 0; a %26lt;= num; a++){
}
for (b = 1; b %26lt; a; b++){
if (a % b == 0)
counter++;
if (counter == 1)
cout%26lt;%26lt; "The prime numbers are " %26lt;%26lt; a %26lt;%26lt; " ";
}
your first "for" loop does nothing because there is nothing between the brackets.
the loop is:
for (a = 0; a %26lt;= num; a++){
}
i think what you wanted is this:
for (a = 0; a %26lt;= num; a++)
__{
__for (b = 1; b %26lt; a; b++)
____{
____if (a % b == 0)
______counter++;
____if (counter == 1)
______cout%26lt;%26lt; "The prime numbers are " %26lt;%26lt; a %26lt;%26lt; " ";
____}
__}
Reply:First you haven't initialised your variable so it might already have a number value within the range. Set it to zero before you start. num=0;
It also looks like your program will only run through the counter and then output prime numbers if the counter = 1. You need to output your numbers from within a loop so that they are output each time you reach one.
Reply:oh
big mistake
A %26amp; B is missing before C
bye
good night
bloom
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment