C if else statement

Syntax for if-else statement

The general format for an if-else statement is


if (condition){//from   w  w w .j  a va 2 s.  co  m
   simple or compound statement  
}else{
   simple or compound statement. 
}

Example for if-else statement


#include <stdio.h>
/*from w  w  w  .ja v a 2  s .  com*/
main(){
  int i = 5;
  if(i > 0){
     printf(" i > 0. \n");
  }else{
     printf(" i < 0. \n");
  }
}

The code above generates the following result.

Example - if statement with two else statements

if statement with two else statements


#include <stdio.h>
#include <stdlib.h>
 /*from  ww w. ja  v a2  s .c  o  m*/
int main()
{
    char num[2];
    int number;
 
    printf("Enter a number from 0 to 9:");
    gets(num);
    number=atoi(num);
 
    if(number<5)
    {
        printf("That number is less than 5!\n");
    }
    else if(number==5)
    {
        printf("You typed in 5!\n");
    }
    else
    {
        printf("That number is more than 5!\n");
    }
 
    return(0);
}

The code above generates the following result.





















Home »
  C Language »
    Language Basics »




C Language Basics
Data Types
Operator
Statement
Array