'Else' without a previous if

Why does it say there isn't any if before the else command?
Tried it several times.
btw, this is a program designed to show all the numbers from 1-1000 that can be divided by 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 #include <iostream>
using namespace std;
int main()
{
    int a;
    a=1;
    while(a<=1000);
    if(a%2==0);
        cout<<a;
    a++;
    else
        a++;

    return 0;
}
Last edited on
You have not set open bracket after while statement and close bracket.
Than you have to put open and close bracket at if statement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 #include <iostream>
using namespace std;
int main()
{
    int a;
    a=1;
    while(a<=1000) {
         if(a%2==0) {
         cout<<a;
         a++;
         } else {
             a++;
            }
}

    return 0;
}
cout<<a; is not part of the if statement because of the semicolon at the end of the previous line. if(a%2==0); means if a is an even number do nothing.
Thank you
#include <iostream>
using namespace std;
int main()
{
int a;
a=1;
while (a<=1000)
{
if ( a%2==0)
{ cout<<a; }
a++;
}
return 0;
}




semi-colon after the condition means an empty body. And one more thing u can optimize your code by eliminating else.
Topic archived. No new replies allowed.