In this guide you will create and understand your first program in C++ programming. Create a simple C++ program that prints "Hello World!" message. Let's look at the program first. Now let's dive into all the parts of it.

Hello World Program in C++

/*

* Multiple line

* comment

*/

#include<iostream>

 

//Single line comment

using namespace std;

 

//This is where the execution of program begins

int main()

{

   // displays Hello World! on screen

   cout<<"Hello World!";

 

   return 0;

}

 

Output:

Hello World!

 

Let’s discuss each and every part of the above program.

1. Comments – You can see two types of comments in the above program

// This is a single line comment
/* This is a multiple line comment
* suitable for long comments
*/

Comments as the names suggests are just a text written by programmer during code development. Comment doesn’t affect your program logic in any way, you can write whatever you want in comments but it should be related to the code and have some meaning so that when someone else look into your code, the person should understand what you did in the code by just reading your comment.

For example:

/* This function adds two integer numbers 
 * and returns the result as an integer value
 */
int sum(int num1, int num2) {
   return num1+num2;
}

Now if someone reads my comment he or she can understand what I did there just by reading my comment. This improves readability of your code and when you are working on a project with your team mates, this becomes essential aspect.

2. #include - This directive tells the compiler to include iostream files. This file contains predefined input/output functions that you can use in your program.

 

3. Use the std namespace. – A namespace is like an area with functions, variables, etc. whose scope is limited to that particular area. Here std is a namespace name that tells the compiler to look for all variables, functions, etc. in that particular domain. We won't go into detail about this here as it can be confusing. I covered this topic with an example in another tutorial. Just follow the tutorials in the given order and you'll be fine.

 

4. int main() - As the name suggests, this is the main function of the program and program execution begins from this function. Int is the return type here, indicating to the compiler that this function returns an integer value. This is the main reason for the return 0 statement at the end of the main function.

 

5. Cout << "Hello World!"; – The cout object belongs to the iostream file and the purpose of this object is to display the double-quoted content to the screen as-is. This object can also print the values ​​of variables to the screen (don't worry, we'll cover that in a future tutorial).

6. Returns 0. – This statement returns 0 from the main() function to indicate successful execution of the main function. A value of 1 represents a failed execution.