📜  C / C++ if else语句和示例

📅  最后修改于: 2021-05-25 21:27:39             🧑  作者: Mango

C / C++中的“决策制定”有助于编写决策驱动的语句并根据某些条件执行特定的代码集。

仅if语句就告诉我们,如果条件为true,它将执行语句块,如果条件为false,则不会。但是,如果条件为假,我们想做其他事情怎么办。这是C / C++ else语句。当条件为false时,可以将else语句与if语句一起使用以执行代码块。

句法:

if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}

if-else语句的工作

  1. 控制属于if块。
  2. 流程跳至“条件”。
  3. 条件已测试。
    1. 如果Condition得出的结果为true,请转到步骤4。
    2. 如果Condition得出false,请转到步骤5。
  4. 执行if块或if内的主体。
  5. else块或else内部的主体将被执行。
  6. 流程退出if-else块。

流程图if-else:

范例1:

C
// C program to illustrate If statement
  
#include 
  
int main()
{
    int i = 20;
  
    // Check if i is 10
    if (i == 10)
        printf("i is 10");
  
    // Since is not 10
    // Then execute the else statement
    else
        printf("i is 20");
  
    printf("Outside if-else block");
  
    return 0;
}


C++
// C++ program to illustrate if-else statement
  
#include 
using namespace std;
  
int main()
{
    int i = 20;
  
    // Check if i is 10
    if (i == 10)
        cout << "i is 10";
  
    // Since is not 10
    // Then execute the else statement
    else
        cout << "i is 20\n";
  
    cout << "Outside if-else block";
  
    return 0;
}


C
// C program to illustrate If statement
  
#include 
  
int main()
{
    int i = 25;
  
    if (i > 15)
        printf("i is greater than 15");
    else
        printf("i is smaller than 15");
  
    return 0;
}


C++
// C++ program to illustrate if-else statement
  
#include 
using namespace std;
  
int main()
{
    int i = 25;
  
    if (i > 15)
        cout << "i is greater than 15";
    else
        cout << "i is smaller than 15";
  
    return 0;
}


输出:
i is 20
Outside if-else block

空运行示例1:

1. Program starts.
2. i is initialized to 20.
3. if-condition is checked. i == 10, yields false.
4. flow enters the else block.
  4.a) "i is 20" is printed
5. "Outside if-else block" is printed.

范例2:

C

// C program to illustrate If statement
  
#include 
  
int main()
{
    int i = 25;
  
    if (i > 15)
        printf("i is greater than 15");
    else
        printf("i is smaller than 15");
  
    return 0;
}

C++

// C++ program to illustrate if-else statement
  
#include 
using namespace std;
  
int main()
{
    int i = 25;
  
    if (i > 15)
        cout << "i is greater than 15";
    else
        cout << "i is smaller than 15";
  
    return 0;
}
输出:
i is greater than 15

相关文章:

  1. C / C++中的决策
  2. C / C++ if语句和示例
  3. C / C++,如果带有示例,则为梯形图
  4. C / C++中的Switch语句
  5. C / C++中的Break语句
  6. 在C / C++中继续执行语句
  7. C / C++中的goto语句
  8. C / C++中的带有示例的return语句
  9. 计划使用嵌套的其他方式为学生分配成绩
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。