Decision-making is one of the most important concepts in programming. The computer needs to make choices based on conditions, and that’s where if-else statements come in. They help control the flow of the program by executing certain blocks of code only when conditions are true.
Understanding Flow Control
Flow control refers to the order in which instructions are executed in a program. By default, instructions run sequentially from top to bottom. Decision-making statements, like if-else, allow the flow to branch based on conditions.
Without flow control: every line executes in order.
With flow control: some code executes only if certain conditions are true, skipping others.
The if-else Statement
The if-else statement is an extension of the if statement. It allows the program to execute one block of code if the condition is true and another block if the condition is false.
Syntax
Explanation:
condition: A Boolean expression that evaluates totrueorfalse.If the condition is true, the first block executes.
If the condition is false, the block after
elseexecutes.
Example 1: Simple If-Else
Output 1 (age = 20):
Output 2 (age = 15):
The program chooses one path based on the age input.
Flowchart of If-Else Statement
The flowchart shows that only one block executes, depending on the condition.
Example 2: Checking Even or Odd
Real-life analogy: Deciding whether a day is weekday or weekend.
Nested If Statements
Sometimes, you need to check multiple conditions within another condition. This is where nested if statements are used.
Syntax
You can nest multiple levels of
ifstatements, but avoid too many levels to keep code readable.
Example 1: Nested If
Output 1 (marks = 95):
Output 2 (marks = 60):
Output 3 (marks = 40):
Nested
ifallows checking more than one condition in a structured way.
Example 2: Nested If with Multiple Grades
Better approach: Use
else ifladder (more on this later).Nested
ifhelps in step-by-step decision-making.
Real-Life Example 1: Traffic Signal Decision
Nested
ifcan handle multiple conditions step by step.
Real-Life Example 2: Bank ATM PIN Check
Nested
ifhelps check multiple security layers.