Why does line 17 never gets executed. I believe that it(if else statement) gets terminated as soon as it meets the first condition. If so, how to solve this problem. Are there any way to check all of the conditions?
#include <iostream>
/*
Why does the third if else statement never gets executed. I believe that
it(if else statement) gets terminated as soon as it meets the first
condition. If so, how to solve this problem. Are there any way to check
all of the conditions?
*/
int main() //This check if you can drive a car or not
{
int age;
std::cout << "Enter your age: ";
std::cin >> age;
if (age >= 18)
std::cout << "You can drive.\n";
else if (age < 18)
std::cout << "You have to be 18 to drive.\n";
else if (age >= 80) // 80 and above should not drive
std::cout << "You are too old to drive\n";
return 0;
}
CodePudding user response:
Your first test is for age >= 18
. Any age above 18
will pass, and none of the subsequent else if
tests will even be checked. If you want this to work as intended, make sure to test age >= 80
first, so the next test only separates the groups below 80, e.g.:
if (age >= 80)
std::cout << "You are too old to drive\n";
else if (age < 18)
std::cout << "You have to be 18 to drive.\n";
else // Don't need a final if check; the previous two checks ensure if you get here, the age is between 18 and 79 inclusive
std::cout << "You can drive.\n";
CodePudding user response:
It won't ever reach the age >= 80
since a value that large would always meet the requirement of age >= 18
and the else
tells it to only choose one option.
You could check the over 80 condition first to make sure it gets found.
if (age >= 80) // 80 and above should not drive
std::cout << "You are too old to drive\n";
else if (age >= 18)
std::cout << "You can drive.\n";
else if (age < 18)
std::cout << "You have to be 18 to drive.\n";
Or you could just add a condition to the first if statement so it won't apply to over 80.
if (age >= 18 && age < 80)
std::cout << "You can drive.\n";
else if (age < 18)
std::cout << "You have to be 18 to drive.\n";
else if (age >= 80) // 80 and above should not drive
std::cout << "You are too old to drive\n";
CodePudding user response:
If age >= 18
is false, then age < 18
is true.
So, no matter what age
is, the third if
will never be reached.
CodePudding user response:
If your input age is already compared with the first if statement, it will not go through the rest of the if-statements. So if your age > 18, if-statement will not check if it's >= 80 later at line 17.
So you can either do another if statement inside the first if-statement or add more conditions in the first if-statement.
if (age >= 18 && age < 80){
std::cout << "You can drive.\n";
}
Or, you can do something like this:
if (age >= 18){
if(age >= 80){
std::cout << "You are too old to drive. \n";
}
else{
std::cout << "You can drive.\n";
}
}
And you can remove the third if-statement, because it will never be executed.