← Back to C++ Course | Chapter 2: Input & Output | Lesson 3 of 8

C++ New Lines

endl moves output to a new line and flushes the buffer, while the \n escape sequence inserts just the newline character, making \n the faster choice inside tight loops.

The endl Manipulator

endl is a C++ stream manipulator that moves output to a new line and also flushes the output buffer, guaranteeing the text printed so far is actually written out immediately.

Example: The endl Manipulator

cpp
#include <iostream>

int main() {
	std::cout << "Line one" << std::endl; // moves to new line and flushes
	std::cout << "Line two" << std::endl;
	return 0;
}

The \n Escape Sequence

The \n escape sequence, inherited from C, represents a newline character and can be embedded directly inside a string literal to move output to a new line at that exact point.

Example: The \n Escape Sequence

cpp
#include <iostream>

int main() {
	std::cout << "Line one\nLine two\n";
	return 0;
}

endl vs \n

Unlike endl, \n only inserts the newline character without forcing a buffer flush, which makes it the faster choice when printing many lines in a tight loop.

Example: endl vs \n

cpp
#include <iostream>

int main() {
	for (int i = 0; i < 3; i++) {
		std::cout << i << "\n"; // faster: no forced flush each iteration
	}
	return 0;
}

Multiple Lines in One Statement

Multiple lines of output can be built either by chaining several \n-terminated strings in one cout statement, or by using separate cout statements each ending in endl.

Example: Multiple Lines in One Statement

cpp
#include <iostream>

int main() {
	std::cout << "Line one\n" << "Line two\n";
	std::cout << "Line three" << std::endl;
	return 0;
}

Blank Lines

A blank line between two pieces of text is produced by two consecutive newlines, whether written as two chained endl manipulators or two \n characters next to each other in a string.

Example: Blank Lines

cpp
#include <iostream>

int main() {
	std::cout << "Above" << std::endl << std::endl;
	std::cout << "Below" << std::endl;
	return 0;
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.