Learn C - C If






The general form or syntax of the if statement is:

 
if(expression) 
    Statement1; 
Next_statement; 

Notice that there is no semicolon at the end of the first line.

The second line could be written directly following the first, like this:

if(expression) Statement1;

The expression in parentheses can be any expression that results in a value of true or false.

If the expression is true, Statement1 is executed, after which the program continues with Next_statement.

If the expression is false, Statement1 is skipped and execution continues immediately with Next_statement.

Because the control expression for an if statement is expected to produce a Boolean result, the compiler will arrange to convert the result of an if expression that produces a numerical result to type bool.

Here's a statement that illustrates this:

if(count) 
  printf("The value of count is not zero.\n"); 

This will only produce output if count is not 0, because a 0 value for count will result in false for the value of the if expression.

Any nonzero value for count will result in true for the expression.

The following code shows a simple example of the if statement


    #include <stdio.h> 
      //from  w  ww  .ja  v  a  2 s. c o m
    int main(void) 
    { 
      int number = 0; 
      printf("\nEnter an integer between 1 and 10: "); 
      scanf("%d",&number); 
      
      if(number > 5) 
        printf("You entered %d which is greater than 5\n", number); 
      
      if(number < 6) 
        printf("You entered %d which is less than 6\n", number); 
      return 0; 
    } 

The code above generates the following result.





if else

Syntax model for if..then can be formulated as below:

  if (conditional) { 
     // do something 
  }else{ 
     // do another job 
  } 

conditional can be obtained by logical or/and comparison operations.

The syntax of the if-else statement is as follows:

if(expression) 
  Statement1; 
else 
  Statement2; 
  
Next_statement; 

Here, you have an either-or situation. You'll always execute either Statement1 or Statement2 depending on whether expression results in the value true or false.

If expression evaluates to true, Statement1 is executed and the program continues with Next_statement.

If expression evaluates to false, Statement2 that follows the else keyword is executed, and the program continues with Next_statement.


    #include <stdio.h> 
      /*ww  w . java2 s.c  om*/
    int main(void) 
    { 
      const double PRICE = 3.50;                     // Unit price in dollars 
      int quantity = 0; 
      printf("Enter the number that you want to buy:");   
      scanf(" %d", &quantity);                            // Read the input 
      

      double total = 0.0;                                 // Total price 
      if(quantity > 10)                                   // 5% discount 
        total = quantity * PRICE * 0.95; 
      else                                                // No discount 
        total = quantity*PRICE; 
      printf("The price for %d is $%.2f\n", quantity, total); 
      return 0; 
    } 

The code above generates the following result.





Blocks of Code in if Statements

You can use a block of statements enclosed between braces {} in if statement.

You can supply several statements that are to be executed when the value of an if expression is true.

The general form for an if statement that involves statement blocks would look like this:

if(expression) 
{ 
  StatementA1; 
  StatementA2; 
  . . . 
} 
else 
{ 
  StatementB1; 
  StatementB2; 
  . . . 
} 
  
Next_statement; 

Example

Here is the sample code:


  #include <stdio.h> 
//from  w  w  w.ja  v  a 2s.c  o m
  int main() { 
     int a, b; 
     a = 5; 
     b = 8; 

     if(a>b  || a-b<a){ 
             printf("conditional-->a>b  || a-b<a \n"); 
     }else{ 
             printf("..another \n"); 
     } 
     return 0; 
  } 

The code above generates the following result.

Nested if Statements


    #include <stdio.h> 
    #include <limits.h>               // For LONG_MAX 
      //from  ww  w .jav  a 2s.  c  o m
    int main(void) 
    { 
      long test = 0L;                 // Stores the integer to be checked 
      
      printf("Enter an integer less than %ld:", LONG_MAX); 
      scanf(" %ld", &test); 
      
      // Test for odd or even by checking the remainder after dividing by 2 
      if(test % 2L == 0L) 
      { 
        printf("The number %ld is even", test); 
      
        // Now check whether half the number is also even 
        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.

Testing Characters

A char value may be expressed either as an integer or as a keyboard character between quotes, such as 'A'.

This example uses some of the new logical operators.

The program will convert any uppercase letter that is entered to lowercase:


    #include <stdio.h> 
      /*from  w  w w . j av  a2  s. c  o m*/
    int main(void) 
    { 
      char letter = 0;                          // Stores a character 
      
      printf("Enter an uppercase letter:");     // Prompt for input 
      scanf("%c", &letter);                     // Read a character 
      
      // Check whether the input is uppercase 
      if(letter >= 'A')                         // Is it A or greater? 
        if(letter <= 'Z')                       // and is it Z or lower? 
        {                                       // It is uppercase 
          letter = letter - 'A' + 'a';          // Convert from upper- to lowercase 
          printf("You entered an uppercase %c\n", letter); 
        } 
        else                                    // It is not an uppercase letter 
          printf("A capital letter.\n"); 
      return 0; 
    } 

The code above generates the following result.