Back to Course

Introduction to C++

0% Complete
0/0 Steps
  1. C++: Basics
    6 Quizzes
  2. C++: Compilation and Execution
    6 Quizzes
  3. C++: Variables
    10 Quizzes
  4. C++: Conditions Operators
    6 Quizzes
  5. C++: Logical Operators
    4 Quizzes
  6. C++: Loops and Errors
    9 Quizzes
  7. C++: Vectors
    3 Quizzes
Lesson 3, Topic 6
In Progress

C++: Chaining

Yasin Cakal 6 Nov 2021
Lesson Progress
0% Complete

Now that we have learned to create multiple output statements, let’s learn to output multiple things in a single statement. In the last code, we outputted marks using the statement std::court<<marks;.

Note that we used quotation marks when printing the phrase Hello, World! on the screen but we missed the quotation marks here. Quotation marks are used when you have to print the output of a literal sentence, phrase, or sequence of characters like in Hello, World!. Quotation marks are eliminated when you have to print the assigned value of a variable type or something similar.

Hence, we can use multiple couts in one sentence to avoid having to create multiple statements. This is called chaining. Multiple << are with the following statement to chain these outputs. Let’s try in the following code:

#include <iostream>

int main()
    int age=21;
    std::cout<<"How old is Andy?\n"<<"Andy is "<<age<<" years old.";
    return 0;


How old is Andy?
Andy is 21 years old.

As observed above, we didn’t even have to use separate statements for creating separate lines in the output. Let’s understand what we did in the code above:

  • an int type variable age was declared and assigned the value of 21.
  • A character output stream was created and the statement How old is Andy?\n was added in the quotation marks. \n was added with it to add a new line.
  • It was chained using << and the literal character sequence Andy is was added. Note that a space was added after is in the statement so that the age variable has a space between is and the value.
  • Next statement years old. was chained to complete the sentence in the output and ended with a ;.


Leave a Reply

%d bloggers like this: