C + + BASIC INPUT/O UTPUT
The C++ standard libraries provide an extensive set of input/output capabilities which
we will see in subsequent chapters. This chapter will discuss very basic and most
common I/O operations required for C++ programming.
C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device
like a keyboard, a disk drive, or a network connection etc. to main memory, this is
called input operation and if bytes flow from main memory to a device like a
display screen, a printer, a disk drive, or a network connection, etc, this is called
output operation.
I/O Library Header Files:
There are following header files important to C++ programs:
Header File Function and Description
<iostream> This file defines the cin, cout, cerr and clog objects, which correspond to
the standard input stream, the standard output stream, the un-buffered
standard error stream and the buffered standard error stream, respectively.
<iomanip> This file declares services useful for performing formatted I/O with so-called
parameterized stream manipulators, such as setw and setprecision.
<fstream> This file declares services for user-controlled file processing. We will discuss
about it in detail in File and Stream related chapter.
The standard output stream cout:
The predefined object cout is an instance of ostream class. The cout object is said to be
"connected to" the standard output device, which usually is the display screen. The cout is used in
conjunction with the stream insertion operator, which is written as << which are two less than
signs as shown in the following example.
#include <iostream >
using nam espace std;
int m ain( )
{
char str[] = "Hello C++";
cout << "Value of str is : " << str << endl;
}
When the above code is compiled and executed, it produces the following result:
Value of str is : Hello C++
The C++ compiler also determines the data type of variable to be output and selects the
appropriate stream insertion operator to display the value. The << operator is overloaded to
output data items of built-in types integer, float, double, strings and pointer values.
The insertion operator << may be used more than once in a single statement as shown above and
endl is used to add a new-line at the end of the line.
The standard input stream cin:
The predefined object cin is an instance of istream class. The cin object is said to be attached to
the standard input device, which usually is the keyboard. The cin is used in conjunction with the
stream extraction operator, which is written as >> which are two greater than signs as shown in
the following example.
#include <iostream >
using nam espace std;
int m ain( )
{
char nam e[50];
cout << "Please enter your nam e: ";
cin >> nam e;
cout << "Your nam e is: " << nam e << endl;
When the above code is compiled and executed, it will prompt you to enter a name. You enter a
value and then hit enter to see the result something as follows:
Please enter your nam e: cplusplus
Your nam e is: cplusplus
The C++ compiler also determines the data type of the entered value and selects the appropriate
stream extraction operator to extract the value and store it in the given variables.
The stream extraction operator >> may be used more than once in a single statement. To request
more than one datum you can use the following:
cin >> nam e >> age;
This will be equivalent to the following two statements:
cin >> nam e;
cin >> age;
The standard error stream cerr:
The predefined object cerr is an instance of ostream class. The cerr object is said to be attached
to the standard error device, which is also a display screen but the object cerr is un-buffered and
each stream insertion to cerr causes its output to appear immediately.
The cerr is also used in conjunction with the stream insertion operator as shown in the following
example.
#include <iostream >
using nam espace std;
int m ain( )
{
char str[] = "Unable to read....";
cerr << "Error m essage : " << str << endl;
}
When the above code is compiled and executed, it produces the following result:
Error m essage : Unable to read....
The standard log stream clog:
The predefined object clog is an instance of ostream class. The clog object is said to be attached
to the standard error device, which is also a display screen but the object clog is buffered. This
means that each insertion to clog could cause its output to be held in a buffer until the buffer is
filled or until the buffer is flushed.
The clog is also used in conjunction with the stream insertion operator as shown in the following
example.
#include <iostream >
using nam espace std;
int m ain( )
{
char str[] = "Unable to read....";
clog << "Error m essage : " << str << endl;
}
When the above code is compiled and executed, it produces the following result:
Error m essage : Unable to read....
You would not be able to see any difference in cout, cerr and clog with these small
examples, but while writing and executing big programs then difference becomes
obvious. So this is good
Practice to display error messages using cerr stream and while displaying other log
messages then clog should be used.
C ++ FUNCTIO NS
A function is a group of statements that together perform a task. Every C++ program has at
least one function, which is main, and all the most trivial programs can define additional
functions.
You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division usually is so each function performs a
specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
The C++ standard library provides numerous built-in functions that your program can call. For
example, function strcat to concatenate two strings, function memcpy to copy one memory
location to another location and many more functions.
A function is knows as with various names like a method or a sub-routine or a procedure etc.
Defining a Function:
The general form of a C++ function definition is as follows:
return_type function_nam e( param eter list )
{
body of the function
}
A C++ function definition consists of a function header and a function body. Here are all the parts
of a function:
Return Type: A function may return a value. The return_type is the data type of the value
the function returns. Some functions perform the desired operations without returning a
value. In this case, the return_type is the keyword void.
Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value
to the parameter. This value is referred to as actual parameter or argument. The parameter
list refers to the type, order, and number of the parameters of a function. Parameters are
optional; that is, a function may contain no parameters.
Function Body: The function body contains a collection of statements that define what the
function does.
Example:
Following is the source code for a function called max. This function takes two parameters num1
and num2 and returns the maximum between the two:
// function returning the m ax between two num bers
int m ax(int num 1, int num 2)
{
// local variable declaration
int result;
if (num 1 > num 2)
result = num 1;
else
result = num 2;
return result;
}
Function Declarations:
A function declaration tells the compiler about a function name and how to call the function. The
actual body of the function can be defined separately.
A function declaration has the following parts:
return_type function_nam e( param eter list );
For the above defined function max, following is the function declaration:
int m ax(int num 1, int num 2);
Parameter names are not importan in function declaration only their type is required, so following
is also valid declaration:
int m ax(int, int);
Function declaration is required when you define a function in one source file and you call that
function in another file. In such case, you should declare the function at the top of the file calling
the function.
Calling a Function:
While creating a C++ function, you give a definition of what the function has to do. To use a
function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A called
function performs defined task and when its return statement is executed or when its function-
ending closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and
if function returns a value, then you can store returned value. For example:
#include <iostream >
using nam espace std;
// function declaration
int m ax(int num 1, int num 2);
int m ain ()
{
// local variable declaration:
int a = 100;
int b = 200;
int ret;
// calling a function to get m ax value.
ret = m ax(a, b);
cout << "Max value is : " << ret << endl;
return 0;
}
// function returning the m ax between two num bers
int m ax(int num 1, int num 2)
{
// local variable declaration
int result;
if (num 1 > num 2)
result = num 1;
else
result = num 2;
return result;
}
I kept max function along with main function and compiled the source code. While running final
executable, it would produce the following result:
Max value is : 200
Function Arguments:
If a function is to use arguments, it must declare variables that accept the values of the arguments.
These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon
entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:
Call Type Description
This method copies the actual value of an argument into the
Callbyvalue formal parameter of the function. In this case, changes made to
the parameter inside the function have no effect on the argument.
This method copies the address of an argument into the formal
Callbypointer parameter. Inside the function, the address is used to access the
actual argument used in the call. This means that changes made
to the parameter affect the argument.
This method copies the reference of an argument into the formal
Callbyreference parameter. Inside the function, the reference is used to access the
actual argument used in the call. This means that changes made
to the parameter affect the argument.
By default, C++ uses call by value to pass arguments. In general, this means that code within a
function cannot alter the arguments used to call the function and above mentioned example while
calling max function used the same method.
Default Values for Parameters:
When you define a function, you can specify a default value for each of the last parameters. This
value will be used if the corresponding argument is left blank when calling to the function.
This is done by using the assignment operator and assigning values for the arguments in the
function definition. If a value for that parameter is not passed when the function is called, the
default given value is used, but if a value is specified, this default value is ignored and the passed
value is used instead. Consider the following example:
#include <iostream >
using nam espace std;
int sum (int a, int b=20)
{
int result;
result = a + b;
return (result);
}
int m ain ()
{
// local variable declaration:
int a = 100;
int b = 200;
int result;
// calling a function to add the values.
result = sum (a, b);
cout << "Total value is :" << result << endl;
// calling a function again as follows.
result = sum (a);
cout << "Total value is :" << result << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Total value is :300
Total value is :120
C ++ PO INTERS
C++ pointers are easy and fun to learn. Some C++ tasks are performed more easily
with pointers, and other C++ tasks, such as dynamic memory allocation, cannot be
performed without them.
As you know every variable is a memory location and every memory location has
its address defined which can be accessed using ampersand & operator which
denotes an address in memory. Consider the following which will print the
address of the variables defined:
#include <iostream >
using nam espace std;
int m ain ()
{
int var1;
char var2[10];
cout << "Address of var1 variable: ";
cout << &var1 << endl;
cout << "Address of var2 variable: ";
cout << &var2 << endl;
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Address of var1 variable: 0xbfebd5c0
Address of var2 variable: 0xbfebd5b6
What Are Pointers?
A pointer is a variable whose value is the address of another variable. Like any variable or
constant, you must declare a pointer before you can work with it. The general form of a pointer
variable declaration is:
type * var-nam e;
Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of
the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use
for multiplication. However, in this statement the asterisk is being used to designate a variable as a
pointer. Following are the valid pointer declaration:
int * ip; // pointer to an integer
double * dp; // pointer to a double
float * fp; // pointer to a float
char * ch // pointer to character
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is
the same, a long hexadecimal number that represents a memory address. The only difference
between pointers of different data types is the data type of the variable or constant that the
pointer points to.
Using Pointers in C++:
There are few important operations, which we will do with the pointers very frequently. a we define
a pointer variables b assign the address of a variable to a pointer and c finally access the value at
the address available in the pointer variable. This is done by using unary operator * that returns
the value of the variable located at the address specified by its operand. Following example makes
use of these operations:
#include <iostream >
using nam espace std;
int m ain ()
{
int var = 20; // actual variable declaration.
int * ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;
// access the value at the address available in pointer
cout << "Value of * ip variable: ";
cout << * ip << endl;
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of * ip variable: 20
C++ Pointers in Detail:
Pointers have many but easy concepts and they are very important to C++ programming. There
are following few important pointer concepts which should be clear to a C++ programmer:
Concept Description
C++ supports null pointer, which is a constant with a
C++NullPointers value of zero defined in several standard libraries.
There are four arithmetic operators that can be used on
C++pointerarithmetic pointers: ++, --, +, -
There is a close relationship between pointers and
C++pointersvsarrays arrays. Let us check how?
You can define arrays to hold a number of pointers.
C++arrayofpointers
C++ allows you to have pointer on a pointer and so on.
C++pointertopointer
Passing an argument by reference or by address both
Passingpointerstofunctions enable the passed argument to be changed in the
calling function by the called function.
C++ allows a function to return a pointer to local
Returnpointerfromfunctions variable, static variable and dynamically allocated
memory as well.
C ++ IF...ELSE STATEMENT
An if statement can be followed by an optional else statement, which executes when
the boolean expression is false.
Syntax:
The syntax of an if...else statement in C++ is:
if(boolean_expression)
{
// statem ent(s) will execute if the boolean expression is true
}
else
{
// statem ent(s) will execute if the boolean expression is false
}
If the boolean expression evaluates to true, then the if block of code will be executed, otherwise
else block of code will be executed.
Flow Diagram:
Example:
#include <iostream >
using nam espace std;
int m ain ()
{
// local variable declaration:
int a = 100;
// check the boolean condition
if( a < 20 )
{
// if condition is true then print the following
cout << "a is less than 20;" << endl;
}
else
{
// if condition is false then print the following
cout << "a is not less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
a is not less than 20;
value of a is : 100
The if...else if...else Statement:
An if statement can be followed by an optional else if...else statement, which is
very usefull to test various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind.
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of he remaining else if's or else's will be tested.
Syntax:
The syntax of an if...else if...else statement in C++ is:
if(boolean_expression 1)
{
// Executes when the boolean expression 1 is true
}
else if( boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
else if( boolean_expression 3)
{
// Executes when the boolean expression 3 is true
}
else
{
// executes when the none of the above condition is true.
}
Example:
#include <iostream >
using nam espace std;
int m ain ()
{
// local variable declaration:
int a = 100;
// check the boolean condition
if( a == 10 )
{
// if condition is true then print the following
cout << "Value of a is 10" << endl;
}
else if( a == 20 )
{
// if else if condition is true
cout << "Value of a is 20" << endl;
}
else if( a == 30 )
{
// if else if condition is true
cout << "Value of a is 30" << endl;
}
else
{
// if none of the conditions is true
cout << "Value of a is not m atching" << endl;
}
cout << "Exact value of a is : " << a << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of a is not m atching
Exact value of a is : 100
C ++ L OOP TYPES
There may be a situation, when you need to execute a block of code several number
of times. In general statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements
multiple times and following is the general from of a loop statement in most of the
programming languages:
C++ programming language provides the following types of loop to handle looping requirements.
Click the following links to check their detail.
Loop Type Description
Repeats a statement or group of statements while a given
whileloop condition is true. It tests the condition before executing the loop
body.
Execute a sequence of statements multiple times and abbreviates
for loop the code that manages the loop variable.
Like a while statement, except that it tests the condition at the end
do...whileloop of the loop body
You can use one or more loop inside any another while, for or
nestedloops do..while loop.
Loop Control Statements:
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
C++ supports the following control statements. Click the following links to check their detail.
Control Statement Description
Terminates the loop or switch statement and transfers execution
breakstatement to the statement immediately following the loop or switch.
Causes the loop to skip the remainder of its body and immediately
continuestatement retest its condition prior to reiterating.
Transfers control to the labeled statement. Though it is not
gotostatement advised to use goto statement in your program.
The Infinite Loop:
A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used
for this purpose. Since none of the three expressions that form the for loop are required, you can
make an endless loop by leaving the conditional expression empty.
#include <iostream >
using nam espace std;
int m ain ()
{
for( ; ; )
{
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an initialization
and increment expression, but C++ programmers more commonly use the for; ; construct to
signify an infinite loop.
NOTE: You can terminate an infinite loop by pressing Ctrl + C keys.