Else statement

Sorry if I sound stupid but this project is generating an error in my compiler.
I want the end statement to be displayed when x is equal to 100.

But an error is generated once compiled:


#include <iostream>
using namespace std;

int main ()
{
int x;

cout <<"Please enter the value of \n"
<< "x: ";
cin >> x;

if (x > 0 )
cout << "x is positive";
else if (x < 0 )
cout <<"x is negative";
else (x == 100)
cout << "x is 100";

return 0;
}

Thanks for the help in advanced :)
else can not have a condition. It is executed when the previous condition is false.

1
2
3
else (x == 100)  // makes no sense

else if(x == 100)  // makes sense, but still wrong (see below) 


The 2nd line there will solve the compiler error, but will not print when x is equal to 100, because it is trumped by an earlier if statement.

Here's how it'd work:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int x = 100;

if(x > 0)  // 100 is > 0, so this is true
{
  // this code will be executed
  //  and the following else statement(s) will not be
}
else if(x < 0)
{
  // this is skipped because previous if() was true
}
else if(x == 100)
{
  // this is also skipped because previous if() was true
  //  it doesn't matter whether or not x==100 is true
  //  because the 'else' makes it skip over the condition entirely.
}



If you want to have a x==100 condition, you either need to remove the else (in which case BOTH the x>0 and x==100 code will execute), or you need to move the x==100 condition so that it's earlier in the chain and has a higher priority.
Thank you for the quick reply my friend.
You have helped loads :)
hello,i have some sort of question,y now Disch is the real pro between us,but i think that is this situations where you have more conditions,you can put the most important,or the one in a million shot (if i can say that) condition first..so that you verify the first time if (in you're case) x==100.because if x==100 it does not matter if it is positive or negative.from 0 to 100 there are many positive numbers,but only one is unique..hope thismethod is good.
That is correct, Mihay.

Those conditions would have a higher priority and would need to go earlier in the chain.
Topic archived. No new replies allowed.