Control Flow: Conditional Statements in C
By Swann
- Published on
Sharing
Introduction
Control flow is a pivotal concept in C programming, allowing developers to define the order in which the program's statements are executed. Conditional statements, like if
, else if
, and switch
, enable the program to make decisions, executing specific blocks of code based on particular conditions.
The if
Statement
Syntax
if (condition) {
// code to be executed if condition is true
}
Example
if (age >= 18) {
printf("Eligible to vote.\n");
}
The if-else
Statement
Syntax
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Example
if (age >= 18) {
printf("Eligible to vote.\n");
} else {
printf("Not eligible to vote.\n");
}
The else if
Statement
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 both conditions are false
}
Example
if (grade == 'A') {
printf("Excellent!\n");
} else if (grade == 'B') {
printf("Good!\n");
} else {
printf("Try Harder!\n");
}
The switch
Statement
Syntax
switch (expression) {
case constant1:
// code to be executed if expression is equal to constant1;
break;
case constant2:
// code to be executed if expression is equal to constant2;
break;
default:
// code to be executed if expression doesn't match any constants;
}
Example
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
default:
printf("Invalid day\n");
}
Conclusion
Conditional statements in C play a vital role in controlling the flow of program execution, enabling logical decision-making processes within your code. By mastering if
, else if
, and switch
statements, developers ensure that their programs can respond and adapt to various conditions and inputs, leading to dynamic and interactive applications.