Saying hello
The first thing every programmer learns is how to show something on the screen. In C++ we use cout (say it: “see out”, short for character output):
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}Output
Hello, World!
The important line is cout << "Hello, World!";
coutis the screen.<<means “send to”. Picture an arrow pushing the text intocout.- The double quotes
" "mark text. Text in quotes is called a string. - The
;(semicolon) ends the instruction, like a full stop ends a sentence.
Remember: Every instruction in C++ ends with a semicolon
;. Forgetting it is the most common beginner mistake.
New lines: endl and \n
cout does not start a new line by itself. Look what happens with two lines:
#include <iostream>
using namespace std;
int main() {
cout << "Line one";
cout << "Line two";
return 0;
}Output
Line oneLine two
Both pieces end up on the same line! To end a line, send endl (end line) or put \n inside the text. Both do the same job:
#include <iostream>
using namespace std;
int main() {
cout << "Line one" << endl;
cout << "Line two\n";
cout << "Line three" << "\n";
return 0;
}Output
Line one Line two Line three
Tip: Most programmers use
"\n"because it is shorter. Use whichever you like.
Chaining many things together
You can use << many times in one line. Each piece is sent to the screen, one after another. Numbers don't need quotes, and C++ can even do maths for you:
#include <iostream>
using namespace std;
int main() {
cout << "I am " << 20 << " years old." << "\n";
cout << "Next year I will be " << 20 + 1 << "\n";
cout << "5 + 3 = " << 5 + 3 << "\n";
return 0;
}Output
I am 20 years old. Next year I will be 21 5 + 3 = 8
See the difference? "5 + 3 = " is in quotes, so it is printed exactly as written. 5 + 3 has no quotes, so C++ works it out and prints 8.
Special characters
Some characters need a backslash \ in front of them. These are called escape sequences:
#include <iostream>
using namespace std;
int main() {
cout << "She said \"Hi!\"\n"; // \" puts a quote inside text
cout << "Name:\tSam\n"; // \t is a tab (a wide space)
cout << "A backslash: \\\n"; // \\ prints one backslash
return 0;
}Output
She said "Hi!" Name: Sam A backslash: \