CodeMIRAI
0 XP

Your first program

2 min read 3 runnable examples Quiz included
C++
#include <iostream>
using namespace std;

int main() {
    cout << "Welcome to C++" << endl;
    cout << "Line two" << "\n";
    return 0;
}

Line by line

#include <iostream> includes the input/output stream library, which provides cout and cin.

using namespace std; lets you write cout instead of std::cout. The Standard Library puts its names in the std namespace to avoid clashes with your own names.

int main(): as in C, execution starts here.

cout << ... ; writes to the screen. << is the insertion operator: it pushes each value into the output, left to right.

endl ends the line (and flushes the output). "\n" also starts a new line.

return 0; reports success to the operating system.

Chaining output

<< can chain text, numbers and expressions in one statement:

C++
#include <iostream>
using namespace std;

int main() {
    int apples = 5;
    double price = 0.75;
    cout << apples << " apples cost " << apples * price << endl;
    return 0;
}

Without using namespace std

Many professional codebases avoid using namespace std; and write the prefix explicitly:

C++
#include <iostream>

int main() {
    std::cout << "Explicit std:: prefix" << std::endl;
    return 0;
}

Both styles work with a real compiler, and the explicit prefix makes it clear where each name comes from. (This one example is shown without a Run button: the in-browser interpreter only understands the using namespace std; style.)

Comments

C++
#include <iostream>
using namespace std;

int main() {
    // single-line comment
    /* multi-line
       comment */
    cout << "Comments are ignored" << endl;
    return 0;
}
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.