Skip to main content

📝 Lesson 3: Data Types and Operators

Master the basics of data storage, arithmetic, and logic in C++.

🎯 Learning Objectives

By the end of this lesson, you will be able to:

  • Identify and use primitive C++ data types (int, double, char, bool, string).
  • Understand the importance of choosing appropriate data types for memory efficiency.
  • Apply arithmetic, assignment, comparison, and logical operators in your code.
  • Perform safe type conversions using explicit casting.

Estimated Time: 60–90 minutes

Project: Build an operator calculator that reads two numbers and reports their arithmetic and comparison results. (An optional stretch peeks ahead to operator selection.)

In This Lesson

Data Types: The Building Blocks

Think of data types as different kinds of containers. Just like you wouldn't store soup in an envelope or mail in a bowl, different types of data need different types of storage!

Why Different Data Types?

Using the right data type is like using the right tool for a job. You wouldn't use a hammer to cut paper or scissors to drive a nail!

flowchart TD A[Choose Data Type] --> B{What are you storing?} B -->|Whole number| C[int] B -->|Decimal| D[double or float] B -->|Single character| E[char] B -->|Yes/No| F[bool] B -->|Text| G[string] C --> H[Age: 25] D --> I[Price: 19.99] E --> J[Grade: A] F --> K[Is student: true] G --> L[Name: Alice]

Declaring and Using Variables

Declaring a variable is like putting a label on a container before filling it.

// Declaration: Creating the container
int age;           // Empty container for whole numbers
double price;      // Empty container for decimals
char grade;        // Empty container for single character
bool isPassed;     // Empty container for true/false
string name;       // Empty container for text

// Initialization: Filling the container
age = 21;
price = 49.99;
grade = 'A';
isPassed = true;
name = "Sarah";

// Declaration + Initialization: Create and fill at once
int score = 100;
double temperature = 98.6;
char initial = 'J';
bool isReady = false;
string city = "New York";

Memory Visualization

Each data type uses different amounts of computer memory, like different sized boxes in storage.

Memory Usage by Data Type char 1 byte int 4 bytes float 4 bytes double 8 bytes Note: Each rectangle represents relative memory size

Type Conversion: Changing Containers

Sometimes you need to convert data from one type to another, like pouring water from a cup to a bottle. C++ handles this, but it requires careful attention to avoid data loss.

⚠️ Pro Tip: Implicit vs. Explicit

While C++ often performs implicit (automatic) conversion, relying on it can lead to subtle bugs. Always prefer explicit casting using static_cast<new_type>(value). It makes your intentions clear to other developers and prevents unintended precision loss.

Arithmetic Operators: Math Operations

Operators are like mathematical tools that work with your data.

flowchart LR A["Arithmetic Operators"] --> B["+ Addition"] A --> C["- Subtraction"] A --> D["* Multiplication"] A --> E["/ Division"] A --> F["% Modulus"] B --> G["5 + 3 = 8"] C --> H["10 - 4 = 6"] D --> I["6 * 7 = 42"] E --> J["20 / 4 = 5"] F --> K["17 % 5 = 2"]

The Special Modulus Operator (%)

The modulus operator gives you the remainder after division. It's like dividing cookies among friends and seeing how many are left over!

17 % 5 = 2 (Remainder) Group 1 (5) Group 2 (5) Group 3 (5) Remainder (2)

Compound Assignment Operators

These are shortcuts for common operations, like speed dial on a phone!

int score = 10;

// Long way vs. Short way
score = score + 5;    // Long way
score += 5;          // Short way (same result!)

// All compound operators
score += 3;    // score = score + 3
score -= 2;    // score = score - 2
score *= 4;    // score = score * 4
score /= 2;    // score = score / 2
score %= 3;    // score = score % 3

Increment and Decrement Operators

These operators add or subtract 1, perfect for counting!

Comparison Operators: Making Decisions

These operators compare values and return true or false, like asking yes/no questions.

Comparison Operators == Equal to != Not equal > Greater < Less than >= Greater/equal <= Less/equal Examples: 5 == 5 → true 5 != 3 → true 7 > 10 → false 3 < 8 → true 5 >= 5 → true 9 <= 6 → false

Logical Operators: Combining Conditions

Logical operators let you combine multiple conditions, like asking "Do you have milk AND eggs?" or "Do you want coffee OR tea?"

graph TD A[Logical Operators] --> B["&& (AND)"] A --> C["|| (OR)"] A --> D["! (NOT)"] B --> E["Both must be true"] C --> F["At least one true"] D --> G["Reverses true/false"] E --> H["age >= 18 && hasLicense"] F --> I["isWeekend || isHoliday"] G --> J["!isRaining"]

Practice Exercise: Calculator Program

🏋️ Build an Operator Calculator

Put this lesson's operators to work — using only what you've learned so far (no if statements yet; those are next lesson).

Instructions:

  1. Read two numbers from the user into double variables.
  2. Print the four arithmetic results: sum, difference, product, and quotient.
  3. Print two comparison results — is the first greater than the second, and are they equal? (A comparison yields a bool, which prints as 1 for true and 0 for false.)

Starter Code:

#include <iostream>
using namespace std;

int main() {
    double a, b;

    // TODO: prompt for and read a, then b
    // TODO: print sum, difference, product, quotient
    // TODO: print the results of a > b and a == b

    return 0;
}
💡 Hint

