Zone Of Makos

Menu icon

Conditional Statements in C

Introduction

In C programming, conditional statements allow you to make decisions and execute different blocks of code based on certain conditions. These statements enable you to create dynamic and flexible programs that can respond to different scenarios. Let's explore the various types of conditional statements in C.

If Statement

The if statement is the most basic conditional statement in C. It allows you to execute a block of code if a certain condition is true. Here's the general syntax:

if (condition) {
  // code to be executed if the condition is true
}

If-Else Statement

The if-else statement extends the if statement by providing an alternative block of code to execute if the condition is false. It allows you to handle both true and false scenarios. Here's the syntax:

if (condition) {
  // code to be executed if the condition is true
} else {
  // code to be executed if the condition is false
}

Nested If-Else Statement

You can nest conditional statements inside each other to handle more complex conditions. This is known as a nested if-else statement. It allows you to check multiple conditions and execute different blocks of code accordingly. Here's an example:

if (condition1) {
  // code to be executed if condition1 is true
  
  if (condition2) {
    // code to be executed if condition2 is true
  } else {
    // code to be executed if condition2 is false
  }
} else {
  // code to be executed if condition1 is false
}

Switch Statement

The switch statement allows you to select one of many code blocks to execute based on the value of a variable. It provides an alternative to multiple if-else statements when comparing a variable against multiple values. Here's the general syntax:

switch (variable) {
  case value1:
    // code to be executed if variable equals value1
    break;
  case value2:
    // code to be executed if variable equals value2
    break;
  // more cases...
  default:
    // code to be executed if variable doesn't match any case
}

Conclusion

Conditional statements are powerful tools in C programming that allow you to control the flow of execution based on specific conditions. By using if , if-else , switch , and nested versions of these statements, you can create dynamic and responsive programs. Make sure to choose the appropriate conditional statement based on the logic you want to implement. We'll again see switch-case statements in next lesson. Happy coding!