C++ Conditional Statements
Many programs need to make decisions. In this lesson, you will learn how C++ uses conditional statements like if, if...else, else-if, nested if, and switch to execute different blocks of code based on conditions.
Introduction
In the previous lesson, you learned how to accept input from users and display output. However, useful programs must do more than simply receive and display data. They must also make decisions.
For example, if a student scores 40 or more, display Pass. If a password is correct, allow login. If an account has enough balance, process a withdrawal. In each situation, the program must choose an action based on a condition.
C++ provides conditional statements that allow a program to evaluate conditions and choose which code should execute.
What is a Conditional Statement?
A conditional statement allows a program to execute different blocks of code depending on the result of a condition. A condition is evaluated as true or false.
Condition
↓
True or False?
↓
Execute the appropriate codeConditional statements help a program make decisions and control which statements execute.
Why Do We Need Conditional Statements?
Without Conditional Statements
- Programs would follow the same path every time.
- Programs could not choose actions based on data.
- User input could not influence program behavior.
- Applications could not properly validate many situations.
With Conditional Statements
- Make logical decisions.
- Control program execution.
- Validate user input.
- Respond differently to different situations.
- Execute only the code required for a particular condition.
Real-World Analogy
Imagine approaching a traffic signal. Your action depends on the color of the light. A red light means stop, a yellow light means prepare or wait according to the situation, and a green light means go.
A C++ program works similarly. It evaluates a condition and chooses an action based on the result.
Types of Conditional Statements
C++ provides several decision-making structures. Each one is useful for a different type of problem.
if
Executes a block only when a condition is true.
if...else
Chooses between two alternative blocks.
else-if Ladder
Checks multiple conditions in sequence.
Nested if
Places one conditional statement inside another.
switch
Selects a matching branch based on the value of an expression.
1. The if Statement
The if statement executes its controlled statement only when the condition evaluates to true. If the condition evaluates to false, that statement is skipped.
if (condition)
{
// Executes when the condition is true
}#include <iostream>
int main()
{
int marks = 75;
if (marks >= 40)
{
std::cout << "Pass";
}
return 0;
}Explanation
- marks stores the value 75.
- marks >= 40 compares 75 with 40.
- The comparison evaluates to true.
- Because the condition is true, the body of the if statement executes.
- The program displays Pass.
Pass2. The if...else Statement
The if...else statement chooses between two alternatives. The if branch executes when the condition is true. Otherwise, the else branch executes.
if (condition)
{
// Executes when true
}
else
{
// Executes when false
}#include <iostream>
int main()
{
int age = 16;
if (age >= 18)
{
std::cout << "Eligible to Vote";
}
else
{
std::cout << "Not Eligible to Vote";
}
return 0;
}Explanation
- age stores the value 16.
- age >= 18 compares 16 with 18.
- The condition evaluates to false.
- The if branch is skipped.
- The else branch executes.
Not Eligible to Vote3. The else-if Ladder
An else-if ladder is useful when several conditions must be tested in order. Conditions are evaluated from top to bottom. The first branch whose condition is true executes, and the remaining branches in that ladder are skipped.
if (condition1)
{
// First branch
}
else if (condition2)
{
// Second branch
}
else if (condition3)
{
// Third branch
}
else
{
// Fallback branch
}#include <iostream>
int main()
{
int marks = 82;
if (marks >= 90)
{
std::cout << "Grade A+";
}
else if (marks >= 75)
{
std::cout << "Grade A";
}
else if (marks >= 60)
{
std::cout << "Grade B";
}
else
{
std::cout << "Grade C";
}
return 0;
}How the Conditions are Checked
- marks >= 90 evaluates to false because 82 is less than 90.
- marks >= 75 evaluates to true because 82 is greater than or equal to 75.
- The Grade A branch executes.
- The remaining branches in the ladder are skipped.
Grade AIn a range-based else-if ladder, test higher or more specific conditions before lower or broader conditions. Otherwise, an earlier condition may match before the intended branch is reached.
4. Nested if
A conditional statement placed inside another conditional statement is commonly called a nested if. The inner condition is reached only when program execution enters the outer branch that contains it.
#include <iostream>
int main()
{
int age = 25;
bool citizen = true;
if (age >= 18)
{
if (citizen)
{
std::cout << "Eligible to Vote";
}
}
return 0;
}Explanation
- The outer condition checks whether age is at least 18.
- Since age is 25, the outer condition is true.
- The program enters the outer block.
- The inner condition checks the value of citizen.
- Because citizen is true, the program displays Eligible to Vote.
Eligible to VoteSimple conditions can often be combined with logical operators. For example, if (age >= 18 && citizen) may be clearer than deeply nested conditions when both conditions belong to one decision.
5. The switch Statement
The switch statement selects a branch based on the value of an expression. It is useful when one expression must be compared against several discrete constant case values.
switch (expression)
{
case value1:
// Statements
break;
case value2:
// Statements
break;
default:
// Statements
}#include <iostream>
int main()
{
int day = 3;
switch (day)
{
case 1:
std::cout << "Monday";
break;
case 2:
std::cout << "Tuesday";
break;
case 3:
std::cout << "Wednesday";
break;
default:
std::cout << "Invalid Day";
}
return 0;
}Explanation
- The switch expression evaluates to 3.
- Execution begins at the matching case 3 label.
- The program displays Wednesday.
- The break statement exits the switch.
- The default branch is not executed.
WednesdayWithout a terminating statement such as break, execution can continue into the statements of the following case. This behavior is called fall-through and can be intentional or accidental.
int value = 1;
switch (value)
{
case 1:
std::cout << "One ";
case 2:
std::cout << "Two";
break;
}
// Output:
// One TwoTraditional switch statements are designed for discrete values rather than arbitrary range conditions such as marks >= 75. Use if...else when decisions depend on ranges or complex boolean expressions.
Program Execution Flow
Comparison of Conditional Statements
| Statement | Purpose | Best Used For |
|---|---|---|
| if | Executes code when a condition is true | A single optional action |
| if...else | Chooses between two alternatives | True or false decisions |
| else-if Ladder | Tests several conditions in order | Ranges and multiple logical conditions |
| Nested if | Places one decision inside another | Dependent or hierarchical conditions |
| switch | Selects a branch from discrete case values | Menus, commands, states, and fixed choices |
Real-World Applications
ATM
Verify PINs, check available balance, and decide whether a transaction can continue.
Banking
Evaluate account status, transaction rules, and eligibility conditions.
E-Commerce
Validate coupons, apply discounts, check stock, and select delivery options.
Student Management
Determine grades, pass or fail status, and eligibility.
Games
Control levels, player states, health conditions, menus, and game actions.
Common Beginner Mistakes
= performs assignment, while == compares values for equality. Confusing them can change data and produce unexpected conditions.
Without braces, only one statement belongs to the controlled body. Adding another indented statement later does not automatically make it part of the condition.
Without break or another terminating control statement, execution may continue into the next case.
A broad condition placed too early in an else-if ladder can prevent more specific later conditions from being reached.
Too many nested levels make code difficult to read, test, and maintain.
Direct equality checks with floating-point calculations can be unreliable because many decimal values cannot be represented exactly.
// Assignment
age = 18;
// Equality comparison
if (age == 18)
{
std::cout << "Age is 18";
}// Only the first statement is controlled
if (age >= 18)
std::cout << "Adult";
std::cout << "Welcome";Using braces consistently makes the controlled block explicit and reduces mistakes when statements are added or moved later.
Best Practices
- Write conditions that clearly express their purpose.
- Use braces consistently, even when a branch currently contains one statement.
- Use if...else for ranges and complex boolean conditions.
- Use switch for clear selection among discrete constant choices.
- Order else-if conditions carefully.
- Avoid unnecessary deep nesting.
- Combine related conditions with logical operators when that improves readability.
- Use meaningful boolean names such as isEligible or hasPermission.
- Handle unexpected values with an appropriate fallback branch when necessary.
- Keep each conditional branch focused and easy to understand.
Frequently Asked Questions
What is a conditional statement?
A conditional statement controls execution based on a condition or selection value.
What does an if statement do?
It executes its controlled statement when its condition evaluates to true.
What is the difference between if and if...else?
if provides an optional path, while if...else chooses between two alternative paths.
How does an else-if ladder work?
Conditions are checked in order. The first true branch executes, and the remaining branches in that ladder are skipped.
What is a nested if?
It is a conditional statement placed inside another conditional branch.
When should I use switch?
Use switch when one expression must select among several discrete case values.
Why is break commonly used in switch?
break exits the switch and prevents execution from continuing into later cases.
Is fall-through always an error?
No. Fall-through can be intentional, but accidental fall-through is a common source of bugs.
Can switch replace every else-if ladder?
No. if...else is better for ranges, inequalities, and complex boolean expressions.
Why does condition order matter?
In an else-if ladder, the first true branch is selected. An earlier broad condition can prevent later specific conditions from being reached.
Key Takeaways
- Conditional statements allow programs to make decisions.
- Conditions determine which execution path is selected.
- if executes a branch when its condition is true.
- if...else chooses between two alternatives.
- An else-if ladder tests conditions in order.
- The first true branch in an else-if ladder is selected.
- Nested if statements represent dependent decisions.
- switch selects among discrete case values.
- break commonly prevents unwanted switch fall-through.
- Condition order affects program behavior.
- Braces improve clarity and reduce maintenance mistakes.
- Choosing the correct conditional structure makes code easier to understand.
Summary
Conditional statements are fundamental control structures in C++. They allow programs to evaluate conditions and select different execution paths. The if statement handles a single optional action, if...else chooses between two alternatives, else-if ladders handle multiple ordered conditions, nested conditions represent dependent decisions, and switch selects among discrete values.
These structures are used throughout real applications for validation, authentication, grading, transactions, menus, game logic, and many other decisions. Understanding how conditions are evaluated, how branches are selected, and how to avoid common mistakes provides the foundation needed before moving on to repeated execution with loops.