Skip to main content

Conditional Statements in C

Conditional statements in C

Conditional statements are used in C to execute different blocks of code depending on whether a certain condition is true or false. This allows you to create programs that can make decisions and adapt their behavior based on input or other factors.

Below are some examples of when you might use conditional statements in C:

  • Checking user input: You can check if the user has entered a valid value, and prompt them to try again if they haven't.

  • Validating data: You can check if the data being read from a file or database is valid, and handle the error if it isn't.

  • Choosing an algorithm: You can select the appropriate algorithm to use based on the size or type of input data.

  • Handling different cases: You can execute different code depending on the value of an enumeration or other variable with a limited number of possible values.

Types of conditional statements in C

There are several types of conditional statements that you can use to control the flow of your program:

if statement

The if statement is used to execute a block of code if a certain condition is true.

The syntax of if statement is:

if (condition) {
// code to execute if condition is true
}

if-else statement

The if-else statement is used to execute one block of code if a certain condition is true, and another block of code if the condition is false.

The syntax of if-else statement is:

if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}

if-else if-else statement

The if-else if-else statement is used to execute one block of code if a certain condition is true, another block of code if a different condition is true, and a third block of code if all conditions are false.

The syntax of if-else if-else statement is:

if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition1 is false and condition2 is true
} else {
// code to execute if condition1 and condition2 are both false
}

switch statement

The switch statement is used to execute a block of code based on the value of a variable.

The syntax of switch statement is:

switch (variable) {
case value1:
// code to execute if variable is equal to value1
break;
case value2:
// code to execute if variable is equal to value2
break;
...
default:
// code to execute if variable is not equal to any of the listed values
break;
}
break statement

The break statement is used to exit the switch block once a matching case has been found. If you omit the break statement, the code will continue to be executed for all remaining cases.