if else not working?

When I put in a negative altitude it prompts me to enter a positve one but one I do the program doesnt follow through to the else if statement. How do I fix this? I'm supposed to be able to enter a negative number and get reprompted until I enter a positive and then the programs goes on to the else. What am I doing wrong?

cout << "Enter the current altitude of the ship: ";
cin >> altitude; '\n';

if (altitude<=(0))
{cout << "Please enter a positive integer for altitude: ";
cin >> altitude;}

else if (altitude>(0))
{
cout << "Enter the current fuel supply of the ship: ";
cin >> currentfuel; '\n';
cout << "Enter the strength of the enemy tractor beam: ";
cin >> beam_stregth; '\n';
}

return 0;
}
You might be misunderstanding the purpose of else

An else block will only execute if the previous if block did NOT execute.

Therefore:

1
2
3
4
5
6
7
8
9
if( altitude <= 0 )
{
    // if this code executes
}
else if( altitude > 0 )
{
    // then this will not, because the 'else' ensures that this will only
    //   run if the previous if block did not run
}


I don't think you want to use else here.
I would write

1
2
if (altitude <= 0) { /* ... */ }
if (altitude > 0) { /* ... */ }

because it is guaranteed that only one of those will execute, provided that altitude does not get modified inside the conditionals.
I used a while instead of the if and an if instead of the else and it works beautiful now! THANKS

oh and you definitely clarified if/else for me :)
Topic archived. No new replies allowed.