Decision making (if, if-else, switch)
Decision Making: A Structured Approach to Solving Problems A decision is a crucial step in problem-solving that involves evaluating conditions and executing...
Decision Making: A Structured Approach to Solving Problems A decision is a crucial step in problem-solving that involves evaluating conditions and executing...
A decision is a crucial step in problem-solving that involves evaluating conditions and executing different paths based on the outcome. This allows us to navigate through various possibilities and reach the desired solution.
The if-else statement is a foundational building block for decision making. It allows us to check specific conditions and execute different blocks of code based on the result.
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Example:
python
name = input("Enter your name: ")
if name == "John":
print("Welcome, John!")
else:
print("Hello, guest!")
This code will take the user's name, compare it to "John," and print a welcoming message if it matches. Otherwise, it will print a generic greeting.
The switch statement is a more flexible and efficient way to handle different conditions compared to the if-else block. It evaluates a variable against a series of cases and executes specific code blocks for each case.
switch (condition) {
case condition1:
// Code for condition1
break
case condition2:
// Code for condition2
break
// Additional cases...
default:
// Default case
}
Example:
python
shirt_size = input("Enter your shirt size: ")
switch shirt_size:
case "S":
print("Your shirt is small.")
break
case "M":
print("Your shirt is medium.")
break
case "L":
print("Your shirt is large.")
break
default:
print("Invalid shirt size.")
This code uses a switch statement to determine the user's shirt size and prints the corresponding message