i m new to C++ programming. i just want to print the prime numbers on screen.

number is given by the user. error show when i compile the code "18 syntax error before `<<' token " plz suggest where is fault.below is my code



#include<iostream>
using namespace std;

int i;


int main()
{
cout<< "enter number""\n";
cin>>i;


for(i=2;i<=2;i++)

if (i%i==0)(i%i+1==0)

cout<<"prime""\n";
else
cout<<"not prime";

return 0;
}
hi,
there are a few problems with the for-loop.
first, you use "i" as the loop variable, and therefore you loose the value you just read with the cin statement.
so better use another one, like this:

1
2
3
4
for (int j = 2; j < (int) ( sqrt(i)+1); j++)
{
    (here the rest of your code)
}


the if-statement you make is also a bit strange.

try something like
1
2
3
4
if (i%j == 0)
{
   blah blah
}

closed account (zb0S216C)
Where to start? I'll start from the point after attaining input.

When you begin your loop, the initialisation section of the loop erases the input the user gave, replacing it with the value of 2. At this point, the input is well-known. The condition section of the loop causes the loop to end as soon as it's encountered; the loop executes once.

Next, the "if" statement. A few notable ill-logic things are happening here. First, the condition divides "i" by itself, which will always evaluate to zero. Therefore, your condition is always true, and the subsequent statement is executed. The statement that follows is pointless at best. This expression is a Boolean context, and means nothing outside an initialisation, and/or conditional context. There's no point in walking through this expression. Because the two last two lines do not affect program output or flow, the compiler will optimise these away, as well as the loop in which they reside, and the "else" branch.

Once the compiler omits the said statements, you're left with this:

1
2
3
4
5
6
7
8
9
int main( )
{
    std::cout<< "enter number""\n";

    int i(0);
    std::cin>>i;

    return(0);
}

[Note: These are my initial assumptions, and may not be entirely accurate.]

Wazzak
Last edited on
i did some modification in the code but still have some problem plz guide me in detail where i doing wrong.


#include<iostream>
using namespace std;

int num;
int counter;
int r; // result to store

int main()
{
cout<< "enter number""\n";
cin>>num;

{
int i;
for(i=2;i<=num;i++)

if (i%num==0)
r=counter;

break;
}

cout<<"prime""\n";

cout<<"not prime""\n";

return 0;
}
Topic archived. No new replies allowed.