cout Statement
Part of the Fundamentals section of Coddy's C++ journey — lesson 33 of 74.
In C++, the cout object provides various methods for printing output to the console. Here are some of the most commonly used cout methods:
<<: Prints a string to the console. It does not add a newline character at the end, so subsequent output will continue on the same line.
endlor\n: Used to add a line break in the output. Without these, all output will appear on the same line.
Here's how you can use these methods:
std::string name = "Alice";
int age = 30;Using endl:
cout << "Name: ";
cout << name;
cout << " is " << age << " years old." << endl;
cout << "Hello, " << name << "!" << endl;
// Output:
// Name: Alice is 30 years old.
// Hello, Alice!Using \n:
cout << "Name: " << name << "\n";
cout << "Age: " << age << "\n";
cout << "Hello, " << name << "!\n";
// Output:
// Name: Alice
// Age: 30
// Hello, Alice!Challenge
BeginnerWrite a C++ program that uses cout methods to output the following:
The starter code already prints "Hello, ". Add code below to print "Coddy!" so that both appear on the same line.
Cheat sheet
In C++, use cout with the << operator to print output to the console:
cout << "Hello World!";Use endl or \n to add line breaks:
cout << "First line" << endl;
cout << "Second line\n";Chain multiple outputs with <<:
std::string name = "Alice";
int age = 30;
cout << "Name: " << name << " is " << age << " years old." << endl;Try it yourself
#include <iostream>
int main() {
std::cout << "Hello, ";
// Write your code below
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - Else