In this program, we will print the hello world on the output screen. We will use cout object of class ostream and also have used // symbol to use comments in C++ to tell what that particular statement does.
We will print it in two different ways so that we can learn more about the cout object.
Print hello world
On separate lines
Using endl stream manipulator
We can achieve this by using the cout object. We will use endl. It is used to break the line and jump the cursor to the next line.
Code:
1 2 3 4 5 6 7 8 9 10 11 |
#include<iostream> using namespace std; int main(){ // prints hello world on separate lines cout << "hello" << endl << "world"; return 0; } |
Using the ‘\n’ character
There is one more way of doing this. We can just include the newline(\n) character in between.
1 2 3 4 5 6 7 8 9 10 11 |
#include<iostream> using namespace std; int main(){ // prints hello world on separate lines cout << "hello\nworld"; return 0; } |
Both of the above-discussed methods will give the same output.
1 2 3 4 |
hello world |
C++ Code on the same line
We can achieve this by printing one full string.
There is one more way, in which we will use the << operator to concatenate the two strings.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include<iostream> using namespace std; int main(){ // prints hello world on the same line cout << "hello world"; cout << endl; cout << "hello " << "world"; return 0; } |
Output:
1 2 3 4 |
hello world hello world |
[…] C++ Program to Hello World! […]