Pages

Friday, February 4, 2011

Output in C++

Output

cout - is used to do output data to your console.


Syntax for printf:

cout<< data here;

Data
Data can be information such as non-numeric (For example a single character which is delimited by ' or a string as a series of characters which is delimited by " ) or numeric (For example integer for a whole number or a float for any number that may contain a decimal value). Sometimes these data are represented by a variable. Variables are some kind of storage of data.


Sample program:

#include<iostream>
using namespace std;

int main ( )
{
   cout<<"Hello my friend stay awhile and listen";
   return 0;
}

Tips:

1. ) Data can be repeatedly added to your output using the insertion operator ( << ).

2.) You can use spaces such as space or a tab for indention for the purpose of readability

3.) You may also use some escape character such as \t for tab or \n for new line.

     Tabs are used for indention
     New lines are use for moving your cursor to point to the next line.

More Sample Program

#include <iostream>
using namespace std;

int main ( )
{
  cout<<"Welcome\tWorld\n"                                //Welcome and World are separated by a tab
        <<"Timon\tand\tpombaba\n";                     //timon and pombaba inserted using <<
  cout<<"I have "<<2<<" hands \n";                               
  cout<<"The first letter in the alphabet is "<<'a'<<"\n" ); 
  cout<<"My name is James Pooker";    //a, 2 is inserted using <<
  getch ( );
  return 0;
}

Notes:
     Recall that // is a single line comment and notice that each printf has a \n inside. So it is clear that after it displays the data inside each cout, the cursor moves to the next line to print another data from a cout command. This \n can be replace by endl (end of line) but it should not be included inside the ". Use the insertion operator instead.
    Notice also for the line of codes of 6 and 7, that as long as the statement is not terminated, the computer continue to read this that it belongs to the command that still not terminated ( cout for this example ). instead of using another cout command, you may just use one cout and just insert data using the insertion operator ( << ).

Output:
Welcome  World
Timon       and     pombaba
I have 2 hands
The first letter in the alphabet is a
My name is James Pooker

No comments:

Post a Comment