Conditional statements play a crucial role in programming as they allow us to make decisions and control the flow of our programs. In the C programming language, conditional statements enable us to execute certain blocks of code based on specified conditions. In this article, I will explore the conditional statements available in C, their syntax, and provide suitable examples to demonstrate their usage.
- If Statement:
The "if" statement is the most basic conditional statement in C. It allows us to execute a block of code if a specified condition is true.The syntax for the "if" statement is as follows:
Cif (condition) {
// code to execute if the condition is true
}
Example:
Cint num = 10;
if (num > 0) {
printf("The number is positive.\n");
}
- If-else Statement:
The "if-else" statement expands on the "if" statement by providing an alternative block of code to execute when the condition is false.The syntax for the "if-else" statement is as follows:
Cif (condition) {
// code to execute if the condition is true
} else {
// code to execute if the condition is false
}
Example:
Cint num = 10;
if (num % 2 == 0) {
printf("The number is even.\n");
} else {
printf("The number is odd.\n");
}
- Nested If Statements:
C allows nesting of conditional statements within each other to handle more complex decision-making scenarios. This enables us to check multiple conditions within different blocks of code. The syntax for nested "if" statements is as follows:
Cif (condition1) {
// code to execute if condition1 is true
if (condition2) {
// code to execute if condition2 is true
}
}
Example:
Cint num = 10;
if (num > 0) {
printf("The number is positive.\n");
if (num % 2 == 0) {
printf("And the number is even.\n");
} else {
printf("But the number is odd.\n");
}
}
- Switch Statement:
The "switch" statement allows for multi-way branching based on different values of a variable or expression. It provides a concise way to handle multiple cases within a single control structure. The syntax for the "switch" statement is as follows:
Cswitch (expression) {
case value1:
// code to execute if expression matches value1
break;
case value2:
// code to execute if expression matches value2
break;
// additional cases...
default:
// code to execute if no case matches the expression
}
Example:
Cint dayOfWeek = 1;
switch (dayOfWeek) {
case 1:
printf("\nMonday"); break;
case 2:
printf("\nTuesday"); break;
// additional cases...
default:
printf("\nInvalid day");}
Conclusion: