Home > Software engineering >  Why codeblocks asking me to add a ";" after else's condition? If I add a ":"
Why codeblocks asking me to add a ";" after else's condition? If I add a ":"

Time:10-21

Write a C program to check whether a given integer is positive even, negative even, positive odd or negative odd.

#include <iostream>
using namespace std;
int main()
{
    int n;
    cout<< "Enter the number you want to check: \n";
    cin>>n;

    if(n>0 &&n%2 ==0){
        cout<< "number is positive even \n";
    }
    else if(n<0 &&n%2 ==0){
        cout<< "number is negative even \n";
    }
    else if(n<0 &&n%2 !=0){
        cout<< "number is negative odd \n";
    }
    else (n>0 && n%2 !=0){
            cout<< "number is positive odd \n";
    }
    
    return 0;
}

This is my code. When I don't add a semicolon after else (n>0 && n%2 !=0). It shows an error: expected ';' before '{' token. When there is semi colon there is a logic error where else output is shown no matter what the number is.

CodePudding user response:

You can not write else (condition) without using if. the correct way is write else if (condition) like you are doing or you can simply write else { cout << "Number is positive"; }.

CodePudding user response:

You can't leave out the if when you have a condition - the compiler interprets n>0 && n%2 !=0 as the body of the else branch, equivalent to this:

else { 
    (n>0 && n%2 !=0)
}
{
        cout<< "number is positive odd \n";
}       

which is missing a semicolon - and if you add one, you get an expression that does nothing and an unconditional output, equivalent to:

else 
    n>0 && n%2 !=0;
cout<< "number is positive odd \n";

Since none of your conditions cover the case where n is zero, you probably want

else if (n>0 && n%2 !=0){
    cout<< "number is positive odd \n";
}
else {
    cout << "number is zero\n";
}

CodePudding user response:

This line: else (n>0 && n%2 !=0)

else means that if all the above if and if-else conditions are false, then the logic in the else condition is executed, no condition need. But you add a condition n>0 && n%2 !=0 which is wrong syntax.

You can fix it by changing:

else (n>0 && n%2 !=0){
    cout<< "number is positive odd \n";
}

To:

else if (n>0 && n%2 !=0){
    cout<< "number is positive odd \n";
}

Or:

else{
    cout<< "number is positive odd \n";
}
  •  Tags:  
  • c
  • Related