If-then-else statements are fundamental conditional statements in programming. They are decision-making tools that allow a program to execute different blocks of code based on whether a specific condition is true or false.
Think of it as giving your program instructions for a choice:
If this one thing is true, then do this action, else (otherwise) do this other action.
🧠 A Simple Analogy
Imagine you're getting dressed in the morning:
IF it is raining,
THEN I will take an umbrella.
ELSE I will wear sunglasses.
Your program will only choose one of those actions (take an umbrella OR wear sunglasses), never both. The decision is based entirely on the condition: "Is it raining?"
## How It's Structured in Code
While the exact syntax (the words and symbols) changes between programming languages, the logic is always the same. It's often broken down into three parts:
if(The Condition)This is the "question" or the "test." It must be something that can be evaluated as either true or false.
Example:
if (age >= 18)
then(The "True" Block)This is the code that runs only if the condition is true. (In many modern languages, the word
thenis implied and not actually typed).Example:
print("You are eligible to vote.")
else(The "False" Block)This is the optional code that runs only if the condition is false.
Example:
print("You are not eligible to vote yet.")
## Examples in Pseudocode
Pseudocode is a way of writing out code logic in plain English.
Example 1: Basic if-else
Here, we check a test score.
score = 75
if (score > 60) then
print("You passed!")
else
print("You failed.")
Result: Because 75 is greater than 60 (the condition is true), the program will print: "You passed!"
Example 2: Chaining with else if
You can also check multiple conditions in a row using else if (or elif in languages like Python). The program checks them in order and stops as soon as it finds one that is true.
temperature = 22
if (temperature > 30) then
print("It's hot outside.")
else if (temperature > 15) then
print("It's nice and warm.")
else
print("It's cold.")
Result:
Is
22 > 30? False. It skips the first block.else if... Is22 > 15? True. It runs this block.The program prints: "It's nice and warm."
It skips the final
elseblock because it already found a true condition.
## Key Points to Remember
Only One Path: In an
if-elsechain, only one block of code will ever be executed.elseis Optional: You can have anifstatement all by itself. If the condition is false, the program just skips that block and moves on.Core Building Block: This simple structure is one of the most important concepts in programming, forming the basis for complex logic and decision-making.
No comments:
Post a Comment