Decision control structure in C
A decision control structure in C is used to perform different actions based on different conditions. These structures allow the program to make decisions and execute specific blocks of code based on the evaluation of boolean expressions. The primary decision control structures in C include:
Understand the decision control structure in C
- if Statement
- if-else Statement
- nested if Statement
- if-else-if Ladder
- switch Statement
if Statement in C
The if
statement evaluates a condition and executes a block of code only if the condition is true.
if (condition) {
// Code to be executed if condition is true
}
Example:
int x = 10;
if (x > 0) {
printf("x is positive");
}
if-else Statement
The if-else
statement evaluates a condition and executes one block of code if the condition is true and another block of code if the condition is false.
if (condition) {
// Code to be executed if condition is true
} else {
// Code to be executed if condition is false
}
Example:
int x = -10;
if (x > 0) {
printf("x is positive");
} else {
printf("x is negative or zero");
}
nested if Statement in C
A nested if
statement is an if
statement placed inside another if
or else
block. This allows multiple levels of condition checking.
if (condition1) {
if (condition2) {
// Code to be executed if both condition1 and condition2 are true
}
}
Example:
int x = 10, y = 20;
if (x > 0) {
if (y > 0) {
printf("Both x and y are positive");
}
}
if-else-if Ladder
The if-else-if
ladder is used to test multiple conditions. It executes the block of code corresponding to the first true condition.
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else if (condition3) {
// Code to be executed if condition3 is true
} else {
// Code to be executed if all conditions are false
}
Example:
int x = 0;
if (x > 0) {
printf("x is positive");
} else if (x < 0) {
printf("x is negative");
} else {
printf("x is zero");
}
switch Statement in C
The switch
statement allows a variable to be tested for equality against a list of values, each with its own block of code.
switch (expression) {
case constant1:
// Code to be executed if expression equals constant1
break;
case constant2:
// Code to be executed if expression equals constant2
break;
// More cases
default:
// Code to be executed if expression doesn't match any case
}
Example
int day = 3;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
default:
printf("Invalid day");
}
These decision control structures are fundamental to controlling the flow of a C program based on dynamic conditions.