C Program - Unit 2 - Decision Making and Branching
C Program - Unit 2 - Decision Making and Branching
Example:
int num = 10;
if (num > 0) {
printf("The number is positive.\n");
} else {
printf("The number is non-positive.\n");
}
Nested if-else statements:
You can also have multiple levels of if-else statements within each other, creating
nested decision-making structures.
if (condition1) {
// Code to execute if condition1 is true
if (condition2) {
// Code to execute if both condition1 and condition2 are true
} else {
// Code to execute if condition1 is true but condition2 is false
}
} else {
// Code to execute if condition1 is false
}
else-if ladder:
The else-if ladder is used when you have multiple conditions to
check, and you want to choose one of several possible blocks of
code to execute.
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 all conditions are false
}
int score = 85;
loop: if (num == 1) {
if (i <= 5) { goto error;
printf("%d ", i); }
i++;
goto loop; printf("This won't be executed.\n");
}
error:
printf("Loop finished!\n"); printf("Error occurred!\n");
return 0; return 0;
} }
Switch Statement
The switch statement in C is a control statement used
to make multi-way decisions based on the value of an
expression.