If/Else Statement:
The if/else statement is a decision-making statement in C that allows the program to execute different blocks of code based on a condition. The basic syntax of an if/else statement is:
if (condition) { // code to be executed if condition is true } else { // code to be executed if condition is false }
Here, condition
is an expression that evaluates to either true
or false
. If the condition is true, the code inside the first block (enclosed in curly braces) is executed; otherwise, the code inside the second block is executed.
Nested If/Else:
Nested if/else statements are if/else statements that are inside another if/else statement. This allows for multiple conditions to be checked and different code to be executed based on the outcome of multiple conditions.
Here’s an example of a nested if/else statement:
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 is a control statement in C that allows for multiple conditions to be checked and different code to be executed based on the value of an expression. The basic syntax of a switch statement is:
switch (expression) { case constant1: // code to be executed if expression is equal to constant1 break; case constant2: // code to be executed if expression is equal to constant2 break; ... default: // code to be executed if expression is not equal to any of the constants }
Here, expression
is an expression that is compared against a series of constants (case values). If a match is found, the code associated with that constant is executed. The break
statement is used to exit the switch statement after the code for a matching constant has been executed. The default
section is optional and is executed if no matching constant is found.