Hello, World!

Programming Languages · C++ Basics · 8 min

Make C++ talk: print text and numbers, start new lines, and leave notes for humans.

Your first line of code

A program is a list of instructions for the computer. In C++ you show text on the screen with std::cout (say "see-out") and the << arrow, which pushes the text out:

std::cout << "Hi there";

Text goes inside double quotes. Every instruction ends with a semicolon ;, like a full stop.

  • Print Hello, World!

The shape of a program

Every C++ program has the same frame:

#include <iostream>

int main() {
    std::cout << "Hi";
    return 0;
}

#include <iostream> brings in std::cout. main is where the program starts, and its code lives between the curly braces { }. return 0; means "finished, no problems". C++ adds it for you in main, but you will see it a lot.

  • Inside main, print Starting up.

  • Add return 0; as the last line inside main.

New lines

std::cout does not start a new line by itself. End a line with std::endl, or put \n (the newline character) inside the text:

std::cout << "Line one" << std::endl;
std::cout << "Line two\n";

Both do the same job here. Most C++ programmers just use \n.

  • Print I am learning C++ and end the line.

  • On the next line, print It is fun.

Numbers don't need quotes

Numbers are different from text. Leave out the quotes and C++ treats them as numbers, so it can do maths:

std::cout << 2 + 3 << "\n";
std::cout << "2 + 3" << "\n";

The first line prints 5. The second prints the text exactly as written. You can chain several << on one line, like above.

  • Print the result of 12 * 4 (no quotes).

Comments are notes for humans

A comment is a note that C++ skips completely. // turns the rest of the line into a comment. Programmers use comments to explain why the code does something.

// This line is ignored
std::cout << "This one runs\n";
  • Add a // comment that says what the program does.

  • Below the existing line, print Comments are skipped.

Put it together: a name badge

Time to combine everything. Make a little name badge that prints three lines. You can use your own name.

  • Print HELLO on the first line.

  • Print my name is on the second line.

  • Print any name on the third line.

More in C++ Basics

Previous: Lambdas and Streams · Next: Variables