If...Else Statement

if...else Statement
The if...else statement is used to execute one block of code if a
condition is TRUE and another block if the condition is FALSE. It is one of
the most fundamental decision control structures in programming, giving your
program the power to choose between two alternatives.
What is if...else Statement?
The if...else statement is a decision control structure that allows a program to make a choice between two alternatives based on a condition.
If the condition is TRUE, the if block executes.
Otherwise, the else block executes. This ensures that
one of the two blocks is always executed, no matter what.
Real-Life Analogy
An if...else statement is like standing at a fork in the road. If the signboard says "Yes", you go left. If it says "No", you go right. You will always take one of the two paths — never both, never neither.
Key Features of if...else Statement
The if...else statement has several important features that make it essential for writing effective conditional code.
Evaluates a Condition
Evaluates a condition or expression that returns either TRUE or FALSE.
Executes One Block if TRUE
When the condition is TRUE, the statements inside the if
block are executed.
Executes Another Block if FALSE
When the condition is FALSE, the statements inside the else
block are executed instead.
Ensures One Block is Executed
Unlike a simple if, the if...else guarantees that exactly one of the two blocks will always execute.
Controls the Flow of Execution
Provides two-way branching, allowing the program to take different actions for different situations.
Makes Programs Dynamic and Intelligent
Enables programs to adapt and respond intelligently to varying input and data conditions.
Syntax (General Form)
The general syntax of the if...else statement is similar across most programming languages, with slight variations in punctuation.
if (condition) {
// Statements when condition is TRUE
}
else {
// Statements when condition is FALSE
}
{ } even for a single
statement for better readability and to avoid bugs.
Flowchart Representation
The flowchart of an if...else statement uses a diamond (decision) symbol to check the condition, then branches into two paths — one for TRUE and one for FALSE.
Start
↓
Is Condition TRUE?
├── Yes → Execute if Block (Statements)
└── No → Execute else Block (Statements)
↓
Stop
How if...else Statement Works?
The if...else statement works in four clear steps:
Condition is Evaluated
The condition inside the if statement is evaluated first.
If TRUE — Execute if Block
If the condition is TRUE (Yes), the statements inside the if
block are executed.
If FALSE — Execute else Block
If the condition is FALSE (No), the statements inside the
else block are executed.
Continue with Next Statement
After executing either block, the program continues with the next statement after the if...else structure.
Example — Check Voting Eligibility
A classic beginner example of if...else is checking whether a person is eligible to vote.
Logic
If age >= 18, print "Eligible to Vote"
Else print "Not Eligible"
Flow Summary
Input age → Check age >= 18 ?
Yes → Eligible to Vote
No → Not Eligible
If the user enters 15 → "Not Eligible to Vote".
Code Examples in Different Languages
Let's implement the "Check Voting Eligibility" program using the if...else statement in three popular programming languages.
Example in C
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age >= 18) {
printf("Eligible to Vote");
} else {
printf("Not Eligible to Vote");
}
return 0;
}
Example in Java
import java.util.Scanner;
public class IfElseExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = sc.nextInt();
if (age >= 18) {
System.out.println("Eligible to Vote");
} else {
System.out.println("Not Eligible to Vote");
}
}
}
Example in Python
age = int(input("Enter your age: "))
if age >= 18:
print("Eligible to Vote")
else:
print("Not Eligible to Vote")
If you enter 14 → Output: "Not Eligible to Vote"
Condition Results
The if...else statement always executes exactly one of the two blocks based on the result of the condition.
| Condition Result | Meaning | Action Taken |
|---|---|---|
| TRUE (Yes) | Condition is satisfied | Execute statements inside if block |
| FALSE (No) | Condition is not satisfied | Execute statements inside else block |
Common Comparison Operators
Conditions in the if...else statement use comparison operators to evaluate values.
| Operator | Meaning | Example |
|---|---|---|
| == | Equal to | a == b |
| != | Not equal to | a != b |
| > | Greater than | a > b |
| < | Less than | a < b |
| >= | Greater than or equal to | a >= b |
| <= | Less than or equal to | a <= b |
Logical Operators with if...else
You can combine multiple conditions in an if...else statement using logical operators.
| Operator | Meaning | Example |
|---|---|---|
| && (AND) | Both conditions must be TRUE | (age >= 18 && age <= 60) |
| || (OR) | At least one must be TRUE | (marks >= 90 || attendance == 100) |
| ! (NOT) | Reverses the condition | !(isBlocked) |
Real-Life Example — Traffic Signal
A real-life example that demonstrates if...else logic is a traffic signal system.
if (light == "RED") {
printf("Stop the vehicle");
}
else if (light == "YELLOW") {
printf("Get Ready");
}
else if (light == "GREEN") {
printf("Go");
}
else {
printf("Invalid Signal");
}
More Practical Examples
Example 1: Check Positive or Negative Number
if (num >= 0) {
printf("Positive Number");
} else {
printf("Negative Number");
}
Example 2: Check Even or Odd
if (num % 2 == 0) {
printf("Even");
} else {
printf("Odd");
}
Example 3: Login Validation
if (password == "admin123") {
printf("Login Successful");
} else {
printf("Invalid Password");
}
Example 4: Pass or Fail
if marks >= 40:
print("Pass")
else:
print("Fail")
Example 5: Largest of Two Numbers
if (a > b) {
printf("A is Largest");
} else {
printf("B is Largest");
}
Advantages of if...else Statement
Advantages
- Enables two-way branching
- Always ensures a block is executed
- Simple and easy to understand
- Supports comparison and logical operators
- Foundation for advanced decision structures
- Works in all programming languages
- Ideal for pass/fail and yes/no decisions
Limitations
- Handles only two branches (use else-if for more)
- Not efficient for many discrete cases (use switch)
- Too many nested if-else reduces readability
- Can be confusing if conditions are poorly written
if vs if...else vs if-else if-else
Let's compare the three most common decision control structures.
| Aspect | if | if...else | if-else if-else |
|---|---|---|---|
| Purpose | Execute code if TRUE | Execute one of two blocks | Multiple conditions |
| Branches | One | Two | Many |
| Handles FALSE? | No | Yes | Yes |
| Best Use | Simple condition check | Two-way decisions | Multi-way decisions |
Tips for Using if...else Statement
Best Practices
- Write clear and simple conditions.
- Use correct comparison operators (e.g.,
==,!=). - Always handle both TRUE and FALSE cases.
- Use meaningful variable names.
- Indent code properly for readability.
- Test your program with different inputs.
- Avoid too many nested conditions — they reduce clarity.
- Use curly braces
{ }even for single statements. - Combine multiple conditions using logical operators for cleaner code.
- Convert complex if-else chains to switch-case when possible.
Common Mistakes to Avoid
Mistake 1: Using = instead of ==
- Wrong:
if (a = 5) - Correct:
if (a == 5) =assigns,==compares
Mistake 2: Missing else Block
- Program handles only TRUE case
- FALSE case is left unhandled
- Always plan for both outcomes
Mistake 3: Semicolon After if
- Wrong:
if (x > 0); - Creates empty statement
- Correct:
if (x > 0) { ... }
Mistake 4: Improper Indentation
- Makes code hard to read
- Can hide logical errors
- Use consistent formatting
Did You Know?
Interesting Fact
The if...else structure is the foundation of Artificial Intelligence, Automation, and Smart Systems. Every "choice" a machine makes — from recommending videos to detecting fraud — starts with a simple if...else decision!
Frequently Asked Questions
Q1. What is the if...else statement?
The if...else statement is a decision control structure that executes one block of code if a condition is TRUE and another block if it is FALSE.
Q2. What is the difference between if and if...else?
An if statement handles only the TRUE case. An
if...else statement handles both TRUE and FALSE cases.
Q3. Can I use multiple if...else statements?
Yes, you can use multiple if...else statements, or use else if
for multiple conditions.
Q4. Is else optional in the if...else statement?
Yes, the else block is optional. If not present, the statement
becomes a simple if.
Q5. Can I nest if...else statements?
Yes, you can nest if...else statements inside each other. This is called a nested if...else.
Q6. What is the fall-through in if...else?
Unlike switch, if...else does not have fall-through. Only one
block executes based on the condition.
Key Takeaways
- The if...else statement executes one of two blocks based on a condition.
- The if block runs when the condition is TRUE.
- The else block runs when the condition is FALSE.
- Always ensures one block is executed.
- Uses comparison and logical operators.
- Foundation for all decision-making in programs.
- Supported in every programming language.
- Essential for building intelligent, real-world applications.
Key Takeaway
The if...else statement helps the program to
choose the right path based on a condition. It is
simple, powerful, and essential for solving real-world
problems. Master this concept to build strong logical and programming
skills.
Best of Luck! Practice more examples, think logically,
code confidently, and build intelligent programs!
Flowchart = Visual Thinking → Smart Solutions → Better
Results! 🚀
Home & Online Tuition
Learn from an experienced tutor with personalized guidance.
Available Locations
Expert Home & Online Tuition
Personalized one-to-one tuition that focuses on concept building, practical learning, problem-solving skills, and excellent academic performance. Suitable for school students looking for structured, interactive, and result-oriented learning.
Subjects We Teach
Why Choose Our Tuition?
✅ Concept-Based Learning
✅ Practical Examples
✅ Weekly Tests
✅ Doubt Solving Sessions
✅ Practice Worksheets
✅ MCQ & Assignments
✅ Exam Preparation
✅ Flexible Class Timings