C++ if...else Statement
A if statement An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
Syntax
In C++ if...else statement syntax:
if(boolean_expression)
{
// statement to execute if the boolean expression is true
}
else
{
// statement to execute if the boolean expression is false
}
If the Boolean expression is true, then the if block's code is executed. If the Boolean expression is false, then the else block's code.
Flowchart
Example
#include
using namespace std;
int main ()
{
// Local variable declaration
int a = 100;
// Check boolean condition
if( a < 20 )
{
// 如果条件为真,则输出下面的语句
cout << "a 小于 20" << endl;
}
else
{
// 如果条件为假,则输出下面的语句
cout << "a 大于 20" << endl;
}
cout << "a 的值是 " << a << endl;
return 0;
}
When the code above is compiled and executed, it produces the following result:
a 大于 20
a 的值是 100
if...else if...else statement
A if statement can be followed by an optional else if...else statement, which can be used to test multiple conditions.
When using the if...else if...else statement, note the following:
- An if can be followed by zero or one else, and the else must come after all else ifs.
- An if can be followed by zero or more else ifs, and the else if must come before the else.
- Once an else if matches successfully, the other else ifs or the else will not be tested.
Syntax
The if...else if...else statement syntax:
if(boolean_expression 1)
{
// Execute when boolean expression 1 is true
}
else if( boolean_expression 2)
{
// Execute when boolean expression 2 is true
}
else if( boolean_expression 3)
{
// Execute when boolean expression 3 is true
}
else
{
// execute when none of the above conditions are true
}
Example
#include
using namespace std;
int main ()
{
// Local variable declaration
int a = 100;
// Check boolean condition
if( a == 10 )
{
// If the if condition is true, output the following statement
cout << "a 的值是 10" << endl;
}
else if( a == 20 )
{
// 如果 else if 条件为真,则输出下面的语句
cout << "a 的值是 20" << endl;
}
else if( a == 30 )
{
// 如果 else if 条件为真,则输出下面的语句
cout << "a 的值是 30" << endl;
}
else
{
// 如果上面条件都不为真,则输出下面的语句
cout << "没有匹配的值" << endl;
}
cout << "a 的准确值是 " << a << endl;
return 0;
}
When the code above is compiled and executed, it produces the following result:
没有匹配的值
a 的准确值是 100
C++ Decision Making