http://KVSeContents.in http://eTeacher.KVSeContents.in
eBook:
XI-XII Computer Science
C++ and Database/Mysql
Click here to check the revised version of these notes
Review Version
(Last reviewed on 05-02-2016)
New Modification(s) is/are:
1 AISSCE 2015 papers with solution added.
Please send your feedback with:
SANJEEV SHARMA
PGT (CS) Kendriya Vidyalaya
Palampur Himachal – INDIA
[email protected]
+919418133050
All material is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported
License unless mentioned otherwise.
Page 1 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Index
Topic PPage NO
XI – COMPUTER SCIENCE UNIT – III C++ 3
XI – COMPUTER SCIENCE UNIT – IV C++ 19
XII – COMPUTER SCIENCE UNIT – I C++ 87
XII – COMPUTER SCIENCE UNIT – II C++ 147
XII – COMPUTER SCIENCE UNIT – III 184
DATABASE 220
AISSCE 2015 question papers and
solution
Click here to download the syllabus for the session 2015-16
Page 2 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
XI – COMPUTER SCIENCE UNIT –III C++
Page 3 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Introduction to C++
C++ is a general purpose programming language invented
in the early 1980s by Bjarne Stroustrup at Bell Labs.
In fact C++ was originally called C with Classes and is
so compatible with C that it will probably compile more
than 99% of C programs without changing a line of
source code.
How do I get started with C++?
First you need a C++ compiler. There are many
commercial and free ones available. All compilers
listed below are completely free and include an IDE for
you to edit, compile and debug your program.
Download and Install Borland's Turbo C++ Compiler.
Download and Install Bloodshed Dev C++ Open source
Compiler
click here to see the Instructions for Downloading and
Installing Borland C++ Compiler 5.5
C++ character set
C++ is a case sensitive language means C++ treats a-z
different from A-Z i.e in C++ "ram" is different from
"RAM".Most of the programming in C++ is done with small
alphabets i.e a-z.
The following chart contains all 128 ASCII
decimal (dec), octal (oct), hexadecimal (hex) and
character (ch) codes of C++ supported characters
Page 4 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
C++ keywords
Chart of reserved keywords in C++. Since they are used
by the language, these keywords are not available for
re-definition.
Identifiers
The name of a variable (or other item you might define
in a program) is called an identifier. A C++ identifier
must start with either a letter or the underscore
symbol, and all the rest of the characters must be
letters, digits, or the underscore symbol. Some of the
valid and Invalid identifiers of c++ are
Page 5 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Literals/Constants in C++
Invalid Identifiers
MY Name
1MY
%my
Valid Identifiers
MY_NAME
MY1
_my
Literals are the most obvious kind of constants. They
are used to express particular values within the source
code of a program. when we wrote:
a = 5;
the 5 in this piece of code was a literal constant.
Literal constants can be divided in Integer
Numerals, Floating-Point
Numerals, Characters, Strings and Boolean Values.
integer-constant
character-constant
floating-constant
string-literal
Boolean-literal
Examples of different
157 // integer constant
'A' // character constant
0.2 // floating constant
0.2E-01 // floating constant
"Ayan" // string literal
There are only two valid Boolean values: true and false.
These can be expressed in C++ as values of type bool by
using the Boolean literals true and false.
Page 6 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Escape Characters in C++
Chart of C++ Escape Characters Set
Structure of a C++ Program
Probably the best way to start learning a programming
language is with a program. So here is our first
program:
// my first program in C++
#include <iostream.h>
int main ()
{
cout << "Hello World!";
return 0;
}
Output :Hello World!
The previous program is the first program that most
programming apprentices write, and its result is the
printing on screen of the "Hello World!" sentence.We
are going to take a look at them one by one:
// my first program in C++
This is a comment line. All the lines beginning with
two slash signs (//) are considered comments and do not
have any effect on the behavior of the program. They
Page 7 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
can be used by the programmer to include short
explanations or observations within the source itself.
#include <iostream.h>
Sentences that begin with a pound sign (#) are
directives for the preprocessor. They are not
executable code lines but indications for the compiler.
In this case the sentence #include <iostream.h> tells
the compiler's preprocessor to include the iostream
standard header file. This specific file includes the
declarations of the basic standard input-output library
in C++, and it is included because its functionality is
used later in the program.
int main ()
This line corresponds to the beginning of the main
function declaration. The main function is the point
where all C++ programs begin their execution. It is
independent of whether it is at the beginning, at the
end or in the middle of the code - its content is
always the first to be executed when a program starts.
In addition, for that same reason, it is essential that
all C++ programs have a main function.
main is followed by a pair of parenthesis () because it
is a function. In C++ all functions are followed by a
pair of parenthesis () that, optionally, can include
arguments within them. The content of the main function
immediately follows its formal declaration and it is
enclosed between curly brackets ({}), as in our
example.
cout << "Hello World";
This instruction does the most important thing in this
program. cout is the standard output stream in C++
(usually the screen), and the full sentence inserts a
sequence of characters (in this case "Hello World")
into this output stream (the screen). cout is declared
in the iostream.h header file, so in order to be able
to use it that file must be included.
Page 8 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Notice that the sentence ends with a semicolon
character (;). This character signifies the end of the
instruction and must be included after every
instruction in any C++ program (one of the most common
errors of students is indeed to forget to include a
semicolon ; at the end of each instruction).
Return; 0;
The return instruction causes the main() function
finish and return the code that the instruction is
followed by, in this case 0. This it is most usual way
to terminate a program that has not found any errors
during its execution. As you will see in coming
examples, all C++ programs end with a sentence similar
to this.
Therefore, you may have noticed that not all the lines
of this program did an action. There were lines
containing only comments (those beginning by //), lines
with instructions for the compiler's preprocessor
(those beginning by #), then there were lines that
initiated the declaration of a function (in this case,
the main function) and, finally lines with instructions
(like the call to cout <<), these last ones were all
included within the block delimited by the curly
brackets ({}) of the main function.
The program has been structured in different lines in
order to be more readable, but it is not compulsory to
do so. For example, instead of
#include <iostream.h>
int main ()
{
cout << " Hello World ";
return 0;
}
We can write:
int main () { cout << " Hello World "; return 0; }
Page 9 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
in just one line and this would have had exactly the
same meaning.
In C++ the separation between instructions is specified
with an ending semicolon (;) after each one. The
division of code in different lines serves only to make
it more legible and schematic for humans that may read
it.
Here is a program with some more instructions:
// my second program in C++
#include <iostream.h>
int main ()
{
cout << "Hello World! ";
cout << "I'm a C++ program";
return 0;
}
Output : Hello World! I'm a C++ program
In this case we used the cout << method twice in two
different instructions. Once again, the separation in
different lines of the code has just been done to give
greater readability to the program, since main could
have been perfectly defined thus:
int main () { cout << " Hello World! "; cout << " I'm
to C++ program "; return 0; }
We were also free to divide the code into more lines if
we considered it convenient:
#include <iostream.h>
int main ()
{ cout <<"Hello World!";
cout<< "I'm a C++ program";
return 0;
}
Page 10 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
And the result would have been exactly the same than in
the previous examples.
Preprocessor directives (those that begin by #) are out
of this rule since they are not true instructions. They
are lines read and discarded by the preprocessor and do
not produce any code. These must be specified in their
own line and do not require the include a semicolon (;)
at the end.
Comments.
Comments are pieces of source code discarded from the
code by the compiler. They do nothing. Their purpose is
only to allow the programmer to insert notes or
descriptions embedded within the source code.
C++ supports two ways to insert comments:
// line comment
/* block comment */
The first of them, the line comment, discards
everything from where the pair of slash signs (//) is
found up to the end of that same line. The second one,
the block comment, discards everything between the /*
characters and the next appearance of the */
characters, with the possibility of including several
lines.
We are going to add comments to our second program:
/* my second program in C++ with more comments */
#include <iostream.h>
int main ()
{
cout << "Hello World! "; // says Hello World!
cout << "I'm a C++ program"; // says I'm a C++ program
return 0;
}
Output :Hello World! I'm a C++ program
Page 11 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
If you include comments within the source-code of your
programs without using the comment characters
combinations //, /* or */, the compiler will take them
as if they were C++ instructions and, most likely
causing one or several error messages.
Compilation Process of a C++ Program
Turbo C++ Compiler Shortcut Keys
F9 :Compile Only
Ctrl F9 :Compile & run
Alt F5 :To see Output Screen
F2 :Save the File
Alt X :Exit Turbo C++
F3 :Load File
Alt F3 :Pick File from List
Page 12 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Concept of Data Types
Data types are means to identify the type of data and
associated operations of handling it. C++ provides a
predefined set of data types for handling the data it
uses. When variables are declared of a particular data
type then the variable becomes the place where the data
is stored and data types is the type of value(data)
stored by that variable. Data can be of may types such
as character, integer, float etc.
Variable in C++
Variables are memory locations to store data of a
program. Whenever we want to accept a data (as input to
your program) or store some temporary data, we would
likely to store that data into a temporary memory
location (or variable).Variable must first be declared
before it can be used.
Once a variable is declared, we are telling the
compiler the name of the variable, the initial value of
the variable (optional) and the type of data our
variable can hold.
The name of the variable must be a valid identifier.
The following image show that internal structure of a
typical C++ variable inside the RAM(Random Access
Memory)
Page 13 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Variable Declaration in C++:
All variables must be declared before use. A
declaration specifies a type, and contains a list of
one or more variables of that type as follows:
type variable_name;
Here, type must be a valid C++ data type including
char, int, float, double or any user defined object
etc., and variable_name may consist of one or more
identifier names separated by commas. Some valid
declarations are shown here:
int i, j, k;
char c, ch;
float f, salary;
double d;
A variable declaration with an initializer is always a
definition. This means that storage is allocated for
the variable and could be declared as follows:
int i = 100;
Variable Initialization in C++:
Variables can be initialized (assigned an initial
value) in their declaration. The initializer consists
of an equal sign followed by a constant expression as
follows:
type variable_name = value;
Some examples are:
Page 14 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
int a = 3, b = 5; // initializing a and b.
byte c = 22; // initializes c.
double d = 12.3
// initializes d.
char z = 'x'; // the variable z has the value
'x'.
For declarations without an initializer: variables with
static storage duration are implicitly initialized with
0; the initial value of all other variables is
undefined.
Example of various types of variables:
#include <iostream.h>
int main ()
{
// Variable declaration:
int a, b;
int c;
float f;
// Initialization
a = 10;
b = 20;
c = a + b;
cout << c << endl ;
f = 12.0/2.0;
cout << f << endl ;
return 0;
}
Output:
30
6.0000
Lvalues and Rvalues
Variables are lvalues and may appear on the left-hand
side of an assignment. Numeric literals are rvalues and
may not be assigned and can not appear on the left-hand
side. Following is a valid statement:
int a = 2; // Here a is a Variable
Page 15 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
But following is not a valid statement and would
generate compile-time error:
1 = 2; // Left Hand Side has a Constant
Scope of Variables
A scope is a block of the program. There are three
places where variables can be declared:
Inside a function or a block which is called local
variables,
In the definition of function parameters which is
called formal parameters.
Outside of all functions which is called global
variables.
Local Variables:
Variables that are declared inside a function or block
are local variables. They can be used only by
statements that are inside that function or block of
code. Local variables are not known to functions
outside their own. Following is the example using local
variables:
#include <iostream.h>
int main ()
{
// Local variable :
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
Page 16 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Global Variables:
Global variables are defined outside of all the
functions, usually on top of the program. The global
variables will hold their value throughout the lifetime
of your program.
A global variable can be accessed by any function. That
is, a global variable is available for use throughout
your entire program after its declaration. Following is
the example using global and local variables:
#include <iostream.h>
// Global variable
int t;
int main ()
{
// Local variables
int a, b;
// Initialization
a = 10;
b = 20;
t = a + b;
cout << t;
return 0;
}
A program can have same name for local and global
variables but value of local variable inside a function
will take preference. For example:
#include <iostream.h>
// Global variable:
int t = 20;
int main ()
{
// Local variable with same name as Global variable
int t = 120;
cout << t;
return 0;
}
Page 17 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
When the above code is compiled and executed, it
produces following output:
120
Initializing Local and Global Variables:
When a local variable is defined, it is not initalised
by the system, we have to initalise it. Global
variables are initalised automatically by the system
when we define them as follows:
Data Type Initialser
int 0
char '\0'
float 0
double 0
pointer NULL
It is a good programming practice to initialize
variables properly otherwise, sometime program would
produce unexpected result.
Data Types Modifiers
1.signed
2.unsigned
3.short
4.long
Int, char, float, double data types can be preceded
with these modifiers to alter the meaning of the base
type to fit various situations properly. Every data
type has a limit of the larges and smallest value that
it can store known as the range. An integer (usually 2
bytes long) can store any value ranging from -32768 to
32767.
Data Type modifiers usually alter the upper and lower
limit of a data type. Unsigned modifier makes a
variable only to store positive values. For Example- if
a data type has a range from –a to a then unsigned
variable of that type has a range from 0 to 2a.
Preceding any data type with signed is optional because
every data type is signed by default. Short integers
are 2 bytes long and long integers are 4 bytes long.
Page 18 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
XI – COMPUTER SCIENCE UNIT –IV C++
Page 19 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Control Flow Statements
When a program runs, the CPU begins execution at
main(), executes some number of statements, and then
terminates at the end of main(). The sequence of
statements that the CPU executes is called the
program’s path. Straight-line programs have sequential
flow — that is, they take the same path (execute the
same statements) every time they are run (even if the
user input changes).
However, often this is not what we desire. For example,
if we ask the user to make a selection, and the user
enters an invalid choice, ideally we’d like to ask the
user to make another choice. This is not possible in a
straight-line program.
C++ provides control flow statements (also called flow
control statements), which allow the user to change the
CPU’s path through the program.
Different C++ flow control Statements
if statement
else if construct
switch statement
break statement
while loop
do while loop
for loop
if-else statement
if ( condition )
{
statement true;
}
else
{
statement false;
}
if-else statement example
Page 20 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
#include <iostream.h>
int main()
{
int a = -10;
if ( a > 0 )
{
cout << "a is a positive Integer";
}
else
{
cout << "a is a negative or zero";
}
return 0;
}
else-if construct
(else-if ladder)
if ( condition-1 )
{
statement; // condition-1 is true
}
else if ( condition-2 )
{
statement; // condition-2 is true
}
else if ( condition-3 )
Page 21 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
{
statement; // condition-3 is true
}
else
{
// default case:
statement; // all above conditions were false
}
else-if ladder example
#include <iostream.h>
int main()
{
int a = -10;
if ( a > 0 )
{
cout << "a is a positive integer";
}
else if ( a < 0 )
{
cout << "a is negative";
}
else
{
cout << "a is zero";
}
return 0;
}
Switch statement
The switch statement provides a alternative to the if
when dealing with a multi-way branch. Suppose we have
some integer value called test and want to do different
operations depending on whether it has the value 1, 5
or any other value, then the switch statement could be
employed:-
switch ( test expression ) {
case 1 :
Page 22 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
// Statements for test = 1
...
break;
case 5 :
// Statements for test = 5
...
break;
default :
// Statements for all other.
...
}
It works as follows
The expression, just test in this case, is evaluated.
The case labels are checked in turn for the one that
matches the value.
If none matches, and the optional default label exists,
it is selected, otherwise control passes from the
switch compound statement
If a matching label is found, execution proceeds from
there. Control then passes down through all remaining
labels within the switch statement. As this is normally
not what is wanted, the break statement is normally
added before the next case label to transfer control
out of the switch statement.
Switch Statement Example
#include <iostream.h>
int main()
{
cout << "Do you want to continue (y or n)?\n";
char ans = 0;
cin >> ans; // get ans from user
Page 23 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
switch ( ans )
{
case 'y':
cout<<"Your Ans is True";
break;
case 'n':
cout<<"Your Ans is False";
break;
default:
cout << "Wrong Input\n";
}
return 0;
}
Output :if user press 'y' than
it will display "Your Ans is true"
Switch Statement Consideration
case constants must be distinct
default is optional
cases and the default can occur in any order
break statement causes an immediate exit from the
switch
put a break after each case
Nested Switch Statement
It is possible to have a switch as part of the
statement sequence of an outer switch. Even if the case
Page 24 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
constants of the inner and outer switch contain common
values, no conflicts will arise.
Syntax:
The syntax for a nested switch statement is as follows:
switch(ch1) {
case 'A':
cout << "This A is part of outer switch";
switch(ch2) {
case 'A':
cout << "This A is part of inner switch";
break;
case 'B': // ...
}
break;
case 'B': // ...
}
Example of nested switch Statement
#include <iostream.h>
int main ()
{
// local variable declaration:
int a = 10;
int b = 20;
switch(a) {
case 10:
cout << "This is part of outer switch" << endl;
switch(b) {
case 20:
cout << "This is part of inner switch" << endl;
}
}
cout << "Exact value of a is : " << a << endl;
cout << "Exact value of b is : " << b << endl;
return 0;
}
Output:
This is part of outer switch
This is part of inner switch
Exact value of a is : 10
Exact value of b is : 20
Page 25 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Loops in C++
Loops have a purpose to repeat a statement a certain
number of times or while a condition is fulfilled.
Loops in C++ are mainly of three types :-
'while' loop
'do while' loop
'for' loop
The while loop
while (expression)
{ statement(s) };
and its functionality is simply to repeat statement
while the condition set in expression is true.For
example, we are going to make a program to countdown
using a while-loop:
// custom countdown using while
#include <iostream.h>
int main ()
{
int n;
cout << "Enter the starting number := ";
cin >> n;
while (n>0) {
cout << n << ", ";
--n;
}
cout << "Finished !\n";
return 0;
}
Page 26 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Enter the starting number := 8
8, 7, 6, 5, 4, 3, 2, 1, Finished!
When the program starts the user is prompted to insert
a starting number for the countdown. Then the while
loop begins, if the value entered by the user fulfills
the condition n>0 (that n is greater than zero) the
block that follows the condition will be executed and
repeated while the condition (n>0) remains being true.
The whole process of the previous program can be
interpreted according to the following script
(beginning in main):
User assigns a value to n
The while condition is checked (n>0). At this point
there are two possibilities:
*condition is true: This statement will be executed:
cout << n << ", "; --n;
*condition is false:This statement will be executed:
cout << "Finished!\n";return 0;
When creating a while-loop, we must always consider
that it has to end at some point, therefore we must
provide within the block some method to force the
condition to become false at some point, otherwise the
loop will continue looping forever. In this case we
have included --n; that decreases the value of the
variable that is being evaluated in the condition (n)
by one - this will eventually make the condition (n>0)
to become false after a certain number of loop
iterations: to be more specific, when n becomes 0, that
is where our while-loop and our countdown end.
The do-while loop
Its format is:
do
{
statement(s);
}while (condition);
Page 27 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Its functionality is exactly the same as the while
loop, except that condition in the do-while loop is
evaluated after the execution of statement instead of
before, granting at least one execution of statement
even if condition is never fulfilled.
For example, the following example program echoes any
number you enter until you enter 0.
Example of do-while loop
#include <iostream.h>
int main ()
{
long n;
do {
cout << "Enter any number (0 to end): ";
cin >> n;
cout << "You have entered: " << n << "\n";
} while (n != 0);
return 0;
}
Enter number (0 to end): 888
You entered: 888
Enter number (0 to end): 777
You entered: 777
Enter number (0 to end): 0
You entered: 0
The do-while loop is usually used when the condition
that has to determine the end of the loop is determined
within the loop statement itself, like in the previous
case, where the user input within the block is what is
used to determine if the loop has to end.
In fact if you never enter the value 0 in the previous
example you can be prompted for more numbers forever.
The for loop
Its format is:
for (initialization; condition; increase)
{
//statement;
}
Page 28 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
It works in the following way:
initialization is executed. Generally it is an initial
value setting for a counter variable. This is executed
only once.
condition is checked. If it is true the loop continues,
otherwise the loop ends and statement is skipped (not
executed).
statement is executed. As usual, it can be either a
single statement or a block enclosed in braces { }.
finally, whatever is specified in the increase field is
executed and the loop gets its execution again
Here is an example of countdown using a for loop:
Example using a for loop
#include <iostream.h>
int main ()
{
for (int n=5; n>0; n--)
{
cout << n << ", ";
}
cout << "Finished!\n";
return 0;
}
5, 4, 3, 2, 1, Finished!
The initialization and increase fields are optional.
They can remain empty, but in all cases the semicolon
signs between them must be written.
For example we could write: for (;n<10;) if we wanted
to specify no initialization and no increase; or for
Page 29 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
(;n<10;n++) if we wanted to include an increase field
but no initialization (maybe because the vriable was
already initialized before).
Optionally, using the comma operator (,) we can specify
more than one expression in any of the fields included
in a for loop, like in initialization, for example:
The comma operator (,) is an expression separator, it
serves to separate more than one expression where only
one is generally expected. For example, suppose that we
wanted to initialize more than one variable in our
loop:
for ( n=0, i=10 ; n!=i ; n++, i-- )
{
// Statements ;
}
This loop will execute for 5 times if neither n or i
are modified within the loop:
n starts with a value of 0, and i with 10, the
condition is n!=i (that n is not equal to i). Because n
is increased by one and i decreased by one, the loop's
condition will become false after the 5th loop, when
both n and i will be equal to 5.
Nested for Loop
The placing of one loop inside the body of another loop
is called nesting. When you "nest" two loops, the
outer loop takes control of the number of complete
repetitions of the inner loop.
Page 30 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Syntax:
The syntax for a nested for loop statement in C++ is as
follows:
for ( initialisation; condition; increment )
{
for ( initialisation; condition; increment )
{
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C++ is
as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C+
+ is as follows:
do
{
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );
The following program uses a nested for loop to find
the prime numbers from 2 to 50:
Page 31 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
#include <iostream.h>
int main ()
{
int i, j;
for(i=2; i<50; i++)
{
for(j=2; j <= (i/j); j++)
if(!(i%j))
break; //if not prime
if(j > (i/j))
cout << i << " is prime\n";
}
return 0;
}
Page 32 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
List of Some Commonly used inbuilt Functions in C++
Standard input/output functions
stdio.h
gets (), puts ()
Character Functions
ctype.h
isalnum (), isalpha (),isdigit (), islower (),isupper
(), tolower (),toupper ()
String Functions
string.h
strcpy (), strcat (),strlen (), strcmp (),strcmpi (),
strrev (),strlen (), strupr (),strlwr ()
iomanip.h
setw(),
Mathematical Functions
math.h
abs (), pow (), sgrt (),sin (), cos (), abs ()
Other Functions
stdlib.h
randomize (), random (),itoa (), atoi ()
Using Library Functions
Header File :ctype.h
int isalnum(int c);
Description:
The function returns nonzero if c is any of:
Page 33 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
o123456789
Return Value
The function returns nonzero if c is alphanumeric
otherwise this will return zero which will be
equivalent to false.
Example
#include <iostream.h>
#include<ctype.h>
int main() {
if( isalnum( '#' ) )
{
cout<< "Character # is not alphanumeric\n" ;
}
if( isalnum( 'A' ) )
{
cout<< "Character A is alphanumeric\n" ;
}
return 0;
}
It will produce following result:
Character A is alphanumeric
int isalpha(int c);
Description:
The function returns nonzero if c is any of:
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Return Value
The function returns nonzero if c is just alpha
otherwise this will return zero which will be
equivalent to false.
Example
#include <iostream.h>
#include<ctype.h>
int main() {
if( isalpha( '1' ) )
Page 34 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
{
cout<< "Character 1 is not alpha\n" ;
}
if( isalpha( 'A' ) )
{
cout<< "Character A is alpha\n";
}
return 0;
}
It will produce following result:
Character A is alpha
int isdigit(int c);
Description:
The function returns nonzero if c is any of:
0123456789
Return Value
The function returns nonzero if c is a digit otherwise
this will return zero which will be equivalent to
false.
Example
#include <iostream.h>
#include<ctype.h>
int main() {
if( isdigit( '1' ) )
{
cout<< "Character 1 is a digit\n" ;
}
if( isdigit( 'A' ) )
{
cout<< "Character A is digit\n" ;
}
return 0;
}
It will produce following result:
Character 1 is a digit
int islower(int c);
Description:
Page 35 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
The function returns nonzero if c is any of:
abcdefghijklmnopqrstuvwxyz
Return Value
The function returns nonzero if c is lower case
otherwise this will return zero which will be
equivalent to false.
Example
#include <iostream.h>
#include<ctype.h>
int main() {
if( islower( 'a' ) )
{
cout<<"Character a is lower case\n";
}
if( islower( 'A' ) )
{
cout<< "Character A is lower case\n";
}
return 0;
}
It will produce following result:
Character a is lower case
int isupper(int c);
Description:
The function returns nonzero if c is any of:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Return Value
The function returns nonzero if c is upper case
otherwise this will return zero which will be
equivalent to false.
Example
#include <iostream.h>
#include<ctype.h>
int main() {
if( isupper( 'a' ) )
{
Page 36 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
cout<< "Character a is upper case\n" ;
}
if( isupper( 'A' ) )
{
cout<<"Character A is upper case\n";
}
return 0;
}
It will produce following result:
Character A is upper case
int tolower(int c);
Description:
The function returns the corresponding lowercase
letter.
Example
#include <iostream.h>
#include<ctype.h>
int main() {
cout<< "Lower case of T is \n"<<tolower('T');
return 0;
}
It will produce following result:
Lower case of T is t
int toupper(int c);
Description:
The function returns the corresponding uppercase
letter.
Example
#include <iostream.h>
#include<ctype.h>
int main() {
cout<< "Upper case of t is \n"<<toupper('t');
return 0;
}
It will produce following result:
Upper case of t is T
Page 37 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
C++ Library Functions Header File :string.h
char *strcpy (char *dest, char *src);
Description:
The strcpy function copies characters from src to dest
including the terminating null character.
Return Value
The strcpy function returns dest.
Example
#include <iostream.h>
#include <string.h>
int main() {
char src[20];
char dest[20];
strcpy(src, "Hello");
strcpy(dest, src");
// Will copy the contents from src array to dest array
cout<<"dest ="<<dest;
return 0;
}
It will produce following result:
dest = Hello
char *strcat(char *dest, const char *src);
Description:
The strcat function concatenates or appends src to
dest. All characters from src are copied including the
terminating null character.
Return Value
The strcat function returns dest. Example
Page 38 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
#include <string.h>
#include <iostream.h>
int main()
{
char src[20]; char
dest[20]; strcpy(src,
"Ayan"); strcpy(dest,
"Sharma");
cout<<"Concatenated String = \n"<<strcat(src,dest);
return 0;
}
It will produce following result:
Concatenated String = AyanSharma
int strlen(char *src );
Description:
The strlen function calculates the length, in bytes, of
src. This calculation does not include the null
terminating character.
Example
#include <string.h>
#include <iostream.h>
int main()
{
char src[20];
strcpy(src, "Ambari");
cout<<"Length of string :"<<src<< " is "<<strlen(src );
return 0;
}
It will proiduce following result:
Page 39 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Length of string Ambari is 6
[email protected]
<[email protected]>;
int strcmp(char *string1, char *string2);
Description: the contents of string1
The strcmp function compares value indicating their
and string2 and returns a
relationship.
Return Value
if Return value if < 0 then it indicates string1 is
less than string2
if Return value if > 0 then it indicates string2 is
less than string1
if Return value if = 0 then it indicates string1 is
equal to string1
Example
#include <string.h>
#include <iostream.h>
int main()
{
char one[20]; char
two[20]; strcpy(one,
"Ayan"); strcpy(two,
"Sharma");
cout<<"Return Value is : \n"<<strcmp( one, two);
strcpy(one, "Sharma");
strcpy(two, "Ayan");
cout<<"Return Value is : \n"<<strcmp( one, two);
strcpy(one, "Ayan");
strcpy(two, "Ayan");
Page 40 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
cout<<"Return Value is : \n"<<strcmp( one, two);
return 0;
}
It will produce following result:
Return Value is : -18
Return Value is : 18
Return Value is : 0
Declaration: char *strupr(char *s);
Description:
strupr convert lowercase letters (a to z) in string s
to uppercase (A to Z).
#include <iostream.h>
#include <string.h>
int main(void)
{
char *s = "abcde";
/* converts string to upper case characters */
cout<<endl<<s;
return 0;
}
Output
ABCDE
Declaration: char *strrev(char *s);
Description:
strrev changes all characters in a string to reverse
order, except the terminating null character.For
example, it would change
AYAN\0
to
NAYA\0
#include<string.h>
#include<iostream.h>
Page 41 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
int main(void)
{
char *s = "AYAN";
cout<<"After strrev(): "<<strrev(s);
return 0;
}
Output
NAYA
C++ Library Functions Header File :math.h
Declaration :- abs(int n);
Description:
abs is not a function but is a macro and is used for
calculating absolute value of a number.
#include <iostream.h>
#include <math.h>
int main()
{
int n, result;
cout<<"Enter an integer to calculate it's absolute
value\n";
cin>>n;
result = abs(n);
cout<<"Absolute value of "<<n<< "is "<<result;
return 0;
}
Output
Enter an integer to calculate it's absolute value -5
Absolute value of -5 is 5
Declaration :- double pow(double, double);
Description:
Page 42 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
pow function returns x raise to the power y where x and
y are variables of double data type.
#include <iostream.h>
#include <math.h>
int main()
{
int m,n, result;
cout<<"Enter two integers to calculate power\n";
cin>>m>>n;
result = pow(m,n);
cout<<"Result is "<<result;
return 0;
}
Output
Enter two integers to calculate power 3 4
Result is 81
Declaration :- double sqrt(double);
Description:
sqrt function returns square root of a number.
#include <iostream.h>
#include <math.h>
int main()
{
double n, result;
cout<<"Enter an integer to calculate it's square
root \n";
cin>>n;
result = sqrt(n);
Page 43 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
cout<<"Result is "<<result;
return 0;
}
Output
Enter an integer to calculate it's square root 9
Result is 3
Declaration: double sin(double);
Description:
Sin function returns sine of an angle(in radian).
#include <iostream.h>
#include <math.h>
int main()
{
double result, x = 0.5;
result = sin(x);
cout<<"sin(x ) of 0.5 is "<<result;
return 0;
}
Output
sin(x) of 0.5 is 0.479426
Declaration: double cos(double);
Description:
Cos function returns cosine of an angle(in radian).
1 radian = 57.2958(approximately).
#include <iostream.h>
#include <math.h>
int main()
Page 44 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
{
double result, x = 0.5;
result = cos(x);
cout<<"cos(x) of 0.5 is "<<result;
return 0;
}
Output
cos(x) of 0.5 is 0.877583
C++ Library Functions Header File :stdlib.h
Declaration: int random(int n);
Description:
random return a random number between 0 to (n-1)
#include <stdlib.h>
#include <iostream.h>
#include <time.h>
/* prints a random number in the range 0 to 9 */
int main(void)
{
randomize();
cout<<"Random number from 0-9 range:\n"<<random(10);
return 0;
}
Declaration: void randomize(void);
Description:
randomize initializes random number generator
#include <stdlib.h>
#include <iostream.h>
#include <time.h>
Page 45 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
/* prints 3 random number in the range 0 to 9 */
int main(void)
{
randomize();
cout<<"3 random numbers from 0-9 range:\n";
for(int i=0;i<3;i++)
cout<<random (10)<<endl;
return 0;
}
Declaration:
char*itoa(int value,char *string,int radix);
Description: itoa converts an integer to a string
#include <iostream.h>
#include <stdlib.h>
int main(void)
{
int number = 444;
char string[5];
itoa(number, string, 10);
cout<<"integer = "<<number<<"string ="<<string;
return 0;
}
Output
integer 444 string 444
Declaration: int atoi(const char *s);
Description: Macro that converts string to integer
#include <stdlib.h>
#include <iostream.h>
int main(void)
{
int n;
char *str = "112";
Page 46 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
n = atoi(str);
cout<<"string = "<<str<<"integer ="<<n;
return 0;
}
Output
string 112 integer 112
Page 47 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Introduction to User-defined functions
C++ allows programmers to define their own functions.
For example the following is a definition of a function
which return the sum of two numbers.
int SumOfNumbers(int a,int b)
// Returns the sum of a and b
{
int c; //local variable
c = a+b;
return c;
}
This function has two input parameters, a , b and will
returns the sum of these parameters. In the function a
local variable c is used to temporarily hold the
calculated value inside the function.
The general syntax of a function definition:
Return-type function-name( Data_Type parameter )
{
Statements;
}
If the function returns a value then the type of that
value must be specified in return-type. This could be
int, float or char or any other valid data type. If the
function does not return a value then the return-type
must be void.
The function-name follows the same rules of
composition as identifiers.
The parameter-list the formal parameters of the
function along with their data types.
The statements consist of any C++ executable
statements.
Page 48 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Types of user Defined Functions
Functions with no parameters
Functions with parameters and no return value
Functions that return values
Call-by-value
Call-by-reference
Functions with no parameters
Functions with no will not return a value but carry out
some operation. For example consider the following
function with no parameters.
void Display(void)
//void inside the parenthesis is optional
{
cout << "Your Message"<< endl;
}
Note that the return has been given as void, this tells
the compiler that this function does not return any
value. Because the function does not take any
parameters the parameter-list is empty, this is
indicated by the void parameter-list.
Since this function does not return a value it cannot
be used in an expression and is called by treating it
as a statement as follows:
Display();
When a function is called the C++ compiler must insert
appropriate instructions into the object code. To do
this correctly the compiler must know the types of all
parameters and the type of any return value. Thus
before processing the call of a function it must be
defined. This can be done by defining the functions
outside the definition of main function:
Page 49 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
#include <iostream.h>
void Display(void) // Function Definition
{
cout <<"Hello World";
}
void main()
{
cout << "Inside main function";
Display(); // call to Display Function
}
Function Prototype
A function prototype supplies information about the
return type of a function and the types of its
parameter. The function prototype is merely a copy of
the function definition with body. Thus the function
prototype for the function Display is:
void Display(void);
Example of Function Prototype:
#include <iostream.h>
void Display(void); // function prototype
int main()
{
cout << "Inside Main Function";
Display();
return 0;
}
void Display(void) // Function definition
{
cout << endl <<"Inside Display Function";
}
Page 50 of 232