C语言 if语句

来源:这里教程网 时间:2026-02-16 12:52:45 作者:

当我们只在给定条件为真时才需要执行一个语句块,那么我们使用if语句。在下一个教程中,我们将学习 C if..else,嵌套if..else和else..if

C – if语句

if语句的语法:

if正文中的语句仅在给定条件返回true时才执行。如果条件返回false,则跳过if内的语句。

if (condition){     //Block of C statements here     //These statements will only execute if the condition is true}

if语句的流程图

if语句的示例

#include <stdio.h>int main(){    int x = 20;    int y = 22;    if (x<y)    {        printf("Variable x is less than y");    }    return 0;}

输出:

Variable x is less than y

多个if语句的示例

我们可以使用多个if语句来检查多个条件。

#include <stdio.h>int main(){    int x, y;    printf("enter the value of x:");    scanf("%d", &x);    printf("enter the value of y:");    scanf("%d", &y);    if (x>y)    {    printf("x is greater than y\n");    }    if (x<y)    {    printf("x is less than y\n");    }    if (x==y)    {    printf("x is equal to y\n");    }    printf("End of Program");    return 0;}

在上面的示例中,输出取决于用户输入。

输出:

enter the value of x:20enter the value of y:20x is equal to yEnd of Program

相关推荐