In this C++ tutorial, you will learn how to write a basic C++ program that prints the message “Hello World” to standard output.

C++ Hello World Program

Printing the message “Hello World” to the standard output is a classic program that everyone writes when they start learning a programming language.

Program

The following is a C++ program, that prints Hello World to standard console output.

main.cpp

#include <iostream>  
using namespace std;

int main() {
   cout << "Hello World!";
}

Name of the above C++ file is main.cpp. Extension of a C++ file is .cpp.

ADVERTISEMENT

Program Explanation

Let us go into the program and understand it line by line.

Line 1: #include <iostream>

An include statement. We are including iostream header file to use the functionalities in it. There are many header files that come included with C++. You can include one header file using one include statement. To include multiple header files in your program, write an include statement for each one of them.

You can also create a header file of your own, in which you define some functionalities. And then you can include that header in your program.

Line 2: using namespace std;

Using namespace statement. Namespaces is kind of grouping of variables under a single name. In this statement we specified that we shall use the namespace named std. std has variables defined like cout which we used in the program in line 5. If you are not writing this using namespace statement, you have to write std::cout instead of cout. While going forward, you will see that writing this namespace statement is useful to ease out the code.

Line 3 – An empty line. You can write empty lines in your C++ program. This lets you have some space between your statements and function. Just to increase the readability of program. Empty lines or spaces are ignored by C++ compiler.

Line 4: int main() {

A function definition. We are defining a function named main that returns an integer and accepts no arguments. You will see main() in most of our C++ programs. This is because main() function is kind of an entry point to the execution of a C++ program. We also have a flower brace that starts the scope of this main() function.

Line 5: cout << "Hello World!";

cout can be used to write an object or value to standard output.

Line 6: }

Ending flower bracket. This closes the scope of main function. Body of main() function, which includes all the statements inside it, should be enclosed between flower braces.

Conclusion

In this C++ Tutorial, we learned how to write a basic hello world program in C++.