C if statement

What is C if statement

To conditionally execute statements, you can use the if or the if...else statement.

Syntax for if statement

The general form of the if statement is


if(expr) {// w  w w.j av a  2s  .  c  o  m
    s1 ;
    s2 ;
    ....
}

expr is a Boolean expression that returns true (nonzero) or false (zero).

Example for if statement

if statement with a comparison operator. The code compares two int values.


#include <stdio.h>
//from  ww w . j av  a2 s  .c o  m
main(){
  int i = 3,j = 5;
  if(i < j){
     printf("i < j \n");
  }   
}

The code above generates the following result.


If a compound statement is used, it must be enclosed in opening and closing braces.


#include<stdio.h>
/*from   w  ww .j  a  va2s  .co m*/
main()
{
   int i=5, j =1;
   
    if (i > j){
        i = i + 1;
        printf("%d",i);
    }   
    else
        j = j +1;
}

The code above generates the following result.

Syntax for nested if Statements


if(expression1){ 
  StatementA;                //from  w w  w  .j a v  a 2  s . co  m
  if(expression2){
    StatementB;              
  }else {
    StatementC;              
  }  
} 
else  {
  StatementD;                
}
Statement E;                 

Example for nested if Statements

Use nested if statement to check long value.


#include <stdio.h>
#include <limits.h>
//from w  ww.  java 2  s  . c o  m
int main(void)
{
  long test = 0L;              


  if( test % 2L == 0L) {
    printf("The number %ld is even", test);

    if ( (test/2L) % 2L == 0L)
    {
      printf("\nHalf of %ld is also even", test);
      printf("\nThat's interesting isn't it?\n");
    }
  }
  else
    printf("The number %ld is odd\n", test);
  return 0;
}

The code above generates the following result.





















Home »
  C Language »
    Language Basics »




C Language Basics
Data Types
Operator
Statement
Array