Coming Soon

This lesson is currently being developed

If statements and blocks

Introduction to conditional execution with if statements.

Control Flow
Chapter
Beginner
Difficulty
40min
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.

8.2 — If statements and blocks

In this lesson, you'll learn how to use if statements to make decisions in your programs, understand when and how to use blocks, and master the fundamentals of conditional programming.

The if statement

An if statement allows you to execute code conditionally - meaning the code runs only if a certain condition is true. This is the foundation of decision-making in programming.

if (condition)
    statement;

If the condition is true, the statement executes. If false, the statement is skipped.

Basic if statement example

#include <iostream>

int main()
{
    int x = 5;
    
    if (x > 3)
        std::cout << "x is greater than 3\n";
    
    std::cout << "Program finished\n";
    
    return 0;
}

Output:

x is greater than 3
Program finished

Since x (5) is greater than 3, the condition is true, so the message prints.

When the condition is false

#include <iostream>

int main()
{
    int x = 2;
    
    if (x > 3)
        std::cout << "x is greater than 3\n";
    
    std::cout << "Program finished\n";
    
    return 0;
}

Output:

Program finished

Since x (2) is not greater than 3, the condition is false, so the message doesn't print.

The else statement

Use else to specify what happens when the if condition is false:

#include <iostream>

int main()
{
    int temperature = 18;
    
    if (temperature >= 20)
        std::cout << "It's warm today!\n";
    else
        std::cout << "It's cool today.\n";
    
    return 0;
}

Output:

It's cool today.

The program checks if temperature >= 20. Since 18 is not >= 20, it executes the else statement.

Chaining with else if

Use else if to check multiple conditions in sequence:

#include <iostream>

int main()
{
    int score = 85;
    
    if (score >= 90)
        std::cout << "Grade: A\n";
    else if (score >= 80)
        std::cout << "Grade: B\n";
    else if (score >= 70)
        std::cout << "Grade: C\n";
    else if (score >= 60)
        std::cout << "Grade: D\n";
    else
        std::cout << "Grade: F\n";
    
    return 0;
}

Output:

Grade: B

The program checks conditions from top to bottom and executes the first true condition. Since 85 >= 80 (but not >= 90), it prints "Grade: B" and skips the remaining conditions.

Understanding blocks (compound statements)

A block or compound statement is a group of statements enclosed in curly braces {}. Blocks allow you to execute multiple statements as a unit.

Single statement (no braces needed)

#include <iostream>

int main()
{
    bool isRaining = true;
    
    if (isRaining)
        std::cout << "Take an umbrella!\n";  // Single statement
    
    return 0;
}

Multiple statements (braces required)

#include <iostream>

int main()
{
    bool isRaining = true;
    
    if (isRaining)
    {
        std::cout << "It's raining today.\n";      // Multiple statements
        std::cout << "Take an umbrella!\n";       // require a block
        std::cout << "Drive carefully.\n";
    }
    
    return 0;
}

Output:

It's raining today.
Take an umbrella!
Drive carefully.

Why always use blocks?

Even for single statements, it's good practice to always use braces:

Dangerous (without braces)

#include <iostream>

int main()
{
    int x = 5;
    
    if (x > 3)
        std::cout << "x is greater than 3\n";
        std::cout << "This always prints!\n";  // NOT part of if!
    
    return 0;
}

Output:

x is greater than 3
This always prints!

The second cout is not part of the if statement - it always executes because it's not indented correctly and there are no braces to group it.

Safe (with braces)

#include <iostream>

int main()
{
    int x = 5;
    
    if (x > 3)
    {
        std::cout << "x is greater than 3\n";
        std::cout << "This is also part of the if\n";
    }
    
    return 0;
}

Output:

x is greater than 3
This is also part of the if

Now both statements are clearly part of the if block.

Practical examples

Example 1: User input validation

#include <iostream>

int main()
{
    int age;
    
    std::cout << "Enter your age: ";
    std::cin >> age;
    
    if (age >= 0 && age <= 150)
    {
        std::cout << "You are " << age << " years old.\n";
        
        if (age >= 18)
        {
            std::cout << "You are an adult.\n";
        }
        else
        {
            std::cout << "You are a minor.\n";
        }
    }
    else
    {
        std::cout << "Invalid age entered!\n";
    }
    
    return 0;
}

Sample Output:

Enter your age: 25
You are 25 years old.
You are an adult.

Example 2: Simple calculator

#include <iostream>

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

Sample Output:

Enter first number: 12.5
Enter operation (+, -, *, /): *
Enter second number: 4
12.5 * 4 = 50

Example 3: Password strength checker

#include <iostream>
#include <string>

