Control Statements in C with Examples
Control Statements in C:
In C programming language, Control Statements are used to execute/transfer the control from one part of the program to another depending on a condition. These statements are also called conditional statements.
Types of Control Statements in C:
In C Programming, There are mainly two types of Control Statements:
1. if-else statement
2. switch statement
if-else statement:
if-else statement is used to execute a statement block or a single statement depending on the value of a condition. It has the following syntax:
if(condition) { - - - - - - - - - <true block> - - - - - - - - - } else { - - - - - - - - - <false block> - - - - - - - - - }
Nested if-else Statement:
An if statement may have another if statement in the < true block > and < false block >. It is the nesting of an if statement within another if statement and the nesting of an if statement with an else statement. This compound statement is called Nested if-else Statement.
if(condition 1) if(condition 2) { - - - - - - - - - <true block 1> - - - - - - - - - } else { - - - - - - - - - <false block 1> - - - - - - - - - } else if(condition 3) { - - - - - - - - - <true block 2> - - - - - - - - - } else { - - - - - - - - - <false block 2> - - - - - - - - - }
Switch statement:
switch statementt is used to execute a block of statements depending on the value of a variable or an expression. It has the following syntax:
switch (<expression>) { case <label 1>: { - - - - - - - - - - <statement 1> - - - - - - - - - - break; } case <label 2>: { - - - - - - - - - - <statement 2> - - - - - - - - - - break; } case <label 3>: { - - - - - - - - - - <statement 3> - - - - - - - - - - break; } case <label n>: { - - - - - - - - - - <statement n> - - - - - - - - - - break; } default: { - - - - - - - - - - <default statement> - - - - - - - - - - break; } }