If Statement - C Statement

C examples for Statement:if

Introduction

The if statement will execute if the expression inside the parentheses is evaluated to true.

It can be any expression that evaluates to a number, in which case zero is false and all other numbers are true.

Demo Code

#include <stdio.h>
int main(void) {
    int x = 0;/* ww w  . j  av  a  2 s .  co m*/

    if (x < 1) {
      printf("x < 1");
    }

}

Result

To test for other conditions, the if statement can be extended by any number of else/if clauses.

Demo Code

#include <stdio.h>
int main(void) {
    int x = 0;/*www . ja va 2  s  .  c  o m*/

    if (x < 1) {
      printf("x < 1");
    }
    else if (x > 1) {
      printf("x > 1");
    }

}

Result

The if statement can have one else clause at the end, which will execute if all previous conditions are false.

Demo Code

#include <stdio.h>
int main(void) {
    int x = 0;//  w  w w . j  av  a2  s.c  om


    if (x < 1) {
      printf("x < 1");
    }
    else if (x > 1) {
      printf("x > 1");
    }
    else {
      printf("x == 1");
    }
}

Result


Related Tutorials