Coming Soon

This lesson is currently being developed

Introduction to if statements

Introduction to conditional execution with if statements.

Fundamental Data Types
Chapter
Beginner
Difficulty
45min
Estimated Time

What to Expect

Comprehensive explanations with practical examples

Interactive coding exercises to practice concepts

Knowledge quiz to test your understanding

Step-by-step guidance for beginners

Development Status

In Progress

Content is being carefully crafted to provide the best learning experience

Preview

Early Preview Content

This content is still being developed and may change before publication.

4.10 — Introduction to if statements

In this lesson, you'll learn about if statements, which allow your programs to make decisions and execute different code paths based on conditions.

What are if statements?

If statements allow your program to make decisions by executing different blocks of code depending on whether a condition is true or false. They're fundamental to creating programs that can respond to different situations.

Think of if statements like a fork in the road: depending on the condition (like weather), you take one path or another (bring umbrella or don't bring umbrella).

Basic if statement syntax

The simplest form of an if statement:

if (condition)
{
    // Code to execute if condition is true
}
#include <iostream>

int main()
{
    int temperature = 32;
    
    std::cout << "Current temperature: " << temperature << "°F\n";
    
    // Basic if statement
    if (temperature <= 32)
    {
        std::cout << "Water will freeze!\n";
    }
    
    std::cout << "Program continues...\n";
    
    return 0;
}

Output:

Current temperature: 32°F
Water will freeze!
Program continues...

if-else statements

You can specify what happens when the condition is false using else:

#include <iostream>

int main()
{
    int age = 17;
    
    std::cout << "Age: " << age << std::endl;
    
    if (age >= 18)
    {
        std::cout << "You can vote!\n";
    }
    else
    {
        std::cout << "You cannot vote yet.\n";
        std::cout << "Wait " << (18 - age) << " more year(s).\n";
    }
    
    return 0;
}

Output:

Age: 17
You cannot vote yet.
Wait 1 more year(s).

Multiple conditions with else if

For multiple conditions, use else if:

#include <iostream>

int main()
{
    int score = 85;
    
    std::cout << "Test score: " << score << std::endl;
    
    if (score >= 90)
    {
        std::cout << "Grade: A - Excellent!\n";
    }
    else if (score >= 80)
    {
        std::cout << "Grade: B - Good job!\n";
    }
    else if (score >= 70)
    {
        std::cout << "Grade: C - Satisfactory\n";
    }
    else if (score >= 60)
    {
        std::cout << "Grade: D - Needs improvement\n";
    }
    else
    {
        std::cout << "Grade: F - Failed\n";
    }
    
    return 0;
}

Output:

Test score: 85
Grade: B - Good job!

Different types of conditions

Comparison operators

#include <iostream>

int main()
{
    int x = 10;
    int y = 20;
    
    std::cout << "x = " << x << ", y = " << y << std::endl;
    
    // Equality
    if (x == y)
    {
        std::cout << "x equals y\n";
    }
    
    // Inequality
    if (x != y)
    {
        std::cout << "x does not equal y\n";
    }
    
    // Less than
    if (x < y)
    {
        std::cout << "x is less than y\n";
    }
    
    // Greater than or equal
    if (y >= x)
    {
        std::cout << "y is greater than or equal to x\n";
    }
    
    return 0;
}

Output:

x = 10, y = 20
x does not equal y
x is less than y
y is greater than or equal to x

Boolean conditions

#include <iostream>

int main()
{
    bool isLoggedIn = true;
    bool hasPermission = false;
    bool isAdmin = true;
    
    // Direct boolean variable
    if (isLoggedIn)
    {
        std::cout << "Welcome back!\n";
    }
    
    // Negated boolean
    if (!hasPermission)
    {
        std::cout << "Access denied - insufficient permissions\n";
    }
    
    // Multiple boolean conditions
    if (isLoggedIn && isAdmin)
    {
        std::cout << "Admin panel available\n";
    }
    
    if (hasPermission || isAdmin)
    {
        std::cout << "You have some level of access\n";
    }
    
    return 0;
}

Output:

Welcome back!
Access denied - insufficient permissions
Admin panel available
You have some level of access

Complex conditions with logical operators

AND operator (&&)

#include <iostream>

int main()
{
    int age = 25;
    bool hasLicense = true;
    bool hasInsurance = true;
    
    std::cout << "Driver eligibility check:\n";
    std::cout << "Age: " << age << std::endl;
    std::cout << "Has license: " << (hasLicense ? "Yes" : "No") << std::endl;
    std::cout << "Has insurance: " << (hasInsurance ? "Yes" : "No") << std::endl;
    
    // All conditions must be true
    if (age >= 18 && hasLicense && hasInsurance)
    {
        std::cout << "✓ Eligible to drive\n";
    }
    else
    {
        std::cout << "✗ Not eligible to drive\n";
        
        // Show what's missing
        if (age < 18)
            std::cout << "  - Too young (need to be 18+)\n";
        if (!hasLicense)
            std::cout << "  - Need a driver's license\n";
        if (!hasInsurance)
            std::cout << "  - Need insurance\n";
    }
    
    return 0;
}

Output:

Driver eligibility check:
Age: 25
Has license: Yes
Has insurance: Yes
✓ Eligible to drive

OR operator (||)

#include <iostream>

int main()
{
    int temperature = 95;  // Fahrenheit
    bool isWeekend = true;
    bool isHoliday = false;
    
    std::cout << "Pool day decision:\n";
    std::cout << "Temperature: " << temperature << "°F\n";
    std::cout << "Weekend: " << (isWeekend ? "Yes" : "No") << std::endl;
    std::cout << "Holiday: " << (isHoliday ? "Yes" : "No") << std::endl;
    
    // Any of these conditions makes it a good pool day
    if (temperature > 80 || isWeekend || isHoliday)
    {
        std::cout << "✓ Great day for the pool!\n";
        
        // Show reasons
        if (temperature > 80)
            std::cout << "  - Weather is warm\n";
        if (isWeekend)
            std::cout << "  - It's the weekend\n";
        if (isHoliday)
            std::cout << "  - It's a holiday\n";
    }
    else
    {
        std::cout << "✗ Not ideal for pool time\n";
    }
    
    return 0;
}

Output:

Pool day decision:
Temperature: 95°F
Weekend: Yes
Holiday: No
✓ Great day for the pool!
  - Weather is warm
  - It's the weekend

Nested if statements

You can put if statements inside other if statements:

#include <iostream>

int main()
{
    bool isRaining = false;
    int temperature = 75;
    bool hasUmbrella = true;
    
    std::cout << "Should I go outside?\n";
    std::cout << "Temperature: " << temperature << "°F\n";
    std::cout << "Raining: " << (isRaining ? "Yes" : "No") << std::endl;
    std::cout << "Have umbrella: " << (hasUmbrella ? "Yes" : "No") << std::endl;
    
    if (temperature > 60 && temperature < 90)  // Good temperature
    {
        std::cout << "Temperature is comfortable\n";
        
        if (isRaining)  // Nested condition
        {
            std::cout << "But it's raining...\n";
            
            if (hasUmbrella)  // Double nested!
            {
                std::cout << "✓ Go outside with umbrella\n";
            }
            else
            {
                std::cout << "✗ Stay inside, no umbrella\n";
            }
        }
        else
        {
            std::cout << "✓ Perfect weather - go outside!\n";
        }
    }
    else
    {
        std::cout << "✗ Temperature is uncomfortable - stay inside\n";
    }
    
    return 0;
}

Output:

Should I go outside?
Temperature: 75°F
Raining: No
Have umbrella: Yes
Temperature is comfortable
✓ Perfect weather - go outside!

Practical applications

User input validation

#include <iostream>

int main()
{
    int userAge;
    
    std::cout << "Enter your age: ";
    std::cin >> userAge;
    
    // Validate input
    if (userAge < 0)
    {
        std::cout << "Error: Age cannot be negative!\n";
    }
    else if (userAge > 150)
    {
        std::cout << "Error: Age seems unrealistic!\n";
    }
    else
    {
        std::cout << "Age " << userAge << " is valid.\n";
        
        // Categorize by age
        if (userAge < 13)
        {
            std::cout << "Category: Child\n";
        }
        else if (userAge < 20)
        {
            std::cout << "Category: Teenager\n";
        }
        else if (userAge < 65)
        {
            std::cout << "Category: Adult\n";
        }
        else
        {
            std::cout << "Category: Senior\n";
        }
    }
    
    return 0;
}

Simple calculator with conditionals

#include <iostream>

int main()
{
    double num1, num2;
    char operation;
    
    std::cout << "Simple Calculator\n";
    std::cout << "Enter first number: ";
    std::cin >> num1;
    
    std::cout << "Enter operation (+, -, *, /): ";
    std::cin >> operation;
    
    std::cout << "Enter second number: ";
    std::cin >> num2;
    
    double result = 0;
    bool validOperation = true;
    
    if (operation == '+')
    {
        result = num1 + num2;
    }
    else if (operation == '-')
    {
        result = num1 - num2;
    }
    else if (operation == '*')
    {
        result = num1 * num2;
    }
    else if (operation == '/')
    {
        if (num2 != 0)  // Check for division by zero
        {
            result = num1 / num2;
        }
        else
        {
            std::cout << "Error: Division by zero!\n";
            validOperation = false;
        }
    }
    else
    {
        std::cout << "Error: Invalid operation!\n";
        validOperation = false;
    }
    
    if (validOperation)
    {
        std::cout << num1 << " " << operation << " " << num2 << " = " << result << std::endl;
    }
    
    return 0;
}

Game logic example

#include <iostream>

int main()
{
    int playerHealth = 75;
    int playerLevel = 5;
    bool hasKey = true;
    bool bossDefeated = false;
    
    std::cout << "=== Adventure Game Status ===\n";
    std::cout << "Health: " << playerHealth << "/100\n";
    std::cout << "Level: " << playerLevel << std::endl;
    std::cout << "Has key: " << (hasKey ? "Yes" : "No") << std::endl;
    std::cout << "Boss defeated: " << (bossDefeated ? "Yes" : "No") << std::endl;
    
    // Game state decisions
    if (playerHealth <= 0)
    {
        std::cout << "\n💀 GAME OVER - You have died!\n";
    }
    else if (playerHealth < 25)
    {
        std::cout << "\n⚠️  WARNING: Low health! Find a health potion!\n";
    }
    
    // Level progression
    if (playerLevel >= 10)
    {
        std::cout << "🎉 You've reached maximum level!\n";
    }
    else if (playerLevel >= 5)
    {
        std::cout << "🌟 You're at intermediate level\n";
    }
    
    // Area access
    if (hasKey && playerLevel >= 3)
    {
        std::cout << "🗝️  You can access the secret chamber\n";
    }
    else if (!hasKey)
    {
        std::cout << "🚪 You need a key to progress\n";
    }
    else
    {
        std::cout << "📈 Level up to access more areas\n";
    }
    
    // Win condition
    if (bossDefeated && playerLevel >= 8 && playerHealth > 0)
    {
        std::cout << "🏆 VICTORY! You've completed the game!\n";
    }
    else if (!bossDefeated && playerLevel >= 8)
    {
        std::cout << "⚔️  You're ready to face the final boss!\n";
    }
    
    return 0;
}

Output:

=== Adventure Game Status ===
Health: 75/100
Level: 5
Has key: Yes
Boss defeated: No

🌟 You're at intermediate level
🗝️  You can access the secret chamber
⚔️  You're ready to face the final boss!

Common mistakes and best practices

✅ Use braces for clarity

// Good: Always use braces, even for single statements
if (temperature > 90)
{
    std::cout << "It's hot!\n";
}

// Avoid: Single line without braces (error-prone)
// if (temperature > 90)
//     std::cout << "It's hot!\n";

✅ Use meaningful conditions

// Good: Clear and readable
bool isEligibleToVote = (age >= 18 && isCitizen);
if (isEligibleToVote)
{
    std::cout << "You can vote!\n";
}

// Less clear: Complex condition inline
// if (age >= 18 && isCitizen && hasRegistered && !isConvicted)

✅ Avoid deep nesting

#include <iostream>

int main()
{
    int age = 25;
    bool hasLicense = true;
    bool hasJob = true;
    
    // Good: Early return/exit pattern
    if (age < 18)
    {
        std::cout << "Too young for car loan\n";
        return 0;
    }
    
    if (!hasLicense)
    {
        std::cout << "Need a driver's license\n";
        return 0;
    }
    
    if (!hasJob)
    {
        std::cout << "Need employment for loan\n";
        return 0;
    }
    
    std::cout << "Eligible for car loan!\n";
    return 0;
}

❌ Common mistakes to avoid

// Mistake: Assignment instead of comparison
int x = 5;
// if (x = 10)  // This assigns 10 to x, doesn't compare!
if (x == 10)    // Correct: comparison

// Mistake: Semicolon after if
// if (condition);  // Empty statement!
// {
//     // This block always executes
// }

// Mistake: Confusing operator precedence
bool a = true, b = false, c = true;
// if (a || b && c)  // This is (a || (b && c)), not ((a || b) && c)
if ((a || b) && c)  // Use parentheses for clarity

Summary

If statements are essential for program decision-making:

Basic syntax:

  • if (condition) { ... } - Execute if true
  • if (condition) { ... } else { ... } - Execute one of two paths
  • if (condition1) { ... } else if (condition2) { ... } else { ... } - Multiple conditions

Conditions can be:

  • Comparison operations (==, !=, <, >, <=, >=)
  • Boolean variables or expressions
  • Combined with logical operators (&&, ||, !)

Best practices:

  • Always use braces {} for code blocks
  • Use meaningful variable names for complex conditions
  • Avoid deep nesting when possible
  • Watch out for assignment vs. comparison (= vs. ==)
  • Use parentheses to clarify complex logical expressions

If statements allow your programs to respond intelligently to different inputs and situations, making them interactive and useful.

Quiz

  1. What's the difference between if and if-else statements?
  2. When would you use else if?
  3. What's the difference between = and == in conditions?
  4. How do && and || operators work in conditions?
  5. Why should you always use braces {} even for single statements?

Practice exercises

Try these if statement exercises:

  1. Write a program that determines if a year is a leap year using if statements
  2. Create a number guessing game that gives hints (too high/too low) using if-else
  3. Build a simple grade calculator that converts numerical scores to letter grades
  4. Write a program that determines the largest of three numbers using nested if statements

Continue Learning

Explore other available lessons while this one is being prepared.

View Course

Explore More Courses

Discover other available courses while this lesson is being prepared.

Browse Courses

Lesson Discussion

Share your thoughts and questions

💬

No comments yet. Be the first to share your thoughts!

Sign in to join the discussion