if-else statement in C language

The if Statement

Relational operators are used mainly to construct the relational expressions used in if and while statements, covered in detail on Day 6, “Basic Program Control.” For now, you will learn the basics of the if statement to show how relational operators are used to make program control statements.

if (expression)
{
   statement;
}

If expression evaluates to true, statement is executed. If expression evaluates to false, statement is not executed. In either case, execution then passes to whatever code follows the if statement. You can say that execution of statement depends on the result of expression. Note that both the line if (expression) and the line statement; are considered to make up the complete if statement; they are not separate statements.

Example

#include<stdio.h>
   int main ()
   {
     if ( 5 < 10 )
     printf( "Five is now less than ten" );

   }

if else Statement in C language

1) An if statement can optionally include an else clause. The else clause is included as follows:

if (expression)
    statement1;
  else
    statement2;

If expression evaluates to true, statement1 is executed. If expression evaluates to false, control goes to the else statement, statement2, which is then executed. Both statement1 and statement2 can be compound statements or blocks.

Code Example

 #include<stdio.h>
  int main()
  {
      int number;
      printf("Enter an integer: ");
      scanf("%d", &number);
      // True if the remainder is 0
      if  (number%2 == 0)
      {
          printf("%d is an even integer.",number);
      }
      else
      {
          printf("%d is an odd integer.",number);
      }
      return 0;
  }

Output

//enter 5
5 is an odd integer.
//enter 6
6 is an even integer.

Nested if..else

This is a nested if. If the first expression, expression1, is true, statement1 is executed before the program continues with the next_statement. If the first expression is not true, the second expression, expression2, is checked. If the first expression is not true, and the second is true, statement2 is executed. If both expressions are false, statement3 is executed. Only one of the three statements is executed.

if( expression1 )
      statement1;
    else if( expression2 )
      statement2;
    else
      statement3;

Nested if..else c code Example

  #include<stdio.h>
  int main()
  {
      int age;

      if( age < 18 )

          printf(“Minor”);

      else if( age < 65 )

          printf(“Adult”);

      else
          printf( “Senior Citizen”);

  }

What is the use of IF statement?

An if statement is a programming conditional statement that, if proved true, performs a function or displays information. Below is a general example of an if statement, not specific to any particular programming language.