Your First C++ Program

Let's get our hands dirty working on a "Hello, World!" program in C++.

“Hello, World!” program

Below is the source code for your first C++ program. First, have a look at the code, then we will discuss it.

Press the RUN button and see the output!

#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
}

When we run the code above, it prints Hello, World! on the console. It means we can modify this code to print anything on the console. Sounds interesting!

Explanation

The highlighted lines in the above program will appear in every C++ program. We will cover the functionality of these lines in the upcoming chapters. For now, just remember that we will always write our code inside the curly braces { }.

📝Note: If you want to dive into the details, you can visit this link Anatomy of a “Hello World!” program.

The segment of the program we want to pay attention to right now is on Line No. 6. When this line executes, it will print Hello, World! on the console.

“Hello, World!”

In C++, we write our content inside double-quotes. Anything written inside double quotes is known as a string. Here, Hello, World! is a string. Don’t worry about the details of a string yet. We’ll cover these details in an upcoming section of the course.

<<

<< is called the insertion or output operator. It takes the content written on its right-hand side and inserts it into the cout. You will learn thoroughly about operators in C++ in an upcoming chapter.

cout

cout knows that it should print everything that is sent via an insertion operator onto the console.

;

A statement is a command that the programmer gives to the computer. Here, Line no. 6 is a statement. It instructs the machine to display Hello, World! on the console. Every statement in the C++ program ends with a semicolon, which indicates the end of the current statement and also that the next one is ready to execute.

Quiz

Q

What is the output of the following C++ program?

int main() 
{
  cout << "I am John.";
}
A)

I am John

B)

“I am John”

C)

I am John.

D)

“I am John.”


🎉 Congratulations! You have just executed the first code in C++. Let’s move on to the next lesson where you will learn about different printing styles.