Reading:
In programming, selection constructs allow for decision-making within code, enabling programs to execute different blocks of instructions based on specific conditions. These constructs provide branching mechanisms that guide the flow of execution in various directions.
One-way selection constructs, exemplified by the “if” statement, execute a block of code if a condition evaluates to true. For example:
x = 10
if x > 5:
print(“x is greater than 5”)
Two-way selection constructs expand on this by providing an alternative block of code to execute if the condition evaluates to false. The “if-else” statement is a common example:
if x > 5:
print(“x is greater than 5”)
else:
print(“x is less than or equal to 5”)
if x > 5:
print(“x is greater than 5”)
elif x == 5:
print(“x is equal to 5”)
else:
print(“x is less than 5”)
switch (x) {
case 1:
printf(“x is 1”);
break;
case 2:
printf(“x is 2”);
break;
default:
printf(“x is neither 1 nor 2”);
}