No history yet

C++ Basics

Getting Started with C++

C++ is a powerhouse for competitive programming. It's fast, efficient, and comes with a rich Standard Template Library (STL) that provides many common data structures and algorithms right out of the box. This combination allows you to write code that runs quickly, which is crucial when problem constraints are tight.

Before you can write any code, you need a development environment. This consists of two main parts: a text editor to write your code and a compiler to translate it into a language the computer can understand.

For a simple and powerful setup, you can use a text editor like Visual Studio Code and a compiler like g++. Most operating systems have straightforward ways to install g++. Once it's set up, you can compile a file named my_program.cpp from your terminal with a command like g++ my_program.cpp -o my_program and run it with ./my_program.

Your First Program

Let's start with the traditional "Hello, World!" program. It's a simple program that just prints a message to the screen, but it introduces the basic structure of all C++ applications.

#include <iostream>

// This is the main function where the program starts.
int main() {
    // Print a message to the console.
    std::cout << "Hello, World!" << std::endl;
    return 0; // Signal that the program finished successfully.
}

Let's break this down line by line:

  • #include <iostream>: This line is a preprocessor directive. It tells the compiler to include the iostream library, which contains the tools for input and output operations, like printing to the screen.
  • int main(): This is the main function. Every C++ program must have a main function, as it's the starting point of execution.
  • std::cout: This is the standard character output stream. The std:: part indicates that cout is part of the standard namespace. It's used to send output to the console.
  • <<: This is the stream insertion operator. It 'inserts' the data on its right into the stream on its left.
  • "Hello, World!": This is a string literal, the text we want to print.
  • std::endl: This is a manipulator that inserts a newline character and flushes the output buffer, ensuring your text appears on the screen immediately.
  • return 0;: This line exits the main function and returns the value 0 to the operating system, which signifies that the program ran without any errors.

Variables and Data Types

Variables are named containers for storing data. To create a variable, you must specify its data type and give it a name. The type tells the compiler how much memory to allocate and what kind of data can be stored.

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

TypeDescriptionExample Usage
intIntegers (whole numbers)int score = 100;
doubleFloating-point numbers (with decimals)double pi = 3.14159;
charA single characterchar grade = 'A';
boolBoolean value (true or false)bool is_correct = true;
std::stringA sequence of charactersstd::string name = "Alice";

To use a variable, you declare it and optionally initialize it with a value. Using const before the type makes the variable's value unchangeable after initialization, which is good practice for values that shouldn't be altered.

#include <iostream>
#include <string> // Required for using std::string

int main() {
    // Declare and initialize variables
    int participant_count = 50;
    double average_score = 88.5;
    const double PASSING_GRADE = 60.0;

    // Using the variables
    std::cout << "Participants: " << participant_count << std::endl;
    std::cout << "Average score: " << average_score << std::endl;

    return 0;
}

Control Your Code's Flow

Programs rarely execute in a straight line. Control structures allow you to make decisions and repeat actions based on certain conditions.

The if-else statement is the primary tool for decision-making. It runs a block of code if a condition is true, and a different block if it's false.

#include <iostream>

int main() {
    int score = 85;

    if (score >= 60) {
        std::cout << "You passed!" << std::endl;
    } else {
        std::cout << "You need to study more." << std::endl;
    }

    return 0;
}

Loops are used to execute a block of code repeatedly. The for loop is perfect when you know how many times you want to repeat, while the while loop is ideal when you want to loop as long as a condition remains true.

#include <iostream>

int main() {
    // A 'for' loop that counts from 1 to 5
    std::cout << "Counting with a for loop:" << std::endl;
    for (int i = 1; i <= 5; ++i) {
        std::cout << i << " ";
    }
    std::cout << std::endl;

    // A 'while' loop that does the same thing
    std::cout << "Counting with a while loop:" << std::endl;
    int j = 1;
    while (j <= 5) {
        std::cout << j << " ";
        j++;
    }
    std::cout << std::endl;

    return 0;
}

Functions and Input/Output

Functions are reusable blocks of code that perform a specific task. They help you organize your program into logical, modular pieces. A function can take inputs (parameters) and produce an output (return value).

Breaking down a complex problem into smaller, manageable functions is a key skill in programming.

Here’s how you define and use a function to calculate the area of a rectangle. This example also shows how to read input from the user with std::cin and the stream extraction operator >>.

#include <iostream>

// Function declaration: takes two integers, returns an integer
double calculate_area(double length, double width) {
    return length * width; // Return the result of the calculation
}

int main() {
    double rect_length, rect_width;

    // Prompt the user for input
    std::cout << "Enter the length of the rectangle: ";
    std::cin >> rect_length; // Read user input into the variable

    std::cout << "Enter the width of the rectangle: ";
    std::cin >> rect_width;

    // Call the function and store its return value
    double area = calculate_area(rect_length, rect_width);

    // Print the result
    std::cout << "The area is: " << area << std::endl;

    return 0;
}

In competitive programming, you'll constantly be reading input, processing it, and printing output. Mastering std::cin and std::cout is the first step. For faster I/O in competitive settings, you can add std::ios_base::sync_with_stdio(false); and std::cin.tie(NULL); at the start of your main function, but don't worry about the details of that just yet.

Time to check your understanding of these core concepts.

Quiz Questions 1/5

What is the primary purpose of the line #include <iostream> at the beginning of a C++ program?

Quiz Questions 2/5

Every C++ program must have a function named main, as it serves as the entry point for execution.

These are the fundamental building blocks of C++. With them, you can start solving a wide range of programming challenges.