Conditional Statements Explained - if, else, else if & switch
Some operators are still left, but before learning them, it’s important to understand conditional statements, because many operators depend on them.
What are Conditional Statements?
Conditional statements help in decision making in code.
Real-life examples:
- If it is raining → we stay inside
- If the weather is good → we go outside
- If age ≥ 18 → you can vote
In programming, we use conditions like this:
if Statement
This is the most basic conditional statement.
Example:
If the condition is true, the code runs. If false, nothing happens.
if...else Statement
Used when you want an alternative action.
Example:
If the condition is true, the first block runs. Otherwise, the else block runs.
else if Statement
Used when you have multiple conditions.
Example (Grading System):
This is useful when you want to check several conditions one by one.
switch Statement
Used when you have multiple fixed values.
Example (Days of Week):
Important Points
- Always use
breakin a switch statement. - Without it, all cases after the matched case will execute.
- Use
defaultto handle invalid inputs.
When to Use What?
| Situation | |
| Single condition | if |
| Two conditions | if...else |
| Multiple conditions | else if |
| Fixed values/options | switch |
Interview Tip
- Conditional statements are used for decision making.
- Use
switchwhen you have many fixed values like menu options or days.