Home  >  Article  >  Backend Development  >  How to use if statement in c++

How to use if statement in c++

下次还敢
下次还敢Original
2024-05-09 03:39:17668browse

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.

How to use if statement in c++

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).
  • If the condition is true, the code block that follows is executed.
  • If the condition is false, execute the else if code block (if it exists).
  • If all conditions are false, execute the 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

  • Conditional expression must return a Boolean value. The
  • else if and else blocks are optional.
  • Multiple if statements can be nested to create complex conditional logic.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn