No history yet

Introduction to C++

Your First C++ Program

Let's start by writing a program that prints a simple message. This is a classic tradition in programming, and it's a great way to see the basic structure of a C++ file.

// This is a comment. The computer ignores it.

// Include the iostream library for input and output
#include <iostream>

// All C++ programs start running in the main function
int main() {
    // Print "Hello, World!" to the console
    std::cout << "Hello, World!";
    
    // Tell the operating system the program ran successfully
    return 0;
}

Let's break that down:

  • #include <iostream>: This line tells the compiler to include the iostream file, which is a library that lets us work with input and output, like printing text to the screen.
  • int main(): This is the main function. Every C++ program has one, and it's the starting point for execution.
  • `std::cout <<

Storing Information

To do anything useful, programs need to store information. We do this using variables. A variable is just a named piece of memory where you can keep a value. When you create a variable, you have to tell C++ what type of data it will hold.

Think of a variable's type like a specially shaped container. A box for shoes isn't the right shape for storing soup, and a variable for whole numbers isn't the right type for storing text.

Here are the most common data types you'll use:

TypeDescriptionExample
intIntegers (whole numbers)int age = 30;
doubleFloating-point numbers (decimals)double price = 19.99;
charA single characterchar grade = 'A';
boolBoolean (true or false)bool isLoggedIn = true;
std::stringA sequence of characters (text)std::string name = "Alice";

Notice that std::string looks a bit different. That's because it comes from a library, just like std::cout. You'd need to include its library at the top of your file with #include <string> to use it.

Once you have variables, you can perform operations on them using operators like + (addition), - (subtraction), * (multiplication), and / (division).

int main() {
    int a = 10;
    int b = 5;
    int sum = a + b; // sum is 15
    
    double wallet = 50.0;
    double itemCost = 12.50;
    double remaining = wallet - itemCost; // remaining is 37.5

    std::cout << remaining;
    return 0;
}

Making Decisions and Repeating Actions

Programs often need to make choices or perform actions repeatedly. C++ gives us tools for this called control structures.

To make a decision, we use if, else if, and else. The program checks a condition, and if it's true, it runs a specific block of code.

int score = 85;

if (score >= 90) {
    std::cout << "You got an A!";
} else if (score >= 80) {
    std::cout << "You got a B!";
} else {
    std::cout << "You can do better!";
}
// Output: You got a B!

To repeat an action, we use loops. A for loop is great when you know exactly how many times you want to repeat something.

// This loop will run 5 times
for (int i = 0; i < 5; i++) {
    std::cout << "This is loop number " << i << "\n";
}

A while loop is used when you want to repeat as long as a certain condition is true.

int countdown = 3;

while (countdown > 0) {
    std::cout << countdown << "...\n";
    countdown = countdown - 1; // Or countdown--;
}
std::cout << "Liftoff!\n";

Building with Functions

As programs grow, you'll find yourself writing the same piece of code over and over. Functions let you package up a block of code, give it a name, and call it whenever you need it. This keeps your code organized and easy to manage.

A function has a return type (what kind of data it sends back), a name, and a list of parameters (the input it needs). The main function we've been using is just a special function that the system calls automatically.

#include <iostream>

// This function takes two integers and returns their sum
int add(int num1, int num2) {
    return num1 + num2;
}

int main() {
    int result = add(5, 3); // Call the function
    std::cout << "The result is: " << result;
    return 0;
}

In this example, when we call add(5, 3), the values 5 and 3 are passed into the num1 and num2 parameters inside the function. The function then returns their sum, 8, which gets stored in the result variable.

A Glimpse of Object-Oriented Programming

One of the most powerful features of C++ is its support for Object-Oriented Programming (OOP). The core idea is to bundle data and the functions that operate on that data into a single unit called an object.

Think of it like this: a car has data (color, speed, fuel level) and functions (accelerate, brake). OOP lets you create a "Car" blueprint that keeps all that information and behavior together.

In C++, this blueprint is called a class. A class defines the properties (variables) and methods (functions) that its objects will have.

class Dog {
public:
    // Properties
    std::string name;
    std::string breed;

    // Method
    void bark() {
        std::cout << "Woof!\n";
    }
};

int main() {
    Dog myDog;
    myDog.name = "Fido";
    myDog.breed = "Golden Retriever";

    std::cout << "My dog's name is " << myDog.name << ".\n";
    myDog.bark(); // Calls the bark method
    return 0;
}

OOP also allows for inheritance, where a new class can be based on an existing one. For example, you could have a general Animal class, and then create a Dog class that inherits from Animal. The Dog class would automatically get all the properties and methods of Animal, and could also add its own specific ones.

This is just scratching the surface, but it's the fundamental idea that makes C++ so flexible for building large, complex applications.

Quiz Questions 1/6

What is the primary role of the int main() function in a C++ program?

Quiz Questions 2/6

Which data type would be most appropriate for storing the value 9.99, representing the price of an item?

You've just covered the basic building blocks of C++. With variables, control structures, functions, and the idea of classes, you have the foundational tools to start writing powerful programs.