int main()
{
    std::string password;
    
    std::cout << "Enter a password: ";
    std::cin >> password;
    
    int length = password.length();
    
    if (length >= 12)
    {
        std::cout << "Password strength: Very Strong\n";
        std::cout << "Excellent password length!\n";
    }
    else if (length >= 8)
    {
        std::cout << "Password strength: Strong\n";
        std::cout << "Good password length.\n";
    }
    else if (length >= 6)
    {
        std::cout << "Password strength: Moderate\n";
        std::cout << "Consider using a longer password.\n";
    }
    else
    {
        std::cout << "Password strength: Weak\n";
        std::cout << "Password is too short. Use at least 6 characters.\n";
    }
    
    return 0;
}

Sample Output:

Enter a password: MySecurePassword123
Password strength: Very Strong
Excellent password length!

Nested if statements

You can place if statements inside other if statements:

#include <iostream>

int main()
{
    int temperature = 25;
    bool isSunny = true;
    
    if (temperature > 20)
    {
        std::cout << "It's warm outside.\n";
        
        if (isSunny)
        {
            std::cout << "Perfect weather for a picnic!\n";
        }
        else
        {
            std::cout << "Good weather, but a bit cloudy.\n";
        }
    }
    else
    {
        std::cout << "It's cool outside.\n";
        
        if (isSunny)
        {
            std::cout << "At least it's sunny!\n";
        }
        else
        {
            std::cout << "Cold and cloudy - stay inside!\n";
        }
    }
    
    return 0;
}

Output:

It's warm outside.
Perfect weather for a picnic!

Common conditions in if statements

Comparing numbers

int x = 10, y = 20;

if (x == y)      // Equal to
if (x != y)      // Not equal to
if (x < y)       // Less than
if (x <= y)      // Less than or equal to
if (x > y)       // Greater than
if (x >= y)      // Greater than or equal to

Logical operators

int age = 25;
bool hasLicense = true;

if (age >= 16 && hasLicense)        // AND: both must be true
if (age < 16 || !hasLicense)        // OR: at least one must be true
if (!(age >= 18))                   // NOT: opposite of condition

Boolean variables

bool isLoggedIn = true;

if (isLoggedIn)          // Checks if true
if (!isLoggedIn)         // Checks if false

Best practices for if statements

1. Always use braces

// Good
if (condition)
{
    doSomething();
}

// Avoid (risky)
if (condition)
    doSomething();

2. Make conditions readable

const int ADULT_AGE = 18;
const int MAX_SCORE = 100;

// Good - clear and readable
if (age >= ADULT_AGE)
if (score <= MAX_SCORE)

// Less clear
if (age >= 18)
if (score <= 100)

3. Use early returns to reduce nesting

// Good - early return reduces nesting
if (age < 0)
{
    std::cout << "Invalid age\n";
    return 1;  // Exit with error code
}

std::cout << "Age is valid: " << age << std::endl;

// Less ideal - deeper nesting
if (age >= 0)
{
    std::cout << "Age is valid: " << age << std::endl;
}
else
{
    std::cout << "Invalid age\n";
    return 1;
}

4. Avoid deeply nested conditions

// Harder to read
if (condition1)
{
    if (condition2)
    {
        if (condition3)
        {
            // Too deep!
        }
    }
}

// Better - combine conditions
if (condition1 && condition2 && condition3)
{
    // Much clearer
}

Summary

If statements are fundamental to programming logic:

  • if executes code when a condition is true
  • else executes alternative code when the condition is false
  • else if chains multiple conditions together
  • Blocks {} group multiple statements together
  • Always use braces for clarity and safety
  • Nested if statements allow complex decision-making
  • Good practices make code readable and maintainable

Mastering if statements allows you to create programs that respond intelligently to different inputs and situations.

Quiz

  1. What happens if an if statement condition is false and there's no else clause?
  2. What is the difference between if (x = 5) and if (x == 5)?
  3. Why should you always use braces with if statements, even for single statements?
  4. How does an else if chain work? Does it check all conditions or stop at the first true one?
  5. What is a compound statement (block)?

Practice exercises

  1. Age categorizer: Write a program that asks for someone's age and categorizes them as: "Child" (0-12), "Teenager" (13-19), "Adult" (20-64), or "Senior" (65+).

  2. Number comparison: Create a program that asks for two numbers and tells the user which is larger, or if they're equal.

  3. Grade calculator: Write a program that converts numerical scores (0-100) to letter grades with + and - modifiers (e.g., 87 = B+, 83 = B, 80 = B-).

  4. Login simulator: Create a simple login system that asks for a username and password, and grants or denies access based on predefined credentials.

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