Control Statements:
Control statements in C are constructs that allow you to control the flow of execution in a program. They enable you to make decisions, loop through a set of instructions, and alter the sequence of program statements based on certain conditions. In Short, Control Statements are used in decision making. These can Change or Transfer Control from one part of program to another part, that’s why called as Control Statements.
Classification of Control Statements:
1. Conditional Statements:
if Statement:
Executes a block of code if a specified condition is true.
Syntax:
if (condition) {
// Code to be executed if the condition is true
}
if-else Statement:
Executes one block of code if the condition is true and another block if the condition is false.
Syntax:
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
else-if Statement:
Allows you to check multiple conditions in a sequence.
Syntax:
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else {
// Code to be executed if none of the conditions are true
}
2. Switch Statement:
Executes different blocks of code based on the value of an expression.
Syntax:
switch (expression) {
case value1:
// Code to be executed if expression equals value1
break;
case value2:
// Code to be executed if expression equals value2
break;
// More cases as needed
default:
// Code to be executed if none of the cases match
}
3. Looping Statements:
while Loop:
Repeats a block of code as long as a specified condition is true.
Syntax:
while (condition) {
// Code to be repeated as long as the condition is true
}
do-while Loop:
Similar to a while loop, but it guarantees that the code inside the loop is executed at least once.
Syntax:
do {
// Code to be repeated as long as the condition is true
} while (condition);
for Loop:
A loop that repeats a block of code for a specified number of times.
Syntax:
for (initialization; condition; update) {
// Code to be repeated as long as the condition is true
}
4. Jump Statements:
break Statement:
Exits the innermost loop or switch statement.
continue Statement:
Skips the rest of the loop’s code and proceeds to the next iteration.
goto Statement:
Transfers control to a labeled statement.
Control statements in C are essential for writing flexible and efficient programs by allowing developers to manage the flow of execution based on different conditions and requirements.