Home >Backend Development >C++ >How to use if else in c language
The if statement performs conditional judgment. When the condition is true, code block 1 is executed, and when it is false, it is skipped. The else statement provides alternative code, and code block 2 is executed when the condition is false. 1. Conditional expression: code block 1 is executed when evaluated to true, and code block 2 is executed when false. 2. Code block: Contains the statement to be executed, enclosed in curly brackets bracketed. 3. Nested if else: Process multiple conditions, find the first if statement that satisfies the condition and execute it, otherwise execute the else statement.
Usage of if else in C language
if
statement in C language Used to perform conditional judgments. When the condition is true, it will execute the given block of code; when the condition is false, it will skip the block of code. The else
statement can be used with the if
statement to provide an alternative block of code if a condition is false.
Syntax
<code class="c">if (condition) { // 代码块 1 } else { // 代码块 2 }</code>
Usage
condition The
part is the expression to be evaluated. It can be any Boolean expression, such as a comparison, logical operator, or function call. If the expression evaluates to true (non-zero), code block 1 is executed. If the expression evaluates to false (zero), code block 2 is executed. For example:
<code class="c">int age = 18; if (age >= 18) { printf("可以投票\n"); } else { printf("不能投票\n"); }</code>
In this example:
age >= 18
is a conditional expression. age
is greater than or equal to 18, code block 1 is executed and "can vote" is printed. age
is less than 18, execute code block 2 and print "Cannot vote". Nested if else statements
if else
Statements can be nested to handle multiple conditions.
For example:
<code class="c">int score = 90; if (score >= 90) { printf("A\n"); } else if (score >= 80) { printf("B\n"); } else if (score >= 70) { printf("C\n"); } else { printf("D\n"); }</code>
In this example:
if
statement checks whether the score is greater than or equal to 90. If it is, it prints "A". if
statement is false, the second level if else
statement will be executed. It checks if the score is greater than or equal to 80. If so, it prints "B". if
statement that satisfies the condition is found. If the condition of no if
statement is true, the else
statement is executed. The above is the detailed content of How to use if else in c language. For more information, please follow other related articles on the PHP Chinese website!