Printing Output:

The cout object alongwith insertion operator (<<) is used to print the text on the screen.


Insertion Operator = "<<"

Note : cout is pronounced as "see-out".


If you want to print anything on screen you have to write cout, then insertion operator, then your text in double quotation marks in the main function.

output.cpp
#include <iostream>
using namespace std;

int main() {
    cout<<"Hi there!";
    return 0;
}


Note : Do not forget to put ; at the end.



Adding line breaks:

  • \n moves the cursor to the next line. It is used inside the quotation marks.

  • output.cpp
    #include <iostream>
    using namespace std;
    
    int main() {
        cout<<"Hi there!\n";
        cout<<"My name is John Smith.";
        return 0;
    }

  • endl manipulator is also used to add line breaks. It is used outside the quotation marks.

  • output.cpp
    #include <iostream>
    using namespace std;
    
    int main() {
        cout<<"Hi there."<<endl;
        cout<<"My name is John Smith.";
        return 0;
    }


    Different Escape Sequences:

    Escape SequenceDescriptionCode
    \nNew line
    cout<<"\n";
    \tTab - prints four spaces
    cout<<"\t";
    \aBeep sound
    cout<<"\a";
    \bBackspace
    cout<<"\b";
    \fForm feed
    cout<<"\f";
    \rCarriage return
    cout<<"\r";
    \\It adds backslash
    cout<<"\\";
    \'Single quote
    cout<<"\'";
    \?Question mark
    cout<<"\?";
    \0Null character
    cout<<"\0";

    Printing Numbers:

    If we want to print numbers in C++, we store them in variables then print variables on screen. We will discuss about this in detail in variable section. Here is a brief description.

    output.cpp
    #include <iostream>
    using namespace std;
    
    int main() {
        num = 10;
        cout<<num;
        return 0;
    }

    Note : If we write numbers in double quotes, these are not treated as numbers. Everything inside double quotation marks is a string literal which is text. Numbers are outside double qoutes.


    Printing Different type of Variables:

    If you want to print data stored in a variable, write the name of the variable with cout<< without quotation marks.

    output.cpp
    #include <iostream>
    using namespace std;
    int main(){
      int marks = 90;
      string name = "Ali";
      char grade = 'A';
      float per = 90.8;
    
      cout << "Marks are "<< marks << endl;
      cout << "Name is "<< name << endl;
      cout << "Grade is "<< grade << endl;
      cout << "Percentage is "<< per << endl;
    
      return 0;
    }
    We will study in detail in variable section that how can we take input in a variable and how to print its value in screen. For now just go through it.