IF Statement


If Statement

 

The if statement is used to execute instructions based on a condition in the program. To write the if statement, the shirt is written in parentheses after the keyword if. After this, the instructions are written between the middle brackets.

Now if the condition is true then the related instructions are executed or else the statements that are written after that are executed.

 

Its general syntax is as follows –

 

if(condition) {
  Statement 1;
  Statement 2;
 }
 Statement x;

 

This can be represented by the following diagram -

 

if statement

 

Carefully read and understand the following conclusive statements -

 

Examples

if (age < 18) {

 printf (“You are young”);

  }

if (age < 18) && (gender == ‘F’) {

  printf (“You are adult”);

  printf (“and Female”);

}

if ((sal > 5000) || (comm < 500)) {

 Bonus = 1000;

}

Read Also: scanf and printf

 

If …else statement

 

This is an extended form of the IF statement. Under this, the instructions are executed when the condition is true.

On the contrary, even if the condition is false, other desired instructions are executed.

 

Its general syntax and diagram are as follows –

 

if (test expression) {
True block or set of statements
}
else {
False-block or set of statements
} statement-x;

 

is statement

 

For example, see and understand the following statements -

 

if (x==10) {

 printf (“X is 10”);

} else {

 printf (“X is not 10”);

}

if (amount < 5000) {

 printf (“Pay in cash”);

} else {

 printf (“Pay through Cash”);

}

 

Nested if … else statement

 

Conditions are also used in the form of chains in the program. To write the conditions in the form of a series, nested statements are used.

 

It can be used in the following three different formats -

 

if (expression 1) {

  if (expression 2) 

     Statement 1;

 else

    Statement 2;

} else {

    Statement;

}

if (expression 1) {

     Statement;

} else {

     if (expression 2) 

      Statement 1;

   else

    Statement 2;

     .......

 }

if (expression 1) {

  if (expression 2) 

     Statement 1;

 else

    Statement 2;

} else {

    if (expression 3) 

     Statement 3;

   else

    Statement 4;

 }

 

Else if statement

 

When a condition is to be checked more than once, we use the else if statement. Its general syntax is as follows -

 

if (condition 1)
    statement 1;
else if (condition 2)
    statement 1;
....
else if (condition-n)
   statement-n;
else
   statement-x;

 

Read Also: Interesting Facts of World