Learn to code in C++ (lesson 2) - new line

Hello World
we rather want this:
Hello
World
Can you guess how to do this? If you really are brand new to coding then I'm guessing you won't have any idea. Or, maybe you thought we do it like this:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello";
cout << "World";
return 0;
}
That most certainly "looks" right, but unfortunately that will not place the words on separate lines 🙁 Try it out and see what happens.
If you typed the program above out and ran it, you would have seen a result like this:
HelloWorld
Wow! That was unexpected. What went wrong?
Well, we have told C++ to cout
(display) the word Hello
and then to cout
(display) the word World
.
Somehow we need to let C++ know that we would like to start on a new line (or, end the current line). This is where the object endl
comes in. endl
stands for "end line". endl
is used in conjunction with cout
and <<
.
This is how we implement endl
to our code:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello" << endl;
cout << "World";
return 0;
}
Notice how we had C++ output Hello
and endl
using the same statement? We can send additional outputs to the display using the same statement by separating them with <<
each time.
Technically, endl
can be used anywhere in the cout
statement - even on it's own. Any of these 3 options would actually work:
cout << "Hello" << endl;
cout << "World";
cout << "Hello";
cout << endl;
cout << "World";
cout << "Hello";
cout << endl << "World";
But remember our programming style? Always keep it in mind when coding! We need to make sure that if someone else had to read our code that they would easily understand/visualise what we are trying to accomplish.
And that is it on endl
for now. We'll be using these a lot in our upcoming programs 😁
Interested in additional content, including activities and solutions?
See my blog here.

Team South Africa banner designed by @bearone
Hiiiii great news, i will follow you and hop to learn a minimum of coding....
Awesome!! I really hope you enjoy the lessons. Coding is actually a lot of fun 😎
wow... thanks for this.
Greatest pleasure 😁
@cheeto.blue You have earned a random upvote from @botreporter because this post did not use any bidbots.