Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

C – Control Statements

C Programming Control Statement
The statements those who control the order of execution of a program are known as control statements.

The if-else control statement

The if-else statement is used to choose & execute anyone action among two.

Syntax

 if(condition)
 {
         // group of programming statements
 }
 else
 {
         // group of programming statements
 }

Braces in the if-else and other control statements are optional if we used only one statement for every action, as shown below:

 if(condition)
         single_statement;
 else
         single_statement;

The syntax without braces can be used only when there is a need to execute a single statement for every action.

The syntax with braces can be used to execute a single statement as well as a group of statements for every action.

It is good to use braces to avoid confusions because curly braces help to distinguish statements as a separate & a single group from other.

If the condition present inside the parentheses is true, if-block is executed. After execution of if-block, program control skips else-block and jumps directly to the statements after else-block.

If the condition inside the parenthesis is false, else-block is executed by skipping if-block.

Flow chart
C Programming Language if-else flowchart

Working

C Programming if-else Working

Example No 1

 #include<stdio.h>
 int main()
 {
     int i;
     i=5;
     if(i<10)
     {
         printf("Inside if block");
     }
     else
     {
         printf("Inside else block");
     }
     printf("After if-else block");
     return 0;
 }

Output

Inside if block
After if-else block

In the above program value of i is less than 10. Therefore condition becomes true, and program control enters into if-block and executes the statement inside it.

Example no 2

 #include<stdio.h>
 int main()
 {
     int i;
     i=15;
     if(i<10)
     {
         printf("Inside if block");
     }
     else
     {
         printf("Inside else block");
     }
     printf("After if-else block");
     return 0;
 }

Output

Inside else block
After if-else block

In the above program value of i is greater than 10. Therefore condition becomes false, and program control enters directly into else-block by skipping if-block and executes the statement inside else-block.

 

 

Leave a reply