You already have every tool you need: arithmetic operators (+ - * /) and comparison operators (>, ==). Compute right inside the output, e.g. cout << "Sum: " << a + b << '\n';. Wrap comparisons in parentheses so they evaluate before printing: cout << (a > b);. No decisions or branching required.

✅ Solution
#include <iostream>
using namespace std;

int main() {
    double a, b;

    cout << "Enter the first number: ";
    cin  >> a;
    cout << "Enter the second number: ";
    cin  >> b;

    // Arithmetic operators
    cout << "Sum:        " << a + b << '\n';
    cout << "Difference: " << a - b << '\n';
    cout << "Product:    " << a * b << '\n';
    cout << "Quotient:   " << a / b << '\n';

    // Comparison operators yield a bool (1 = true, 0 = false)
    cout << "a > b?  " << (a > b)  << '\n';
    cout << "a == b? " << (a == b) << '\n';

    return 0;
}

🔭 Optional Stretch: Pick One Operation (peek ahead)

This reaches into the next lesson on purpose — skip it with a clear conscience if you'd rather wait. Instead of printing all the results, let the user type one operator (+ - * /) and print just that result. Choosing which calculation to run requires a decision — the if statement — which you'll learn properly in Lesson 4: Control Structures. Here's a taste if you're curious.

💡 Hint

Read the operator into a char with cin >> operation;. Compare a char to a literal using single quotes: if (operation == '+') { ... }. Chain the cases with else if.

✅ Solution
#include <iostream>
using namespace std;

int main() {
    double num1, num2, result;
    char operation;

    cout << "Enter first number: ";
    cin  >> num1;
    cout << "Enter operation (+, -, *, /): ";
    cin  >> operation;
    cout << "Enter second number: ";
    cin  >> num2;

    if (operation == '+') {
        result = num1 + num2;
        cout << "Result: " << result << '\n';
    } else if (operation == '-') {
        result = num1 - num2;
        cout << "Result: " << result << '\n';
    } else if (operation == '*') {
        result = num1 * num2;
        cout << "Result: " << result << '\n';
    } else if (operation == '/') {
        if (num2 != 0) {
            cout << "Result: " << num1 / num2 << '\n';
        } else {
            cout << "Error: Division by zero!" << '\n';
        }
    } else {
        cout << "Unknown operator: " << operation << '\n';
    }

    return 0;
}

Don't worry if the if / else if syntax feels new — Lesson 4 covers it from the ground up.

Common Mistakes to Avoid

Quick Reference Card

graph TD A[C++ Operators Quick Reference] --> B[Arithmetic] A --> C[Comparison] A --> D[Logical] A --> E[Assignment] B --> F["+ - * / %"] C --> G["== != > < >= <="] D --> H["&& || !"] E --> I["= += -= *= /= %="]

Challenge Exercise: Eligibility Checker

🏋️ Advanced Practice with Comparison & Logical Operators

Using only this lesson's operators (still no if — that's next lesson), write a program that:

  1. Asks for the user's age and a test score (0–100).
  2. Computes these true/false facts, each stored in a bool:
    • isAdult — age is 18 or over
    • passed — score is 60 or over
    • honorRoll — score is 90 or over
    • eligible — is an adult and passed
  3. Prints each flag (a bool prints as 1 for true, 0 for false).
💡 Hint

Combine comparisons with the logical operators && (and), || (or), and ! (not). For example: bool eligible = isAdult && passed;

✅ Solution
#include <iostream>
using namespace std;

int main() {
    int age, score;

    cout << "Enter your age: ";
    cin  >> age;
    cout << "Enter your score (0-100): ";
    cin  >> score;

    bool isAdult   = age >= 18;
    bool passed    = score >= 60;
    bool honorRoll = score >= 90;
    bool eligible  = isAdult && passed;

    cout << "isAdult:   " << isAdult   << '\n';
    cout << "passed:    " << passed    << '\n';
    cout << "honorRoll: " << honorRoll << '\n';
    cout << "eligible:  " << eligible  << '\n';

    return 0;
}

Want to turn a score into an actual letter grade (A/B/C/D/F) or print a different message for each case? That requires making a decision — the if and switch statements in Lesson 4: Control Structures. The classic letter-grade calculator is a perfect first project the moment you finish that lesson.

🎯 Quick Quiz

Question 1: What does the expression 17 % 5 evaluate to in C++?

Question 2: What's wrong with writing if (x = 5) when you meant to check whether x equals 5?

Question 3: Given int x = 5; cout << x++;, what gets printed, and what is x afterward?

Summary

🎉 Key Takeaways

  • Data types determine what kind of information you can store
  • Choose wisely: int for counting, double for measurements, string for text
  • Operators perform arithmetic, assignment, comparison, and logical operations on your data
  • == compares, = assigns — don't mix them up!
  • Compound assignment (+=, -=, etc.) and increment/decrement (++, --) are shortcuts worth knowing well
  • Prefer explicit casts like static_cast<int>(value) over relying on implicit conversion
  • Initialize variables to avoid unexpected behavior
  • Practice with small programs to build confidence

📚 Additional Resources

🚀 What's Next?

You now know how to store data and operate on it — but every program also needs to make decisions. In Lesson 4: Control Structures, you'll take the comparison and logical operators from this lesson and put them to work in if/else statements and switch statements to control the flow of your programs.

🎉 Data types and operators: mastered!

You've built the vocabulary every C++ expression is made of. From here on, every program you write will lean on what you just learned.