The if statement in C is used to execute different blocks of code based on conditions. The syntax is: if (condition) {...} else if (condition) {...} else {...}. A conditional expression returns a Boolean value that executes the immediately following block of code when true, and executes the else if or else block (if one exists) when false. If all conditions are false, the else block (if present) is executed.
if statement in C
The if statement in C is used to create conditional statements that allow programmers to Different code blocks are executed for different results of each condition.
Syntax
<code class="cpp">if (condition) { // 如果条件为真,执行的代码块 } else if (condition) { // 如果条件为假,但另一个条件为真,执行的代码块 } else { // 如果所有条件都为假,执行的代码块 }</code>
How it works
if
The statement is followed by a conditional expression , an expression that returns a Boolean value (true or false). else if
code block (if it exists). else
code block (if it exists). Example
<code class="cpp">int number = 10; if (number > 0) { std::cout << "Number is positive" << std::endl; } else if (number < 0) { std::cout << "Number is negative" << std::endl; } else { std::cout << "Number is zero" << std::endl; }</code>
In this case, the output will be "Number is positive" because the value of variable number
is 10, greater than 0.
Note
else if
and else
blocks are optional. The above is the detailed content of How to use if statement in c++. For more information, please follow other related articles on the PHP Chinese website!