C if...else statement

C Decision Making

aif statementcan be followed by an optionalelse statementThe else statement executes when the boolean expression is false.

Syntax

In C languageif...elseSyntax of statements:

if(boolean_expression)
{
   /* 如果布尔表达式为真将执行的语句 */
}
else
{
   /* 如果布尔表达式为假将执行的语句 */
}

If the boolean expression istrue, then executeifcode within the block. If the boolean expression isfalse, then executeelseCode within the block.

The C language treats anynon-zeroandnon-nullThe value is assumed to betrue, takezeroornullassumed to befalse。

Flowchart

C 中的 if...else 语句

Example

Example

#include <stdio.h> int main () { /*Local variable definition*/ int a = 100; /*Check boolean condition*/ if( a < 20 ) { /*If the condition is true, print the following statement*/ printf("a is less than 20\n" ); } else { /*If the condition is false, output the following statement*/ printf("a is greater than 20\n" ); } printf("the value of a is %d\n", a); return 0; }

When the above code is compiled and executed, it produces the following result:

a 大于 20
a 的值是 100

if...else if...else statement

aifthe statement can be followed by an optionalelse if...elsestatement, which can be used to test multiple conditions.

When using if...else if...else statements, the following points need attention:

  • 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 else if must come before else.
  • Once an else if matches successfully, the other else ifs or else will not be tested.

Syntax

In the C language,if...else if...elseSyntax of statements:

if(boolean_expression 1)
{
   /* 当布尔表达式 1 为真时执行 */
}
else if( boolean_expression 2)
{
   /* 当布尔表达式 2 为真时执行 */
}
else if( boolean_expression 3)
{
   /* 当布尔表达式 3 为真时执行 */
}
else 
{
   /* 当上面条件都不为真时执行 */
}

Example

Example

#include <stdio.h>
 
int main ()
{
   /* local variable definition */
   int a = 100;
 
   /* Check boolean condition */
   if( a == 10 )
   {
       /* If the if condition is true, output the following statement */
       printf("The value of a is 10\n" );
   }
   else if( a == 20 )
   {
       /* If the else if condition is true, output the following statement */
       printf("The value of a is 20\n" );
   }
   else if( a == 30 )
   {
       /* If the else if condition is true, output the following statement */
       printf("The value of a is 30\n" );
   }
   else
   {
       /* If none of the above conditions is true, output the following statement */
       printf("No matching value\n" );
   }
   printf("The exact value of a is %d\n", a );
 
   return 0;
}

When the above code is compiled and executed, it produces the following result:

没有匹配的值
a 的准确值是 100

C Decision Making

other extensions