Control structures are fundamental components of programming languages that dictate the flow of execution of statements. In C language, control structures can be categorized into selective control structures and iterative control statements. This article provides an overview of different types of control structures in C, including if statements, switch statements, the conditional ternary operator, and for loops.
Selective Control Structures
Selective control structures allow the program to choose different paths of execution based on certain conditions.
If Statements
The ‘if’ statement allows the execution of a block of code based on whether a specified condition evaluates to true.
Syntax:
if (condition) {
// Code to be executed if condition is true
}
You can also use else
and else if
to create more complex decision trees.
Example:
if (a > b) {
printf("a is greater than b");
} else if (a < b) {
printf("b is greater than a");
} else {
printf("a is equal to b");
}
Switch Statement
The switch
statement provides an efficient way of handling multiple conditions compared to using multiple if
statements. It evaluates an expression and executes code corresponding to the matching case.
Syntax:
switch (expression) {
case constant1:
// code to be executed if expression == constant1
break;
case constant2:
// code to be executed if expression == constant2
break;
default:
// code to be executed if no cases match
}
Example:
switch (choice) {
case 1:
printf("Option 1 selected");
break;
case 2:
printf("Option 2 selected");
break;
default:
printf("Invalid option");
}
Conditional Ternary Operator
The conditional (ternary) operator is a shorthand method of writing an if-else
statement. It is often used for simple conditions.
Syntax:
condition ? expression_if_true : expression_if_false;
Example:
int max = (a > b) ? a : b; // assigns the greater of a or b to max
Iterative Control Statements
Iterative control statements allow executing a block of code multiple times until a specified condition is met.
For Loop
The for
loop is used for executing a block of code a specific number of times. It consists of three parts: initialization, condition, and increment/decrement.
Syntax:
for (initialization; condition; increment) {
// Code to be executed
}
Example:
for (int i = 0; i < 10; i++) {
printf("%d ", i);
}
In this example, the loop prints numbers from 0 to 9.
Conclusion
Understanding control structures is vital for effective programming in C. They help in making decisions and controlling the flow of a program, allowing for more versatile and complex applications.