In this post, you’ll learn how to write your first Hello World program in C++.
Every programmer starts to learn coding with the ‘Hello World’ program, a simple beginner’s program which focuses on the basic output statement of the language. In this lesson, you will learn how to display the statement ‘Hello World’ using the output functions. Let’s take a look at the below source code
How to Print Hello World in C++?
RUN CODE SNIPPETSource Code
#include<iostream> using namespace std; int main() { cout<<"Hello World!"; return 0; }
Output
Hello World!
Let’s break down the code to understand it better.
#include<iostream>
- This line which is called the header file is used in every C++ codding.
#include
statement tells the compiler to use available files and<iostream>
is the name of the specific file that we have used in this code. - The
<iostream>
file stands for Input and Output statement. This file includes the output statement ‘cout’ and various other statements.
using namespace std;
- The C++ has a standard library that has files for different functions and this line is used to access the standard file for input and output statements.
- The statement is necessary because when working with larger and more complex codding, the compiler can get confused on where it can find the values in the library which results in errors.
- This statement must always end with a semicolon ‘ ; ‘.
int main();
- This line usually controls the function of the code, as it calls the functions to perform their tasks.
- The
int main()
shows that the input value is a type of integer, once the program is executed the function returns to the main function, by using the statement ‘return 0;’. - The return statement must always end with a semicolon ‘ ; ‘.
{ }
- The opening ‘ { ‘ and the closing ‘ } ‘ curly braces mark the start and the finish of the main function
- Every statement and value between these braces belong to the main function.
cout
- This statement is used to display the output as a visual presentation on the output device. To display a statement as an output use this function, followed by inserting the statement after Insertion Operator ‘ << ‘
- When using characters/sentences, write them within quotes ” “,
"Hello World!"
. - This statement must always end with a semicolon ‘ ; ‘.
Now that you have understood how the source code performs its function, try it yourself to understand it better.
Note: C++ is a case-sensitive language which means that you cannot change the upper and lower case of the statements when you are using them. For example ‘cout’ and ‘Cout’ are two different statements, when not used correctly it can cause errors.