C++C++ · Lesson 1 of 9

Hello, World!

C++ Hello World has a critical upgrade over C's version: it uses cout instead of printf, and the difference reveals everything about the two languages.

C++
#include <iostream>
#include <string>

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

cout is the standard output stream. << is the stream insertion operator — it "inserts" data into the stream. endl flushes the buffer and adds a newline (use "\n" instead for performance in tight loops). std:: is the standard library namespace.

C++
#include <iostream>
#include <string>
using namespace std;  // now you can write cout instead of std::cout

int main() {
    cout << "Hello, World!" << "\n";

    string name = "Alice";
    int age = 30;

    // Chain multiple insertions
    cout << "Name: " << name << ", Age: " << age << "\n";

    // endl vs "\n"
    // endl: flushes buffer (slower, use when you need immediate output)
    // "\n": just a newline (faster)
    cout << "Fast newline\n";
    cout << "Flushed output" << endl;

    // Input with cin
    // cout << "Enter your name: ";
    // string input;
    // cin >> input;   // reads one word
    // getline(cin, input);  // reads full line

    return 0;
}
◆ Note
using namespace std; saves typing but pollutes the global namespace. In small programs and student code it's fine. In larger codebases, be explicit: std::cout, std::string, etc.