Published: 04 May 2018 โบ Updated: 04 May 2018
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
Please upvote if you liked this post, follow if you want to see more, and let me know your thoughts in the comments.
Leave Learn to code in C++ (lesson 2) - new line to:
Read more #steemiteducation posts
Best Posts From cheeto.blue
We have not curated any of cheeto.blue's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From cheeto.blue
- 1926 Chevrolet "Superior" Pick Up Truck - Franschhoek Motor Museum
- Learn to code in C++ (lesson 3) - comments
- Learn to code in C++ (lesson 2) - new line
- Learn to code in C++ (lesson 1) - Hello, World!
- Learn to code in C++ (lesson 0) - install a C++ IDE
- Back to work - hello Steemit!!
- 1914 Humbrette Model 8 - Franschhoek Motor Museum
- 1911 Ford Model T - Franschhoek Motor Museum
- 1904 Mars Carette - Franschhoek Motor Museum
- Allen family