Conditional Statements In C

Conditional statements, including if, else if, and else, are fundamental control flow structures in C programming that allow you to execute different blocks of code based on specific conditions.

if Statement

The if statement is used to test a condition. If the condition is true, the code within the associated block is executed; otherwise, it's skipped.

Syntax:
if (condition) { // Code to execute if the condition is true }
Example:
int number = 10; if (number > 0) { printf("The number is positive.\n"); }

In this example, the if statement checks if the value of the variable number is greater than 0. If the condition is true, the printf() function is called to print the message "The number is positive." If the condition is false, the printf() function is not called and the program continues to the next statement.

else if Statement

The else if statement is used to test additional conditions when the initial if condition is false. It allows you to provide multiple alternatives.

Syntax:
if (condition1) { // Code to execute if condition1 is true } else if (condition2) { // Code to execute if condition2 is true } else { // Code to execute if none of the conditions are true }
Example:
int number = 0; if (number > 0) { printf("The number is positive.\n"); } else if (number < 0) { printf("The number is negative.\n"); } else { printf("The number is zero.\n"); }

In this example, the else if statement is used to check multiple conditions. In this case, the first condition is checked. If the condition is true, the printf() function is called to print the message "The number is positive." If the condition is false, the next condition is checked. In this case, the second condition is checked. If the condition is true, the printf() function is called to print the message "The number is negative." If the condition is false, the printf() function is not called and the program continues to the next statement.

else Statement

The else statement is used to specify a block of code to execute when none of the preceding conditions (in if and else if clauses) is true. It is optional, and there can be only one else statement associated with an if statement.

Syntax:
if (condition) { // Code to execute if the condition is true } else { // Code to execute if the condition is false }
Example:
int number = -10; if (number > 0) { printf("The number is positive.\n"); } else { printf("The number is negative.\n"); }

In this example, the else statement is used to execute a block of statements if the condition in the if statement is false. In this case, if the value of the variable number is less than or equal to 0, the printf() function is called to print the message "The number is negative."

Conclusion

Conditional statements are essential for decision-making in C programs. They allow you to control the flow of your program based on various conditions, making your code flexible and responsive to different scenarios.