Conditionals
Conditionals are a fundamental part of programming that allow you to make decisions in your code based on certain conditions. In C programming, there are several types of conditional statements that you can use to control the flow of your program:
-
if statement: The
ifstatement is used to execute a block of code if a specified condition is true. For example:int x = 10; if (x > 5) { printf("x is greater than 5\n"); }In this example, the code inside the
ifblock will be executed because the conditionx > 5is true. -
if-else statement: The
if-elsestatement is used to execute one block of code if a condition is true and another block of code if the condition is false. For example:int x = 10; if (x > 5) { printf("x is greater than 5\n"); } else { printf("x is not greater than 5\n"); }In this example, the first block of code will be executed because the condition
x > 5is true. Ifxwere less than or equal to 5, the second block of code would be executed instead. -
else if statement: The
else ifstatement is used to specify a new condition to test if the previous condition was false. You can have multipleelse ifstatements to check for different conditions. For example:int x = 10; if (x > 15) { printf("x is greater than 15\n"); } else if (x > 5) { printf("x is greater than 5 but less than or equal to 15\n"); } else { printf("x is less than or equal to 5\n"); }In this example, the second block of code will be executed because the condition
x > 5is true, while the first conditionx > 15is false. -
switch statement: The
switchstatement is used to perform different actions based on different conditions. It is often used as an alternative to multipleif-elsestatements when you have a variable that can take on multiple values. For example:int day = 3; 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; case 6: printf("Saturday\n"); break; case 7: printf("Sunday\n"); break; default: printf("Invalid day\n"); }In this example, the code will print “Wednesday” because the value of
dayis 3, which matches the case for Wednesday. Thebreakstatements are used to exit the switch block after a case is executed, preventing the execution of subsequent cases. Thedefaultcase is executed if none of the specified cases match the value ofday.
Understanding and using conditionals effectively is crucial for writing functional and efficient C programs. They allow you to control the flow of your program and make decisions based on user input, variable values, or other conditions.