C++ New Lines

C++ Tutorial

💻 C++ New Lines – Complete Beginner to Interview Guide

In C++ New Lines are used to move the cursor to the next line while printing output.
They make output readable, structured, and professional.


1️⃣ New Line Using endl


 

Output

Hello
C++

📌 Points

  • Moves cursor to next line

  • Flushes output buffer

  • Slightly slower in loops


2️⃣ New Line Using \n


Output

Hello
C++

📌 Points

  • Faster than endl

  • Does not flush buffer

  • Preferred in competitive programming


3️⃣ Multiple New Lines ⭐


Output

Line 1

Line 2


4️⃣ New Line with Variables ⭐


Output

A = 10
B = 20

5️⃣ C++ New Lines Inside Loops ⭐


Output

Number: 1
Number: 2
Number: 3

6️⃣ Mixing endl and \n ⚠️


Output

Hello
World
C++

7️⃣ Common New Lines Mistakes ❌

❌ Forgetting << endl
❌ Writing /n instead of \n
❌ Using endl inside heavy loops (slow)
❌ Expecting \n to flush output


📌 Interview Questions (C++ New Lines)

Q1. Difference between endl and \n?
👉 endl adds a new line and flushes buffer
👉 \n only adds a new line

Q2. Which is faster: endl or \n?
👉 \n

Q3. When should endl be used?
👉 When buffer flushing is required (debugging, logs)


✅ Summary

endl → new line + buffer flush
\n → new line only
✔ Use \n for performance
✔ Use endl for clarity/debugging

You may also like...