Conditional statements in C allow you to make decisions in your program by checking if certain conditions are true or false. These conditions control the flow of execution in your program. C provides several types of conditional statements:
The if statement is used to check if a condition is true. If the condition is true, a block of code is executed.
if (condition) { // Block of code executed if condition is true }
#includeint main() { int num = 10; if (num > 5) { printf("The number is greater than 5.\n"); } return 0; }
The if-else statement allows you to execute one block of code if the condition is true, and another block if the condition is false.
if (condition) { // Block of code executed if condition is true } else { // Block of code executed if condition is false }
#includeint main() { int num = 3; if (num > 5) { printf("The number is greater than 5.\n"); } else { printf("The number is less than or equal to 5.\n"); } return 0; }
The else-if ladder allows you to check multiple conditions. If the first condition is false, the next condition is checked, and so on. If no conditions are true, the final else block is executed.
if (condition1) { // Block of code executed if condition1 is true } else if (condition2) { // Block of code executed if condition2 is true } else { // Block of code executed if none of the above conditions are true }
#includeint main() { int num = 10; if (num > 15) { printf("The number is greater than 15.\n"); } else if (num > 5) { printf("The number is greater than 5 but less than or equal to 15.\n"); } else { printf("The number is less than or equal to 5.\n"); } return 0; }
The switch statement is an alternative to using multiple if-else statements when checking a variable against many possible values. It evaluates an expression and matches it with cases to execute the corresponding block of code.
switch (expression) { case value1: // Block of code executed if expression == value1 break; case value2: // Block of code executed if expression == value2 break; default: // Block of code executed if no case matches }
#includeint main() { int day = 4; switch (day) { case 1: printf("Monday\n"); break; case 2: printf("Tuesday\n"); break; case 3: printf("Wednesday\n"); break; case 4: printf("Thursday\n"); break; case 5: printf("Friday\n"); break; default: printf("Invalid day\n"); } return 0; }
break
in switch
statements, leading to "fall-through" behavior.if-else
statements when a switch
statement would be more appropriate.{}
when there are multiple statements inside an if
, else
, or else-if
block.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!