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

in steemiteducation •  6 months ago
image

Now that we know how to display some text, let's take it a bit further.

What if we wanted to type "Hello World", not on one line, but rather on two separate lines. So, instead of this:

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.

cheeto.blue
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.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

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 😁

You just received a Tier 0 upvote! Looking for bigger rewards? Click here and learn how to get them or visit us on Discord