๐ŸŽ“ A1Learner
๐Ÿ”

C++ Output

Output is the text and numbers a program prints to the screen. A program can print words, whole numbers, and decimal numbers.

Two lines with \n

The \n inside each string starts a new line. Each print adds one line to the screen.

#include <iostream>

int main() {
  std::cout << "Hello\n";
  std::cout << "World\n";
  return 0;
}

Chaining joins pieces

Chaining sends piece after piece with << between them. All the pieces land on one line.

#include <iostream>

int main() {
  std::cout << "Total: " << 6 << std::endl;
  return 0;
}

std::endl ends a line

std::endl ends the current line. The next print starts on a fresh line.

#include <iostream>

int main() {
  std::cout << "First line" << std::endl;
  std::cout << "Second line" << std::endl;
  return 0;
}

Numbers need no quotes

A whole number and a decimal number print as they are. Neither value sits inside quote marks in the code.

#include <iostream>

int main() {
  std::cout << 42 << std::endl;
  std::cout << 3.5 << std::endl;
  return 0;
}

Example

#include <iostream>

int main() {
  std::cout << "Item: " << "Pen" << std::endl;
  std::cout << "Count: " << 3 << std::endl;
  std::cout << "Total: " << 6 << std::endl;
  return 0;
}

Key points

  • std::cout sends text and numbers to the screen.
  • The characters \n inside a string start a new line.
  • Chaining means joining pieces with << so they print together.
  • std::endl ends the current line.
  • Text in code sits inside double quotes.
  • Numbers print without quotes around them in the code.
  • A decimal number has a point in it, like 3.5.

In this example, the first print chains the label Item with the word Pen. The second print chains the label Count with the number 3. The third print chains the label Total with the number 6.

Note

A line can end with \n or with std::endl.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C++ Compiler

Exercise

Which line prints the number 42 and ends the line?