Вы находитесь на странице: 1из 232

http://KVSeContents.in http://eTeacher.KVSeContents.

in

Notes on:
XI-XII Computer Science
C++ and Database/Mysql

Click here to check the revised version of these notes

Review Version
(Last reviewed on 09-06-2015)
New Modifications are

1 New Image inserted in Array

2 New Image inserted in Queue

3 Sample CBSE paper added

4 Spelling's Correction
5 More MYSQL's examples

Please send your feedback on:


sanjivksharma@yahoo.com/09418133050

All material is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported


License unless mentioned otherwise.

Page 01 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

Index

Topic Page NO
XI COMPUTER SCIENCE UNIT 3
III C++

XI COMPUTER SCIENCE UNIT 19


IV C++

XII COMPUTER SCIENCE UNIT 87


I C++

XII COMPUTER SCIENCE UNIT 147


II C++

XII COMPUTER SCIENCE UNIT 184


III DATABASE

CBSE Sample Paper 2014-15 220

Page 02 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

XI COMPUTER SCIENCE UNIT III C++

Page 03 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 04 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 05 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.
1. integer-constant
2. character-constant
3. floating-constant
4. string-literal
5. 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 06 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 07 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 08 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 09 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
programs 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 wed 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
CPUs 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


1. case constants must be distinct
2. default is optional
3. cases and the default can occur in any order
4. break statement causes an immediate exit from the
switch
5. 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

a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
o 1 2 3 4 5 6 7 8 9
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:
a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
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:
0 1 2 3 4 5 6 7 8 9
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:


a b c d e f g h i j k l m n o p q r s t u v w x y z
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:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
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


kvhussainpur09@rediffmail.com
<kvhussainpur09@rediffmail.com>;

int strcmp(char *string1, char *string2);


Description:
The strcmp function compares the contents of string1
and string2 and returns a value indicating their
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.
1. The function-name follows the same rules of
composition as identifiers.
2. The parameter-list the formal parameters of the
function along with their data types.
3. 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
1.
2. Functions with parameters and no return value
3. Functions that return values
4. Call-by-value
5. 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
http://KVSeContents.in http://eTeacher.KVSeContents.in

Functions with parameters and no return value


The function Display() is now changed to the function
DisplayValues which has to parameters a and b:

void DisplayValues(int a,int b)


{
cout << endl<<" a = "<<a <<endl <<" b = "<<b;
}
As before this function does not return a value hence
it is declared as having type void. It now takes two
parameters a and b. The parameter list consists of Data
type and a name for these formal parameters. Inside the
body of the function their values are displayed.
The function is called in the same manner as Display(),
but values must be given for the parameters a and b as
shown below.
int main()
{
int a = 2, b=4;
DisplayValues(a,b);
DisplayValues(2,4); /* Values can be given directly
with variables*/
return 0;
}

Note : Make sure that actual parameters data type must


match the formal parameters data type given in the
definition of the function.

While defining the function prototype for a function


with parameters it is not necessary to specify the
parameters names, we can simply write the Data types of
each parameter separated by comma. Thus a suitable
function prototype for the parameterised version of
DispalyValues would be:

Page 51 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

void DisplayValues(int,int); // No need to give name


for parameters
Example
#include <iostream.h>
// Function prototypes Only Data type of parameters
is specified
void DisplayValues(int,int);
int main()
{
int a,b;
cout<<"Inside Main- Enter Two Values"<<endl;
cin>>a>>b;
cout<<"Call to DisplayValues Function";
DisplayValues(a,b);
return 0;
}
void DisplayValues(int a,int b) // Function Definition

{
cout << endl<<" a = "<<a <<endl <<" b = "<<b;
}
Functions that return values
One of the most useful forms of function is one that
returns a value . In this case the return type given in
the function prototype is that of the value to be
returned.

int CalSum(int a ,int b) // Here return type is integer


which will Returns the sum of two integers
{
int c; //local variable
c = a+b;
return c; // return statement
}
The function prototype for this function is:

Page 52 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

int distance(int, int); // function prototype

Some points to note:


1. The function has been given the return type int
because it is going to return a integer value.
2. The parameter-list has two parameters, namely,
a and b of integer type.
3. Inside the definition of CalSum there is a
return statement.
Because this function returns a value it includes a
return statement which returns the value. Return value
may be a constant, a variable or an expression. Return
statement cab be written as
return (a+b);
Example of function that will return a value
#include <iostream.h>
//Function prototypes Only Data type of parameters is
specified
int CalSum(int ,int );int main()
{
int a,b,SUM;
cout<<"Inside Main- Enter Two Values"<<endl;
cin>>a>>b;

SUM=CalSum(a,b);
//Here the value return by CalSum will be assigned to
SUM
cout<<endl<<"The Sum of a and b is = "<<SUM;
return 0;
}
int CalSum(int a ,int b)
{
int c; //local variable
c = a+b;
return c; // return statement

Page 53 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

}
Output
Inside Main- Enter Two Values
2 3
The Sum of a and b is = 5
Default Arguments
C++ allows a function to assign default values to
parameters. The default value is assigned when no
argument corresponding to that parameter is specified
in the call to that function. For Example :
int calSum(int a = 10, int b = 20)
{
return a+b;
}
In the above code segment, if the CalSum() function is
invoked without arguments, then the default values of
10 and 20 are assigned to a and b respectively. If
values are passed to the function, then corresponding
values are assigned to a and b.
Example of Default Arguments
//This program illustrates the use of default arguments
#include<iostream.h>
void CalSum(int a = 10, int b = 20)
{
cout<<"Sum is "<<a+b<<endl;
}
void main()
{
int a = 2, b = 4;
CalSum(); // Without Arguments Call will use Default
Arguments
CalSum(a,b); // With Arguments Call will not use
Default Arguments

Page 54 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

}
Output:
Sum is 30
Sum is 6
Use of One default arguments
//This program illustrates the use of ONE default
arguments
#include<iostream.h>
void CalSum(int a , int b = 20)
{
cout<<"Sum is "<<a+b<<endl;
}
void main()
{
int a = 2, b = 4;
CalSum(a); // With one Argument Call will use ONE
Default Argument
CalSum(a,b); // With Arguments Call will not use
Default Arguments
}
Output:
Sum is 22
Sum is 6
Some points to remember when using default arguments:
Default arguments must be the last argument(s)(Right to
Left). Therefore, the following code is illegal:
int CalSum(int a=20 ,int b,int c); // Wrong
int CalSum(int a ,int b=20 , int c); // Wrong
int CalSum(int a =10 ,int b=20 , int c); // Wrong
Right method to specify Default Arguments is
int CalSum(int a ,int b=10 , int c=20); // Right
int CalSum(int a =5 ,int b=10 , int c=20); // Right

Page 55 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

Call by value and Call by Reference


When C++ passes arguments to functions it passes them
by value. There are many cases when we may want to
alter a passed argument in the function and receive the
new value back to the calling function. C++ uses
pointers explicitly to do this. The best way to study
this is to look at an example where we must be able to
receive changed parameters. Let us try and write a
function to swap variables:
// Call by Value Example
#include<iostream.h>
int main()
{
void swap(int m,int m);
int a=10 ,b=20;
swap(a,b); // Call by value
cout<<"After interchanging the values ";
cout<<" a = "<<a<<endl<<"b = "<<b;
return 0;
}
void swap(int m ,int n)
{
int a;
a=m;
m=n;
n=a;
cout<<"Inside swap function the values are ";
cout<<endl<<" m = "<<m<<endl<<" n= "<<n;
}
output:
Inside swap function the values are
m=20
n=10;
After interchanging the values
a=10
b=20
Note: No change to the values of a and b inside the
calling function .Because when we pass values to the
function only the copies of those values get passed not
the original data value .Any change made inside the
called function to these data value is not reflected to

Page 56 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

the calling function. That is why we call it call by


value.
swap(a, b) WON'T WORK.
Pointers provide the solution: Pass the address of the
variables to the functions and access address of
function.
Thus our function call in our program would look like
this:
swap(&a, &b)
// Call by Reference Example
#include<iostream.h>
int main()
{
void swap(int *m,int *m);
int a=10 ,b=20;
swap(&a,&b); // Call by reference
cout<<"After interchanding the values ";
cout<<" a = "<<a<<endl<<"b = "<<b;
return 0;
}
void swap(int *m ,int *n)
{
int a;
a=*m;
*m=*n;
*n=a;
cout<<"Inside swap function the values are ";
cout<<endl<<" *m = "<<m<<endl<<" *n= "<<n;
}
output:
Inside swap function the values are

Page 57 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

*m=20
*n=10;
After interchanging the values
a=20
b=10

Note: The values of a and b changed .Because when we


pass reference of the values to the function orginal
data value are passed .Any change made inside the
called function to these data value is reflected to the
calling function. That is why we call it call by
Reference.

Page 58 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

Array

An array is a series of elements of the same type


placed in contiguous memory locations that can be
individually referenced by adding an index to a unique
identifier.
That means that, for example, we can store 5 values of
type int in an array without having to declare 5
different variables, each one with a different
identifier. Instead of that, using an array we can
store 5 different values of the same type, int for
example, with a unique identifier.
Arrays come in two flavors: one dimensional and
dimensional arrays.
Declaring an Array
Just like any variable ,an array has to be declared
before being used. Yet the difference this time is that
you need to tell the compiler what kind of array you
are defining. This is because, once more, the compiler
wants to know how much space your array is going to
occupy in the computer memory. This is because when you
declare an array of items, the compiler puts each one
of the items in an appropriate location.
Like any other variable, the syntax of declaring an
array is:
DataType ArrayName[size]

Page 59 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

The array is first identified by its kind, which could


be a char, an int, a float, etc; followed by its name.
The name is then followed by square brackets that
specify the size of the array.
Here are examples of declaring arrays:
int a[4];
float f[100];
double d[100];
int a[4]; declares a group or array of 4 values, each
one being an integer.

float f[100]; declares an array of 100 floating-point


values.
double d[100]; declares an array of double-precision
numbers. There are 100 of these items in the group.

float f[100]; declares an array of 100 floating-point


values.
double d[100]; declares an array of double-precision
numbers. There are 100 of these items in the group.
Initializing an Array
Just like any variable can be initialized, an array
also can be initialized. To accomplish this, for a one-
dimensional array, the syntax used is:
DataType ArrayName[size] = { element1, element2, ,
elementn};
Here are examples of declaring an initializing arrays:
int num[5] = {1,2,3,4,5};

Page 60 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

If you have decided to initialize the array while you


are declaring it, you can omit the size. Therefore,
array can be declared as follows:
int num[] = {1,2,3,4,5};
Processing the Elements of an Array
After initializing an array, its elements are counted
from left to right. Each element of the array, also
called a member of the array, has a specific and
constant position. The position of an item is also
called its index. The first member of the array, the
most left, has an index of 0. The second member of the
array has an index of 1. Since each array has a number
of items which can be specified as n, the last member
of the array has an index of n-1
Based on this system of indexing, to locate a member of
an array, use its index in the group. Imagine you
declare and initialize an array as follows:
double weight[] = {20.2,24.5,34.7};
To locate the value of the 3rd member of the array, you
would type weight[2]. In the same way, the 1st member
of the array can be located with weight[0].
Once you can locate a member of the array, you can
display its value. Here is an example:
#include <iostream.h>

int main()
{
double weight[] = {20.2,24.5,34.7};
cout << "2nd member = " << weight[1] << endl;
cout << "3rd member = " << weight[2] << endl;
return 0;
}
This would produce:
2nd member = 24.5
3rd member = 34.7
The Size of an Array

Page 61 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

When declaring an array, we saw that you must specify


the number of items that the array is made of. Here is
an example:
float price[5];
Depending on how you want to deal with your array, you
may sometimes need to increase or decrease its
dimension. To do this, you would need to locate the
declaration of the array and change its dimension. If
the program is long and the array is declared in some
unusual place, this could take some time. The
alternative is to define a constant prior to declaring
the array and use that constant to hold the dimension
of the array. Here is an example:
#include <iostream.h>
int main()
{
const int SIZE = 5;
int weight[SIZE] = {20,30,40,50,60};
cout << "weight 1: " << weight[0] << endl;
cout << "weight 2: " << weight[1] << endl;
cout << "weight 3: " << weight[2] << endl;
cout << "weight 4: " << weight[3] << endl;
cout << "weight 5: " << weight[4] << endl;
return 0;
}
We knew the dimensions of the arrays we have used so
far, because we could count the number of members of
the array. Imagine you declare a large array, possibly
made of 50 or 100 members, you wouldn't start counting
the number of members. C++ provides the sizeof operator
that can be used to get the dimension of an array. The
syntax you would use is:
sizeof(NameofArray)
If we declare an array as follows:
int number[] = {1,2,3,4,5};
Instead of counting the number of members of this array
we can use the sizeof operator as follows:
int NumberOfElements = sizeof(Number)/sizeof(int);

Page 62 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

Accessing Array Members


int items[5];
Each member of the array can be located using its
index, as we have seen so far. In the same way, you can
request the value of any member of the array using its
index. In the following example, we declare an array of
5 integers and then we request the values of the 2nd
and the 4th members:
#include <iostream.h>
int main()
{
const int count = 5;
int items[count];
cout << "Enter the values of two items\n";
cout << "Item 1: ";
cin >> items[0];
cout << "item 4: ";
cin >> items[3];
cout << "\nYou have Entered following values";
cout << "\nItem 1: " << items[0] ;
cout << "\nItem 4: " << items[3] ;
return 0;
}
Here is an example of running the program:
Enter the values of two items
Item 1: 45
Item 4: 66
You have Entered following values
item 1: 45
item 4: 66
Operations on Arrays
You can add the values of two members of the
array(Number[2]+Number[0]), you can subtract the value
of one of the members from another member(member[1]-
Number[4]). In the same way, you can perform
multiplication, division, or remainder operations on
members of an array.
Sum of all the Elements of an Array

Page 63 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

#include <iostream.h>
#define N 3
int main()
{
int a1[N];
int sum=0;
int i;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)
cin>>a1[i];
// Now we will find Sum
for(i=0;i<N;i++)
sum=sum+a1[i];
cout<<endl<<"Sum of all The elements is "<<sum;
return 0;
}
Product of all the Elements of an Array
#include <iostream.h>
#define N 3
int main()
{
int a1[N];
int pro=1;
int i;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)
cin>>a1[i];
// Now we will find Product

Page 64 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

for(i=0;i<N;i++)
pro=pro*a1[i];
cout<<endl<<"Product of all The elements is "<<pro;
return 0;
}
Average of all the Elements of an Array
#include <iostream.h>
#define N 3
int main()
{
int a1[N];
int sum=0;float avg=0.0;
int i;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)
cin>>a1[i];
// Now we will find Average
for(i=0;i<N;i++)
sum=sum+a1[i];
avg=(float)sum/N;
cout<<endl<<"Average of all The elements is "<<avg;
return 0;
}
Maximum Element of an Array
#include <iostream.h>
#define N 3
int main()

Page 65 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

{
int a1[N];
int max=0;
int i;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)
cin>>a1[i];
// Now we will find Max element
for(i=0;i<N;i++)
if(max<a1[i])
max=a1[i];
cout<<endl<<"Max elements is "<<max;
cin>>i;
return 0;
}
Minimum Element of an Array
#include <iostream.h>
#define N 3
int main()
{
int a1[N];
int min=9999;
int i;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)
cin>>a1[i];
// Now we will find Min element
for(i=0;i<N;i++)
if(min>a1[i])
min=a1[i];;
cout<<endl<<"Max elements is "<<min;
return 0;
}

Page 66 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

Linear Search
Another type of operation regularly performed on an
array consists of looking for a value held by one of
its members. For example, you can try to know if one of
the members holds a particular value you are looking
for. Here is an example:
#include <iostream.h>
int main()
{
// Declare the members of the array
int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int find;
int i, m = 8;
cout << "Enter a number to search: ";
cin >> find;
for (i = 0;i<m; ++i)
if(numbers[i]==find)
cout << find << "Found" << endl;
// Find whether the number typed is a member of the
array
if (i == m)
cout << find << " Not Found"<< endl;
return 0;
}

This would produce:


Enter a number to search: 44
44 Found

Page 67 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

Counting vowels,consonants, digits, white space and


total number of characters in a String
#include<iostream.h>
int main(){
char line[150];
int i,v,c,ch,d,s;
v=c=ch=d=s=0;
cout<<"Enter a line of string:\n";
gets(line);
for(i=0;line[i]!='\0';++i)
if(line[i]=='a'||line[i]=='e'||line[i]=='i'
||line[i]=='o'||line[i]=='u')
++v;
else if(line[i]>='a'&&line[i]<='z')
++c;
else if(line[i]>='0'&&c<='9')
++d;
else if (line[i]==' ')
++s;
cout<<"Total vowels: "<<v;
cout<<"\nTotal consonants: "<<c;
cout<<"\nTotal digits: "<<d;
cout<<"\nTotal white spaces: "<<s;
cout<<"\nTotal characters: "<<i;
return 0;
}
C++ program to reverse string without using strrev
library function

#include<iostream.h>
#include<string.h>
void Reverse(char str[]);
int main(){
char str[100];
cout<<"Enter a string to reverse: ";
gets(str);
Reverse(str);
cout<<"String after reversing: ";
puts(str);
return 0;
}
void Reverse(char str[]){
int i,j;

Page 68 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

char temp[100];
for(i=strlen(str),j=0;i!=0;--i,++j){
temp[j]=str[i];
}
temp[j]='\0';
strcpy(str,temp);
}

Page 69 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

Two-Dimensional Arrays
A 2-dimensional array is an array of arrays. In other
words, it is an array where each member of the array is
also an array.

Declaring and Initializing a 2-Dimensional Array


Two-dimensional array is made of rows and columns. Each
column represents one category of data that everyone of
the rows shares with the other rows. To declare it, use
double pair of a opening and closing square brackets.
Data_Type NameOfArray[ROWS][COLUMNS];
int TwoDArray[5][5];
This declarations creates 5 rows and each row contains
5 elements.
You can initialize an array the same way you would
proceed the a one-dimensional array: simply provide a
list of values in the curly brackets.
A multidimensional array is represented as an algebraic
matrix as MxN. This means that the array is made of M
rows and N columns. Total number of elements of a
multidimensional array can be calculated by multiply
the number of rows by the number of columns. Therefore
a 2x3 array contains 2*3=6 elements.
Based on this, when initializing a 2-dimensional array,
make sure you provide a number of values that is less
than or equal to the total number of elements.
Here is an example:
double age[2][3] = {12,14,16,17,17,19};
Page 70 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

To locate a member of the array, this time, each must


be identified by its double index. The first member is
indexed at [0][0]. The second is at [0][1]. For a 2x3
array as this one, the 5th member is at [1][1]. You can
use this same approach to display the values of the
members of the array. Here is an example:
#include <iostream.h>
int main()
{
// A 2-Dimensional array
int TwoDArray[2][3] = {1,2,3,4,5,6};
// Display the array
cout << "Elements of the array";
cout << "\nTwoDArray [0][0]" << ": "
<< TwoDArray[0][0];
cout << "\nTwoDArray [0][1]" << ": "
<< TwoDArray[0][1];
cout << "\nTwoDArray [0][2]" << ": "
<< TwoDArray[0][2];
cout << "\nTwoDArray [1][0]" << ": "
<< TwoDArray[1][0];
cout << "\nTwoDArray [1][1]" << ": "
<< TwoDArray[1][1];
cout << "\nTwoDArray [1][2]" << ": "
<< TwoDArray[1][2];
cout << endl;
return 0;
}
Output:
Elements of the array
TwoDArray [0][0]: 1
TwoDArray [0][1]: 2
TwoDArray [0][2]: 3
TwoDArray [1][0]: 4
TwoDArray [1][1]: 5
TwoDArray [1][2]: 6

Page 71 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

C++ also allows you to include each row in its own pair
of curly brackets. You must separate each row from the
next with a comma. Here is an example:
int items[2][3] = {

{ 1,2,3},{4,5,6}

};

Processing a 2-Dimensional Array


To process a 2D array, we should know how many columns
the array contains. We can use two for loops to process
the array. Here is an example:
#include <iostream.h>
int main()
{
// A 2-Dimensional array
int items[2][3] = {
{ 1,2,3},
{ 4,5,6}
};
// Display all elements
cout << "Elements of the array";
for(int i = 0; i < 2; ++i)
for(int j = 0; j < 3; ++j)
cout << "\nItems[" << i << "][" << j << "]: "
<< items[i][j];
cout << endl;
return 0;
}
Sum of Diagonal elements of an Two Dimensional Array

#include <iostream.h>
#define N 3
#define M 3
int main()
{
int a1[N][M],s;
int i,j;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)
for(j=0;j<M;j++)
cin>>a1[i][j];
// Now we will find sum of diagonal elements
Page 72 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

for(i=0;i<N;i++)
for(j=0;j<M;j++)
{
if(i==j)
s=s+ a1[i][j];
}
cout<<endl<<"Sum of diagonal elements of a1 and a2
is "<<s;
return 0;
}
Finding Maximum element in MXN Array
// Max Element in a two Dimensional Array
#include <iostream.h>
#define N 3
#define M 3
int main()
{
int a1[N][M];
int max=0;
int i,j;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)
for(j=0;j<M;j++)
cin>>a1[i][j];
// Now we will find Max element
for(i=0;i<N;i++)
for(j=0;j<M;j++)
{
if(max<a1[i][j])
max=a1[i][j];
}

Page 73 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

cout<<endl<<"Maximum element is "<<max;


return 0;
}
Finding Minimum element in MXN Array
// Min Element in a two Dimensional Array
#include <iostream.h>
#define N 3
#define M 3
int main()
{
int a1[N][M];
int min=9999;
int i,j;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)
for(j=0;j<M;j++)
cin>>a1[i][j];
// Now we will find Min element
for(i=0;i<N;i++)
for(j=0;j<M;j++)
{ if(min>a1[i][j])
min=a1[i][j];
}
cout<<endl<<"Minimum element is "<<min;
cin>>min;
return 0;
}

Page 74 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

2D Array and String


Because strings are in fact sequences of characters, we
can represent them also as plain arrays of char
elements.
For example, the following array:
char Ayan[20];
is an array that can store up to 20 elements of type
char. In this array, we can store sequences of
characters up to 20 characters long. But we can also
store shorter sequences. For example, Ayan could store
at some point in a program either the sequence "Hello"
or the sequence "Happy Diwali", since both are shorter
than 20 characters.
Therefore, since the array of characters can store
shorter sequences than its total length, a special
character is used to signal the end of the valid
sequence: the null character, whose literal constant
can be written as '\0' (backslash, zero).
Our array of 20 elements of type char, called Ayan, can
be represented storing the characters sequences "Hello"
and "Happy Diwali" as:

Notice how after the valid content a null character


('\0') has been included in order to indicate the end
of the sequence.
Initialization of null-terminated character sequences
If we want to initialize an array of characters with
some predetermined sequence of characters we can do it
just like any other array:
char Ayan[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
In this case we would have declared an array of 6
elements of type char initialized with the characters

Page 75 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

that form the word "Hello" plus a null character '\0'


at the end.
Arrays of char elements have an additional method to
initialize their values: using string literals.String
literals enclosed between double quotes always have a
null character ('\0') automatically appended at the end
by the compiler. Therefore we can initialize the array
of char elements called Ayan with a null-terminated
sequence of characters by either one of these two
methods:

char Ayan[] = { 'H', 'e', 'l', 'l', 'o', '\0' };


char Ayan[] = "Hello";
In both cases the array of characters Ayan is declared
with a size of 6 elements of type char: the 5
characters that compose the word "Hello" plus a final
null character ('\0') which specifies the end of the
sequence and that, in the second case, when using
double quotes (") it is appended automatically.
Using null-terminated sequences of characters
Null-terminated sequences of characters are the natural
way of treating strings in C++.For example, cin and
cout support null-terminated sequences as valid
containers for sequences of characters, so they can be
used directly to extract strings of characters from cin
or to insert them into cout. For example:
// null-terminated sequences of characters
#include <iostream.h>
int main ()
{
char yourname[] = "Please, enter your first name: ";
char message [] = "Hello, ";
char name [80];
cout << yourname;
cin >> name;
cout << message << name << "!";
return 0;
}
Please, enter your first name: Sanjeev
Hello, Sanjeev!

Page 76 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

As you can see, we have declared three arrays of char


elements. The first two were initialized with string
literal constants, while the third one was left
uninitialized. In the first two arrays the size was
implicitly defined by the length of the literal
constant they were initialized to. While for name we
have explicitly specified that it has a size of 80
chars.

Page 77 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

User Defined Data Types


The C++ language allows you to create and use data
types other than the fundamental data types. These
types are called user-defined data types. There are two
ways by which a user-defined data type can be created.
The first is by using the keyword struct, and the
second is by using the keyword class. Data types
defined using the keyword struct are called structures.
Structures
In C++, a structure is a collection of variables that
are referenced by a single name. The variable can be of
different data types. They provide a convenient means
of keeping related information together. Structure
definition forms a template which is then used to
create structure variables. The variables that make up
the structure are called structure members.

The following code segment shows how a structure that


defines an roll_no and name can be created. The keyword
struct tells the compiler that a structure is being
declared.
struct student
{
int roll_no;
char name[20];
};
Notice that the structure declaration is terminated by
a semi-colon. Also, the structure name student
identifies this particular data structure. In this
structure no structure variable has been declared.
To declare a variable, you need to use the following
statement:
student stu;
This defines a structure's variable of type 'student',
called stu. When we declare a structure, we are, in
essence, defining a data type. Memory is not allocated
for a structure until a variable of that type is
created.

Page 78 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

The compiler automatically allocates sufficient memory


to accommodate all the elements that make up the
structure. We can declare structure's variables at the
time of declaring a structure.
For example:
struct student
{
int roll_no;
char name[20];
}stu;
will declare a structure type called student and
declare the variable stu.
The general form of a structure declaration is:
struct <structure_name>
{
<type> <variable1>;
<type> <variable2>;
...
...
<type> <variableN>;
}<structure vars>;
where <structure_name> is the name of the structure.
The structure name is then used to declare structure
variables. <structure vars> are the names of structure
variables.
The .(dot) Operator
Individual structure elements can be referenced by
combining the .(dot) operator and the name of the
structure variable. For example, the following
statement assigns a value of 10 to the element roll_no
of the structure variable stu declared earlier.
stu.roll_no=10;
The general form to access a structure element is:
<structure variable>.<element name>

Page 79 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

The following program illustrates input and output


operations using structures:
//structure example
#include<iostream.h>
struct student
{
int roll_no;
char name[20];
}stu;
int main()
{
cout<<"Enter Roll No:";
cin>>stu.roll_no;
cout<<"Enter Name:";
cin>>stu.name;
cout<<endl<<"Roll NO = "<< stu.roll_no<<endl<<"Name = "
<<stu.name;

return 0;
}
Enter Roll No: 11
Enter Name : Sample
Roll No = 11
Name = Sample
Passing structure variable to a function
(call by-value)
#include <iostream.h>
struct temp
{
int a, b;

} ;

Page 80 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

void StructPass(temp var);


int main(void)
{
temp arg;
arg.a = 123;
arg.b = 321;
StructPass(arg); // Passing structure variable
return 0;
}
void StructPass(temp var)
{
cout<<var.a;
cout<<var.b;
}
Passing structure variable to function using
(call-by-reference)

#include <iostream.h>
struct temp
{
int a, b;
} ;
void StructPass(temp *var);
int main(void)
{
temp arg;
// Here the name of ".(dot)" is Direct Member
Selector Operator
arg.a = 123;
arg.b = 321;
StructPass(&arg); // Passing structure variable
address
cout<<"\nInside Main ";
cout<<"\n arg.a = "<<arg.a;

Page 81 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

cout<<"\n arg.b = "<<arg.b;


return 0;
}
void StructPass(temp *var) // Pointer to structure temp
{
/* The -> (Indirect Member Selector) operator is used
when a structure element has to be accessed through
pointer. */
var->a=888;
var->b=999;
cout<<"\nInside StrutPass ";
cout<<"\nvar->a = "<<var->a;
cout<<"\nvar->b = "<<var->b;
}
Output
Inside StrutPass
var->a =888
var->b =999
Inside Main
arg.a =888
arg.b =999;
The -> Operator
The -> (Indirect Member Selector) operator is used
when a structure element has to be accessed through a
pointer.
Arrays of Structure
#include <iostream.h>
struct student
{
int age;
int roll_no;
char name[20];

Page 82 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

};
int main()
{
student data[3];// Array of 3 Structure variables
int i = 0;
cout<<endl<<"Enter age,roll no and name of three
students:";
for(i = 0; i<3 ;i++)
{
cin>>data[i].age;
cin>>data[i].roll_no;
cin>>data[i].name;
}
cout<<endl<<"Your have Entered:";
for(i = 0; i<3 ;i++)
{
cout<<data[i].age<<"\t";
cout<<data[i].roll_no<<"\t";
cout<<data[i].name<<endl;
}
return 0;
}
Passing Array of Structure to a Function
#include <iostream.h>
struct student
{
int age;
int roll_no;
char name[20];
};
int main()
{
void PassArrayStruct(student data[]);
student data[3];// Array of 3 Structure variables
int i = 0;
cout<<endl<<"Enter age,roll no and name of three
students:";
for(i = 0; i<3 ;i++)
{
cin>>data[i].age;
cin>>data[i].roll_no;
cin>>data[i].name;
}

Page 83 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

PassArrayStruct(data); // Passing Array of


Structure variables
return 0;
}
void PassArrayStruct(student data[])
{ int i;
cout<<endl<<"Accessing Values Inside PassArrayStruct
Function:";
for(i = 0; i<3 ;i++)
{
cout<<data[i].age<<"\t";
cout<<data[i].roll_no<<"\t";
cout<<data[i].name<<endl;

}
}
typedef keyword in C++
In C++, we can declare a variable using one of the
built-in data types. In the same way, we can declare an
array or a pointer. If we want to use the same data
type for many declarations of variables, we can
customize its name. The typedef keyword allows us to
create an alias for a data type. The syntax to use
typedef is:
typedef DataType AliasName;
The typedef keyword is required. The typedef keyword
can be followed by any C++ built-in data type, like
int, char, double etc. On the right side of the data
type, type the name(alias) that will be used to
represent the data type. Here is the example:
#include <iostream.h>
typedef short SmallInt;
typedef unsigned long Lint;
int main()
{ SmallInt tdef = 123;
Lint LI = 321;
Page 84 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

cout << endl <<"Use of typedef short SmallInt" <<tdef;


cout<<endl<<"Use of typedef unsigned long Lint" <<LI;
return 0;
}
Output:
Use of typedef short SmallInt 123
Use of typedef unsigned long Lint 321
With typedef short SmallInt and unsigned long Lint can
now be used as a data type to declare variables of type
small integer and unsigned long integer.
Define preprocessor macros .
Syntax:
#define identifier replacement
When the preprocessor encounters this directive, it
replaces any occurrence of identifier in the rest of
the code by replacement. This replacement can be an
expression, a statement or a block. Preprocessor simply
replaces any occurrence of identifier by replacement.
#define SIZE 100
int Number[SIZE];
int Count[SIZE];
After the preprocessor has replaced SIZE, the code
becomes equivalent to:
int Number[100];
int Count[100];
#define can also work with parameters to define
function macros:
#define getmax(a,b) a>b?a:b

This would replace any occurrence of getmax followed by


two arguments by the replacement expression.

Page 85 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

// #Define Macro Example


#include <iostream.h>
#define getmax(a,b) ((a)>(b)?(a):(b))
int main()

{
int x=5, y;
y= getmax(x,2);
cout << y << endl;
cout << getmax(7,x) << endl;
return 0;
}
Output
7
Because preprocessor replacements happen before any C++
syntax check, macro definitions can be a tricky feature
so be careful !!!.

Page 86 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

XII COMPUTER SCIENCE UNIT I C++

Page 87 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

Object Oriented Programming


A type of programming in which main concentration is on
DATA rather than on ALGORITHM
Characteristics of Object Oriented Programming

Data encapsulation - Encapsulation is the process of


combining data and methods into a single unit called
class.
Using encapsulation, nobody can directly access the
data. Data is only accessible through the methods
existing inside the class.
Data hiding - Hiding the implementation details of a
class from the user. To ensure this class groups its
members into three sections:
Private, protected and public
In which private and protected are hidden from the
outside world
For example
class Kangra
{
private:
int m; // m is only accessible within the class

protected:
int n // n is only accessible within the class and
// to the subclass of Kangra
public:
int p; //p is accessible inside and outside the class
Kangra() // constructor
{ }
};

Polymorphism It is the ability for a message or data


to be processed in more than one form. An operation may
exhibit different behaviors in different instances. The
behavior depends on the data types and number of data

Page 88 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

items used in the operation. Polymorphism is


implemented using function overloading.
For example
class Kangra
{
public:
Kangra()
{ }
int area(int a)
{
return a*a;
}
int area( int a,int b); //Overloaded function
{
return a*b;
}

};

Inheritance Inheritance is the process by which


objects of one class can acquire the properties of
objects of other class.
Inheritance provides code re-usability, like, adding
additional features to an existing class without
modifying it. This is achieved by deriving new class
from the existing one. The new class will have combined
features of both the classes.
For example-
class A
{
Public :

Page 89 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

int a ,b;
void show ()
{
cout<<a<<b;
}
};
class B: private A //Use of Inheritance
{
int c;
void dispdata ()
{
cout<<c;
}
};
Concept of Class and Object in C++
Class -A class is a blue print for creating objects.
Definition:
A class is a group of objects which show a common
property.
OR
A class is a collection of objects of similar type.Once
a class is defined, any number of objects can be
created which belong to that class.For example Define
a class to print the values of two numbers.
Class HelloWorld
{
int one;
int two;
public:

Page 90 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

void setdata()
{
cout<<enter two numbers;
cin>>one>>two;
}
void putdata()
{
cout<<one<<endl<<two;
}
};

int main()
{
HelloWrold obj;
Obj.setdata();
Obj.putdata();
return 0;
}
Classes are generally declared using the keyword class,
with the following format:
class class_name
{
access_specifier_1:
member;
access_specifier_2:
member;
...
};

Page 91 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

Object -It may be defined as identifiable identity with


some characteristics and behavior.
Syntax of creating Object:
Class_name Object_Name;
If we have class named AB then the Object of this class
can be created using above syntax as
AB Obj;
Abstract class
An abstract class is a class that is designed to be
specifically used as a base class. An abstract class
contains at least one pure virtual function.
You declare a pure virtual function by using a pure
Specifier
(= 0) in the declaration of a virtual member function
in the class declaration.
The following is an example of an abstract class:
class AB {
public:
virtual void f() = 0; //Pure virtual
Function

};
Concrete class It is a derived class that implement
all the missing functionality of a abstract class.
The following is an example of an concrete class:

class CD : public AB //Here class AB is abstract class


{ // Declare Above
public:
CD()
{ // set up the CD }
virtual f() // implementation of f() of class AB

Page 92 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

{
/* do stuff of f() */
}
};

Advantages and disadvantages of Object Oriented


Programming
Advantages
1. Re-usability of code.
2. Ease of redesign and extension.
3. Data can be divided as public and private.(data
protection)
4. Program development becomes easy due to increased
modularity.(abstraction and encapsulation)
Disadvantages
1. The relation among classes become artificial at
times
2. The object oriented programming design id
difficult.
3. OOP is a high level concept so takes more time to
execute as many routines run behind at the time of
execution.
4. Offers less number of functions as compared to low
level programming which interacts directly with
hardware.

Page 93 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

Access Specifiers in C++


Declaration of class:
class CLASS_NAME
{
//Access Specifier
Data Members

Member Functions

};
Data members are data type properties that describe the
characteristics of a class. There may be zero or more
data members of any type in a class.
Member functions are the set of operations that may be
applied to the objects of that class. It is the
interface between the class members and object. It is
always single it doesnt make any copy. There may be
zero or more member functions in a class.
Program Access Level that control access to members
from within the program. These access levels are
private, protected or public. Depending upon the access
level of a class member , access to it is allowed or
denied.
Class name that serves as a type specifier for the
class using which object of this class type can be
created.
For Example
#include<iostream.h>
#include<conio.h>
class sum // class
{
int a,b,s; //data members
public:
sum() // constructor
{

Page 94 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

a=10;
b=20;
}
void show() //member function
{
s=a+b;
cout<<sum of numbers is<<s<<endl;
}
};
int main()
{
sum obj; //object of class
obj.show();
return 0;
}
public, protected and private are three access
specifiers in C++.

IF YOU DON'T SPECIFY ANY ACCESS SPECIFIER WITH A DATA


MEMEBR OR WITH A MEMBER FUNCTION, THE ACCESS SPECIFIER
FOR THOSE MEMBERS WILL BE TREATED AS private BY
DEFAULT.
The general form of class definition is given below.
class class-name{
private:
Data Members/Member Functions
protected:
Data Members/Member Functions

Page 95 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

public:
Data Members/Member Functions
};
The class body contains the declaration of members
(data and functions). There are generally three types
of member in a class: private, protected and public
which are grouped under three sections namely private:
protected: and public:.
The private member can be accessed only from within the
class and public members can be accessed from outside
the class also. If no access specifier (public,
protected or private) is specified then by default,
members are private.
Private variables can only be accessed by the class
Class A
{
private:
int x;
public:
void SetX(int n) { x = n; } //this is ok
};
int main()
{
A aobj;
aobj.x = 0; //error because x is private and not
accessible outside the class
}
Protected is similar to private but can also be
accessed by inherited classes
class A
{
protected:
int x;
public:
void SetX(int n) { x = n; } // this is ok
};
class B : public A
{

Page 96 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

public:
void ShowX() { cout << x << "\n"; }
// this is ok as x is protected member
};
Public member can be accessed from outside the class
Class A
{
public:
int x
void SetX(int n) { x = n; } // <<< this is ok
};
int main()
{
A aobj;
aobj.x = 0;
// Ok because x is public accessible outside the class
}

Page 97 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

Constructor and Destructor Member Functions


Constructor: - Constructor function gets invoked
automatically when an object of a class is constructed
(declared).
Destructor:- A destructor is a automatically called
member function of a class, when an object is destroyed
of that class.
THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~)
BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF
THE CLASS IN WHICH THEY ARE DECLARED.
Use of Constructor and Destructor function of a class:
-
1. Constructor function is used to initialize member
variables to pre-defined values as soon as an
object of a class is declared.
2. Constructor function having parameters is used to
initialize the data members to the values passed
values, upon declaration.

Generally, the destructor function is needed only when


constructor has allocated dynamic memory.
Defining Constructor and Destructor functions
The example below illustrates how constructor and
destructor functions are defined:
class Kangra
{
private:
int n;
public:
Kangra() //constructor
{
n=1;
}
~Kangra() //destructor
{ }
};

Page 98 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

A few points to note:


Both of the functions have the same name as that of
the class, destructor function having (~) before
its name.
Both constructor and destructor functions should
not be preceded by any data type (not even void).
These functions do not (and cannot) return any
values.
We can have only the constructor function in a
class without destructor function or vice-versa.
Constructor function can take arguments but
destructors cannot.
Constructor function can be overloaded as usual
functions.
Explicit call to the constructor: - By explicit call to
the constructor,means that the constructor is
explicitly declared by the programmer inside the class.
Implicit call to the constructor: - By implicit call to
the constructor,means that the constructor is
implicitly provided by the Compiler when an Object of
the Class is created and there is no Explicit
Constructor defined inside the Class.
Example 1: Explicit constructor function to initialize
data members to pre-defined values
#include<iostream.h>
class Kangra
{
private:
int a;
int b;
public:
Kangra()
{
//here constructor function is used to initialize data
members to pre-defined values
a=10;
b=10;
}
int add()
{

Page 99 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

return a+b;
}
};
int main(void)
{
Kangra obj;
cout<<obj.add();
return 0;
}
Example 2: Explicit constructor function to initialize
data members to values passed as arguments
#include<iostream.h>
class Kangra
{
private:
int a;
int b;
public:
Kangra(int i, int j)//Explicit Constructor with
arguments
{
a=i;
b=j;
}
int add(void)
{
return a+b;
}
};
int main()
{
myclass obj(10,20); //This Can be written as Kangra obj
obj=Kangra(10,20);
cout<<obj.add();
}
Default/Implicit constructor: - These constructors are
inserted automatically by the Compiler into class
declarations that do not have any implicit constructor.
Example:
class Ayan

Page 100 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

{
Ayan() { } //Default/Implicit Constructor
};
Copy Constructor
A copy constructor is a special constructor that
creates a new object from an existing object. If we do
not define a copy constructor, the compiler will
generate one for us that performs a shallow copy
(copies only a pointer so that the two pointers refer
to the same object) of the existing object's member
variables. So, if our object allocates any resources,
we most likely need a copy constructor so that we can
perform a deep copy (copies what a pointer points to so
that the two pointers now refer to distinct objects).
// Shallow Copy Example
char *ch = new char('Z');
char *cp = ch; // copy the pointer ch
*ch = 'X'; // change the value of the char pointed to
by *ch
// Deep Copy Example
int *p = new int(99);
int *q = new int(*p);
// Allocate a new int before copying the value pointed
to by p
*p = 100; // change the value of the int pointed to by
p
Example of Default Copy Constructor that compiler
provides and its problem:
#include <iostream.h>
#include<string.h>
class Kangra
{
int *temp;
public:

Page 101 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Kangra(int i)
{
cout << " Constructor";
temp=new int();
*temp = i;
}
~Kangra()
{
cout << "Destructor";
delete temp;
}
};
int main()
{
Kangra kg(150); // First Object Created Invoke our
Constructor
Kangra kg1(kg); // Here is the Problem;
/* When Second Object will be Created It will
not Invoke our Constructor. It will invoke Default Copy
Constructor */
cout << "Main";
return 0;
}
Let's look at the output:
Constructor
Main
Destructor
Destructor
Null Pointer Assignment
Destructor does delete. The problem is it is trying to
delete a pointer we haven't allocated. When default
copy constructor is called (Kangra kg1(kg)), it does
not allocate anything.

How to fix it?

Page 102 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Use explicit Copy Constructor Instead of Default Copy


Constructor
#include<iostream.h>
#include<string.h>
class Kangra
{
int *temp;
public:
Kangra(int i)
{
cout<<"Constructor\n";
temp=new int();
*temp=i;
}
Kangra(const Kangra &obj) // Explicit Copy Constructor
{
cout << "Copy Constructor\n";
temp = new int();
*temp=*obj.temp ;
}
~Kangra()
{
cout << "Destructor\n";
delete temp;
}
};
int main()
{
Kangra kg(150); // Call to Simple Constructor when
Object 1 will be created
Kangra kg1(kg); // Call to Explicit Copy Constructor
when Object 2 will be created
cout << "Main\n";
return 0;
}
Now we will get the desired output: Two Objects Created
and Two Deleted

Page 103 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Constructor
Copy Constructor
Main
Destructor
Destructor
This should be our choice.
Summary
The copy constructor gets called in the following
cases:
An object is passed to a method by value or returned by
value.
An object is initialized using the syntax, MyClass a =
b.
An object is thrown or caught in an exception.
Constructor with Default Argument:
#include <iostream.h>
#include<string.h>
class Kangra
{
int temp;
public:
Kangra(int i=10) //Constructor with Default Argument 10
{
cout << " Inside Constructor with Default Argument";
temp=i;
cout<<"Temp = "<<temp;
}
};
int main()
{
Kangra kg; // Object Created without argument. This

Page 104 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

will take default argument of the Constructor

cout << "Main";


return 0;
}
Output:
Inside Constructor with Default Argument
temp=10;
Main

Page 105 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Inheritance in C++
A key feature of C++ is inheritance. Inheritance allows
to create classes which are derived from other classes,
so that they automatically include some of its
"parent's" members, plus its own. For example, If we
declare a class FRUIT which describes all the common
attribute of fruits such as their taste , colour etc.
From this FRUIT class we cab drive two other classes
Apple and Orange.

The class Fruits would contain members that are common


for both types of Fruits. In our case: Taste and
Colour. And Orange and Apple would be its derived
classes, with specific features that are different from
one type of fruit to the other.
If a base class includes a member A and we derive it to
another class with another member called B, the derived
class will contain both members A and B.
In order to derive a class from another, we use a colon
(:) in the declaration of the derived class using the
following format:
Class derived_class: access_specifier base_class

{ /*...*/ };

Page 106 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Where derived_class_name is the name of the derived


class and base_class_name is the name of the class on
which it is based. The access specifier may be replaced
by any one of the access specifiers such as
public,protected and private. This access specifier
limits the most accessible level for the members
inherited from the base class: The members with a more
accessible level are inherited with this level instead,
while the members with an equal or more restrictive
access level keep their restrictive level in the
derived class.
// Inheritance Example
#include <iostream.h>
#include<string.h>
class Fruits
{
public:
char taste[20],color[20];
};
class Orange: public Fruits
{
public:
void TasteColor()
{
strcpy(taste,"sweet-sour");
strcpy(color,"orange");
}
void Display()
{
cout<<"Orange Taste = "<<taste<<endl;
cout<<"Orange Colour ="<<color<<endl;

Page 107 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

}
};
class Apple: public Fruits
{
public:
void TasteColor()
{

strcpy(taste,"sweet");

strcpy(color,"red");

void Display()
{
cout<<"Apple's Taste = "<<taste<<endl;
cout<<"Apple's Colour ="<<color<<endl;
}
};
int main ()
{
Orange org;
Apple app;
org.TasteColor();
app.TasteColor();
org.Display();
app.Display();
return 0;
}
Output:

Page 108 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Orange Taste = sweet-sour


Orange Colour =orange
Apple Taste = sweet
Apple Colour =red
The objects of the classes Orange and Apple each
contain members inherited from Fruits. These are: taste
and color().
Since we wanted taste and color to be accessible from
members of the derived classes Orange and Apple, we
have used public access specifier.
We can summarize the different access types according
to who can access them in the following way:

Access Public Protected Private

Members of the same class yes yes Yes

Members of derived
Yes Yes No
classes

Non members
Yes No No

Where "not members" represent any access from outside


the class, such as from main(), from another class or
from a function.

Access Specifier in Inheritance:

When deriving a class from a base class, the base class


may be inherited through public,
protected or private inheritance. The type of
inheritance is specified by the access-specifier .
public inheritance is commonly used. While using
different type of inheritance, following rules are
applied:

1. Public Inheritance: When deriving a class from


a public base class, public members of the base

Page 109 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

class become public members of the derived class


and protected members of the base class
become protected members of the derived class. A
base class's private members are never accessible
directly from a derived class, but can be accessed
through calls to the public and protected members
of the base class.

2. Protected Inheritance: When deriving from


a protected base class,public and protected
members of the base class become
protected members of the derived class.

3. Private Inheritance: When deriving from


a private base class, public and protected members
of the base class become private members of the
derived class.
In our example, the members inherited by Orange and
Apple classes have the same access permissions as they
had in their base class Fruits:This is because we have
used the public keyword to define the inheritance
relationship on each of the derived classes:
class Orange: public Fruits{ ... }

This public keyword after the colon (:) denotes the


most accessible level the members inherited from the
class that follows it (in this case Orange) will have.
Since public is the most accessible level, by
specifying this keyword the derived class will inherit
all the members with the same levels they had in the
base class.
If we specify a more restrictive access level like
protected, all public members of the base class are
inherited as protected in the derived class. Whereas if
we specify the most restricting of all access levels:
private, all the base class members are inherited as
private.
For example, if we derive Orange class as:
class Orange: protected Fruits;

Page 110 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

This would set protected as the maximum access level


for the members of Orange that it inherited from Apple.
That is, all members that were public in Fruits would
become protected in Orange. Of course, this would not
restrict Orange to declare its own public members. That
maximum access level is only set for the members
inherited from Fruits.
If we do not explicitly specify any access level for
the inheritance, the compiler assumes private for
classes declared with class keyword and public for
those declared with struct.
Forms of Inheritance
Single Inheritance: It is the inheritance hierarchy
wherein one derived class inherits from one base class.
Multiple Inheritance:It is the inheritance hierarchy
wherein one derived class inherits from multiple base
class(es)
Hierarchical Inheritance: It is the inheritance
hierarchy wherein multiple subclasses inherits from one
base class.
Multilevel Inheritance: It is the inheritance hierarchy
wherein subclass acts as a base class for other
classes.
Hybrid Inheritance:The inheritance hierarchy that
reflects any legal combination of other four types of
inheritance.

Page 111 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Examples

Single Inheritance
When a class is inherited from one base class,this type
of Inheritance is called Single Inheritance Example
// Inheritance Example
#include <iostream.h>
#include<string.h>
class Fruits
{
public:
char taste[20],color[20];

};
class Orange: public Fruits // Single Inheritance
{

public:

void TasteColor()

Page 112 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

{
strcpy(taste,"sweet-sour");
strcpy(color,"orange");
}
void Display()
{
cout<<"Orange Taste = "<<taste<<endl;
cout<<"Orange Colour ="<<color<<endl;
}
};
int main ()
{
Orange org;
org.TasteColor();
org.Display();
return 0;
}
Output:
Orange's Taste = sweet-sour
Oange's Colour =orange
Multiple Inheritances:
A C++ class can inherit members from more than one
class and here is the syntax:
class derived-class: access base_A, access base_B....
Where access is one of public, protected, or private
and would be given for every base class and they will
be separated by comma as shown above. Let us try the
following example:
#include<iostream.h>
#include<conio.h>

Page 113 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

class A
{
protected:
int m;
};
class B
{
protected:
int o;
};
class C: public A, public B //Use of Multiple
Inheritance
{
public:
void set_m_o()
{
m=5; // m is Inherited from class A
o=6; // o is Inherited from class B
}
void display() // Not Inherited from any class
{
cout<<"m="<<m<<endl;
cout<<"o="<<o<<endl;
cout<<"m*o="<<m*o<<endl;
}
};
int main()
{
A aobj;
B bonj;
C cobj;
cobj.set_m_o();
cobj.display();
return 0;
}
Output:
m=5
o=6
m*o=30

Page 114 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Multi Level Inheritances:


#include<iostream.h>
class A
{
public :
int a1;
};
class B: public A //class B is publicly derived by
class A
{
public :
int b1;
};
class C: public B // //class C is publicly derived by
class B
{
public :
void Cgetdata()
{
cout<<endl<<"Enter the values of a1 and b1";
cin>>a1>>b1; // a1 and b1 are derived from class A and
class B
}
void Cputdata()
{
cout<<endl<<"You have entered a1 = "<<a1<<"and b1 is
="<<b1;
}
};
int main()
{
C obj;
obj.Cgetdata(); //member function of class C
obj.Cputdata(); //member function of class C
return 0

;
}
Output:

Page 115 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Enter the values of a1 and b1


10 20
You have entered a1= 10 b1 = 20
What is inherited from the base class?

In principle, a derived class inherits every member of


a base class except:
its constructor and its destructor its operator=()
members its friends
Although the constructors and destructors of the base
class are not inherited themselves, its default
constructor (i.e., its constructor with no parameters)
and its destructor are always called when a new object
of a derived class is created or destroyed.
If the base class has no default constructor or you
want that an overloaded constructor is called when a
new derived object is created, you can specify it in
each constructor definition of the derived class:
derived_constructor_name (parameters) :
base_constructor_name (parameters) {...}
Example:
// constructors and derived classes
#include <iostream.h>
class A
{
public:

A()
{
cout << "A's no parameter constructor\n";
}
A(int a)
{

Page 116 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

cout << "A's one parameter constructor\n";


}
};
class B : public A
{
public:
B(int a) // A's no parameter constructor will called by
the compiler
{
cout << "B's one parameter constructor\n";
}
};
class C : public A
{
public:
C(int a) : A(a) // Explicit Call to A;s one parameter
constructor
{
cout << "C's one parameter constructor\n";
}
};
int main ()
{
B bobj(0);
C cobj(0);
return 0;
}
A's no parameter constructor
B's one parameter constructor

Page 117 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

A's one parameter constructor


C's one parameter constructor
Notice the difference between which A's constructor is
called when a new B's object is created and which a new
C's object is created. This difference is because of
the constructor declaration of B and C class:
B(int a) // nothing specified: call default by the
compiler to A's no parameter constructor

C(int a) : A(a) // constructor specified: Explicit


call to the A's one parameter constructor

Page 118 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Data File Handling

File

A file is a collection of bytes stored on a secondary


storage device, which is generally a disk of some kind.
The collection of bytes may be interpreted, for
example, as characters, words, lines, paragraphs
,fields and records belonging to a database.
Essentially there are two kinds of files that
programmers deal with text files and binary files.
Text files
A text file can be a stream of characters that a
computer can process sequentially. It is not only
processed sequentially but only in forward direction.
For this reason a text file is usually opened for only
one kind of operation (reading, writing, or appending)
at any given time.
Similarly, since text files only process characters,
they can only read or write data one character at a
time.
Binary files
A binary file is no different to a text file. It is a
collection of bytes. In C++ Programming Language a byte
and a character are equivalent. Hence a binary file is
also referred to as a character stream, but there are
two essential differences.

1.No special processing of the data occurs and each


byte of data is transferred to or from the disk
unprocessed.
2.C++ Programming Language places no constructs on
the file, and it may be read from, or written to,
in any manner chosen by the programmer.
Binary files can be either processed sequentially or,
depending on the needs of the application, they can be
processed using random access techniques. In C++
Programming Language, processing a file using random
access techniques involves moving the current file
position to an appropriate place in the file before

Page 119 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

reading or writing data. This indicates a second


characteristic of binary files. They a generally
processed using read and write operations
simultaneously.
For example, a database file will be created and
processed as a binary file. A record update operation
will involve locating the appropriate record, reading
the record into memory, modifying it in some way, and
finally writing the record back to disk at its
appropriate location in the file.
C++ has two basic classes to handle files, ifstream and
ofstream. To use them, include the header file fstream.
Ifstream handles file input (reading from files), and
ofstream handles file output (writing to files). The
way to declare an instance of the ifstream or ofstream
class is:
ifstream fin;
fin.open("filename");
or
ifstream fin( "filename" );
The default mode for opening a file with ofstream's
constructor is to create it if it does not exist, or
delete everything in it if something does exist in it.
ios::in -- Open file for input mode/read mode
ios::out -- Open file for output mode/write mode
ios::app -- Open file for append mode
ios::binary --Open file in Binary mode

we can combine more than one mode at a time with |


(Logical Or operator)
ofstream fout( "test.txt", ios::in|ios::out );
This will open test.txt file in input as well as in
output mode simultaneously.

Open File in append mode:


ofstream fout( "test.txt", ios::app );

Page 120 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

This will open the file without destroying the current


contents and allow you to append new data.
Detecting End of File
C++ provides a special function, eof( ), that returns
nonzero (meaning TRUE) when there are no more data to
be read from an input file stream, and zero (meaning
FALSE) otherwise.
Rules for using end-of-file (eof( )):
1.Always test for the end-of-file condition before
processing data read from an input file stream.

2.Use a while loop for getting data from an input file


stream.
Example of read from file and display it using eof()
#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("input.txt");
char ch;
while(!fin.eof()) //use of eof() function
{
fin.get(ch);
cout<<ch;
}
fin.close();
getch();
return 0;
}
Program to count number of words
#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("input.txt");
char words[50]; int count=0;

Page 121 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

while(!fin.eof())
{
fin>>words;
count++;
}
cout<<"Number of words in file is "<<count;
fin.close();
getch();
return 0;
}
Program to count number of lines
#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("input.txt");
char line[80]; int count=0;
while(!fin.eof())
{
fin.getline(line,80);
count++;
}
cout<<"Number of lines in file is "<<count;
fin.close();
getch();
return 0;
}

Program to count number of vowels


#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("input.txt");
char ch; int count=0;
while(!fin.eof())
{
fin.get(ch);

Page 122 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
count++;
}
cout<<"Number of vowels in file are "<<count;
fin.close();
getch();
return 0;
}
Program to count number of digits
#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("input.txt");
char ch; int count=0;
while(!fin.eof())
{
fin.get(ch);
if(isdigit(ch))
count++;
}
cout<<"Number of digits in file are "<<count;
fin.close();
getch();
return 0;
}
Program to count number of line starting with alphabet
A.
#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("input.txt");
char line[80]; int count=0;
while(!fin.eof())
{
fin.getline(line,80);

Page 123 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

if(line[0]=='A')
count++;
}
cout<<"Number of lines starting with A are
"<<count;
fin.close();
getch();
return 0;
}
Program to copy contents of one file to another file.
#include<fstream.h>
int main()
{
ifstream fin;
fin.open("source.txt");
ofstream fout;
fout.open("destination.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
fout<<ch;
}
fin.close();
fout.close();
return 0;
}
Binary File Handling Functions

ifstream::read

ifstream& read ( char* t, int n );


Reads a block of data of n characters and stores it in
the array pointed by t.
If the End-of-File is reached before n characters have
been read, the array will contain all the elements read
until it.
Notice that this is an unformatted input function and
what is extracted is not stored as a c++ string format,

Page 124 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

therefore no ending null-character is appended at the


end of the character sequence.
Parameters
t
Pointer to an allocated block of memory where the
content read will be stored.
n
Integer value of type streamsize representing the size
in characters of the block of data to be read.

ofstream::write

ofstream& write ( const char* t , int n );


Writes the block of data pointed by t, with a size of n
characters, into the output buffer. The characters are
written sequentially until n have been written.

This is an unformatted output function and what is


written is not necessarily a c++ string, therefore any
null-character found in the array t is copied to the
destination and does not end the writing process.

Parameters
t
Pointer to a block data with the content to be written.
n
Integer value of type streamsize representing the size
in characters of the block of data to write.

Return Value

The function returns *this.


ofstream::seekp()
ofstream& seekp ( int pos );
ofstream& seekp ( int off, ios::seekdir dir );
Sets the position of the put pointer.
The put pointer determines the location in the output
sequence where the next output operation is going to
take place.

Page 125 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Parameters
pos
The new position in the stream buffer. This parameter
is an integral value.
off
Integral value representing the offset to be applied
relative to an absolute position specified in the dir
parameter.
dir
Seeking direction. It is an object of type ios::seekdir
that specifies an absolute position from where the
offset parameter off is applied. It can take any of the
following member constant values:

ios::beg beginning of the stream buffer


ios::cur current position in the stream buffer
ios::end end of the stream buffer

Return Value
The function returns *this.
Example

// Position of put pointer


#include <fstream.h>
int main () {
long pos;
ofstream outfile;
outfile.open ("example.txt");
outfile.write ("My Name is Ayan",15);
pos=outfile.tellp();
outfile.seekp (pos-4);

outfile.write ("Sanju",5);
outfile.close();
return 0;

Page 126 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

}
In this example, seekp is used to move the put pointer
back to a position 4 characters before the end of the
first output operation. The final content of the file
shall be:
My Name is Sanju
ifstream::seekg()

ifstream& seekg ( int pos );


ifstream& seekg ( int off, ios::seekdir dir );
Sets the position of the get pointer.
The get pointer determines the next location to be read
in the source associated to the stream.

Parameters
pos
The new position in the stream buffer. This parameter
is an integral value of type streampos.
off
Integral value representing the offset to be applied
relative to an absolute position specified in the dir
parameter.
dir
Seeking direction. It is an object of type ios::seekdir
that specifies an absolute position from where the
offset parameter off is applied. It can take any of the
following member constant values:
ios::beg beginning of the stream buffer
ios::cur current position in the stream buffer
ios::end end of the stream buffer
Return Value
The function returns *this.
Example

// load a file into memory


#include <iostream.h>

Page 127 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

#include <fstream.h>
int main () {
int length;
char buffer[100];
ifstream is;
is.open ("test.txt", ios::binary );
// get length of file:
is.seekg (0, ios::end);
length = is.tellg();
is.seekg (0, ios::beg);
// read data as a block:
is.read (buffer,length);
is.close();
cout.write (buffer,length);
return 0;
}

In this example seekg is used to move the get pointer


to the end of the file, and then back to the beginning.

ofstream ::tellp ( );
int tellp ( );
Get position of put pointer
Returns the absolute position of the put pointer.
The put pointer determines the location in the output
sequence where the next output operation is going to
take place.
Return Value
An integral value of type int with the number of
characters between the beginning of the output sequence
and the current position.

Page 128 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Failure is indicated by returning a value of -1.


Example
// position of put pointer
#include <fstream.h>
int main ()
{
long pos;
ofstream outfile;
outfile.open ("test.txt");
outfile.write ("My Name is Ayan",15);
pos=outfile.tellp();
outfile.seekp (pos-4);
outfile.write ("Sanju",5);
outfile.close();
return 0;
}
In this example, tellp is used to get the position of
the put pointer after the writing operation. The
pointer is then moved back 4 characters to modify the
file at that position, so the final content of the file
shall be:
My name is Sanju
ifstream::tellg()
int tellg ( );
Get position of the get pointer.
Returns the absolute position of the get pointer.
The get pointer determines the next location in the
input sequence to be read by the next input operation.
Return Value

Page 129 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

An integral value with the number of characters between


the beginning of the input sequence and the current
position.
Failure is indicated by returning a value of -1.
Example of tellg()

#include <iostream.h>
#include <fstream.h>
int main () {
int length;
char buffer[50];
ifstream is;
is.open ("test.txt", ios::binary );
is.seekg (0, ios::end);

// get length of file:


length = is.tellg();
is.seekg (0, ios::beg);
// read data:
is.read (buffer,length);
is.close();
cout.write (buffer,length);
return 0;
}
In this example, tellg is used to get the position in
the stream after it has been moved with seekg to the
end of the stream, therefore determining the size of
the file.

Some Basic Operations on Binary Files in C++

#include<iostream.h>

#include<string.h>

class student
{
int rollno;

Page 130 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

char name[20];
public:
void getdata()
{
cout<<"\nEnter The Roll no. ";
cin>>rollno;
cout<<"\n\nEnter The Name of The Student ";
gets(name);
}
void showdata()
{
cout<<"\nRoll no. : "<<rollno;
cout<<"\nStudent Name : ";
puts(name);
}
int returnrollno()
{
return rollno;
}
};
This function will write on Binary File
void write_data()
{
student obj;
ofstream fout;
fout.open("student.dat",ios::binary|ios::app);
obj.getdata();
fout.write((char*)&obj,sizeof(obj));
fout.close();
}

This function will display records


void display()
{
student obj;
ifstream fin;
fin.open("student.dat",ios::binary);
while(fin.read((char*)&obj,sizeof(obj)))
{
obj.showdata();
}
fin.close();
}

Page 131 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

This function will search and display from binary file


void search (int n)
{
student obj;
ifstream fin;
fin.open("student.dat",ios::binary);
while(fin.read((char*)&obj,sizeof(obj)))
{
if(obj.returnrollno()==n)
obj.showdata();
}
fin.close();
}

This function will delete a record

void deleterecord(int n)
{
student obj;
ifstream fin;
fp1.open("student.dat",ios::binary);
ofstream fout;
fout.open("Temp.dat",ios::out|ios::binary);
while(fin.read((char*)&obj,sizeof(obj)))
{
if(obj.returnrollno()!=n)
fout.write((char*)&obj,sizeof(obj));
}
fin.close();
fout.close();
remove("student.dat");
rename("Temp.dat","student.dat");
}

This function will modify a record


void modifyrecord(int n)
{
fstream finout;
student obj;
int found=0;
finout.open("student.dat",ios::in|ios::out);
while(finout.read((char*)&obj,sizeof(obj)) &&
found==0)
{

Page 132 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

if(obj.returnrollno()==n)
{
obj.showdata();
cout<<"\nEnter The New data of student";
obj.getdata();
int pos=-1*sizeof(obj);
finout.seekp(pos,ios::cur);
finout.write((char*)&obj,sizeof(obj));
found=1;
}
}
finout.close();
}

Page 133 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Pointer
A pointer is a variable which contains the address in
memory of another variable. We can have a pointer to
any variable type.
The & operator gives the address of the variable
pointed by the pointer. The indirection or dereference
operator * gives the contents of the variable pointed
to by a pointer.
To declare a pointer to a variable do:
Data-type *pointer_variable_name;
NOTE: We must associate a pointer to a particular type:
You can't assign the address of a short int to a long
int, for instance.
Consider the effect of the following code:
int x = 1, y = 2;
int *ip;
ip = &x;
y = *ip;
x = ip;
*ip = 3;
Assume that the variable x resides at memory location
100, y at 200 and ip at 1000.

Page 134 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

The assignments x = 1 and y = 2 load these values into


the variables. ip is declared to be a pointer to an
integer and is assigned to the address of x (&x). So ip
gets loaded with the value 100.
Next y gets assigned to the contents of ip. In this
example ip currently points to memory location 100 ,the
location of x. So y gets assigned to the values of x,
which is 1.
It is legal to assign the current value of ip to x. The
value of ip at this instant is 100.Finally we can
assign a value to the contents of a pointer (*ip).
IMPORTANT: When a pointer is declared it does not point
anywhere. You must set it to point somewhere before you
use it.
So ...
int *ip;
*ip = 100;
will generate an error
The correct use is:
int *ip;

int x;

Page 135 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

ip = &x;
*ip = 100; // Now the value of x is 100
We can do integer arithmetic on a pointer:
int *ip;
int i=10;
ip= &i;
*ip = *ip + 5;
++*ip;
(*ip)++;
// The value of i and *ip would be 17
The reason we associate a pointer to a data type is so
that it knows how many bytes the data is stored in.
When we increment a pointer we increase the pointer by
one block memory.
So for a character pointer ++ch_ptr adds 1 byte to the
address.For an integer pointer ++ip_ptr adds 2 bytes to
the address. For a float pointer ++flp_ptr adds 4 bytes
to the address.
Consider a float variable (fl) and a pointer to a float
(flp)

Pointer Arithmetic Assume that flp points to fl then if


we increment the pointer ( ++flp) it moves to the
position shown 4 bytes on. If on the other hand we
added 2 to the pointer then it moves 2 float positions
i.e 8 bytes as shown in the Figure.

Page 136 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Dynamic memory allocation/deallocation operators

// Use of new and delete operators


#include <iostream.h>

int main ()
{
int *intp = NULL; // Pointer initialized with null
intp = new int; // Request memory for the variable

*intp = 123; // Store value at allocated address


cout << "Pointer intp = " << *intp << endl;
delete intp ; // free up the memory.
return 0;
}
Reference variable
A reference variable is an alias, that is, another name
for an already existing variable. Once a reference is
initialized with a variable, either the variable name
or the reference name may be used to refer to the
variable.
Reference vs Pointer variable:
References are often confused with pointers but three
major differences between references and pointers are:
1. You cannot have NULL reference for a reference
variable
2. Once a reference variable is initialized to an
object, it cannot be changed to refer to another
object. Pointers can be pointed to another object
at any time.
3. A reference must be initialized when it is created.
Pointers can be initialized at any time.
// Reference variable Example
#include <iostream.h>
int main ()
{
// declare simple variables
int i;
Page 137 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

// declare reference variables


int &r = i; // Now we can refer i as r or r is a
alias for i
i = 5;
cout << "Value of i = " << i << endl;
cout << "Value of reference variable r = " << r <<
endl;
return 0;
}
Output
Value of i = 5
Value of reference variable r = 5
Call by value and Call by Reference
When C++ passes arguments to functions it passes them
by value. There are many cases when we may want to
alter a passed argument in the function and receive the
new value back to the calling function. C++ uses
pointers explicitly to do this. The best way to study
this is to look at an example where we must be able to
receive changed parameters. Let us try and write a
function to swap variables:
// Call by Value Example
#include<iostream.h>
int main()
{
void swap(int m,int m);
int a=10 ,b=20;
swap(a,b); // Call by value
cout<<"After interchanging the values ";
cout<<" a = "<<a<<endl<<"b = "<<b;
return 0;
}
void swap(int m ,int n)
{
int a;
a=m;
m=n;
n=a;
cout<<"Inside swap function the values are ";
cout<<endl<<" m = "<<m<<endl<<" n= "<<n;

Page 138 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

}
output:
Inside swap function the values are
m=20
n=10;
After interchanging the values
a=10
b=20
Note: No change to the values of a and b inside the
calling function .Because when we pass values to the
function only the copies of those values get passed not
the original data value .Any change made inside the
called function to these data value is not reflected to
the calling function. That is why we call it call by
value.
swap(a, b) WON'T WORK.
Pointers provide the solution: Pass the address of the
variables to the functions and access address of
function.
Thus our function call in our program would look like
this:
swap(&a, &b)
// Call by Reference Example
#include<iostream.h>
int main()
{
void swap(int *m,int *m);
int a=10 ,b=20;
swap(&a,&b); // Call by reference
cout<<"After interchanging the values ";
cout<<" a = "<<a<<endl<<"b = "<<b;
return 0;
}
void swap(int *m ,int *n)

Page 139 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

{
int a;
a=*m;
*m=*n;
*n=a;
cout<<"Inside swap function the values are ";
cout<<endl<<" *m = "<<m<<endl<<" *n= "<<n;
}
output:
Inside swap function the values are
*m=20
*n=10;
After interchanging the values
a=20
b=10

Note: The values of a and b changed .Because when we


pass reference of the values to the function original
data value are passed .Any change made inside the
called function to these data value is reflected to the
calling function. That is why we call it call by
Reference.

Let us see another way of call by reference using C++


reference variable .

// Using Reference variables method


#include<iostream.h>
int main()
{
void swap(int &m,int &m);
int a=10 ,b=20;
cout<<"After interchanging the values ";
swap(a,b); // Call by value
cout<<" a = "<<a<<endl<<"b = "<<b;
return 0;

Page 140 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

}
void swap(int &m ,int &n)// use of reference variable
{
int a;
a=m;
m=n;
n=a;
cout<<"Inside swap function the values are ";
cout<<endl<<" m = "<<m<<endl<<" n= "<<n;
}
output:
Inside swap function the values are
m=20
n=10;
After interchanging the values
a=20
b=10
Pointers and Arrays
Pointers and arrays are very closely linked.
Consider the following:
int a[10], x;
int *pa;
pa = &a[0]; /* pa pointer to address of a[0] */
x = *pa;
/* x = contents of pa (a[0] in this case) */

Arrays and Pointers


To get somewhere in the array using a pointer we could
do:
(pa + i)= a[i]
C++ however is much more subtle in its link between
arrays and pointers.
For example we can just type
pa = a;
instead of

Page 141 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

pa = &a[0]
and
a[i] can be written as *(a + i).
We also express pointer addressing like this:
pa[i] = *(pa + i).
However pointers and arrays are different:
A pointer is a variable. We can do
pa = a;
pa++ ;
An Array is not a variable.
a = pa and a++ ARE ILLEGAL.
We can now understand how arrays are passed to
functions. When an array is passed to a function what
is actually passed is its initial elements location in
memory.
So:
int a[]={1,2};
void arpass(int a[]);
arpass(a) ;
/* Passing array in a function. Here only name of the
array is required, it is same as arpass(&a[0]); */
Example of passing array in a function
#include <iostream.h>
int main ()
{
int a[]={1,2}; // Declare simple int arry
void arpass(int a[]); // Function declaration for
accepting array as an argument

arpass(a); //At the time of call only the name of the


array needs to specified

Page 142 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

return 0;
}
void arpass(int a[]) // Function Definition
{
for(int i=0;i<2;i++)
cout<<a[i];
}
Pointer to an One Dimensional Array
#include <iostream.h>
int main ()
{
int i,a[5];
int *p;
p=a; // same as p = &a[0]
cout<<endl<<"Enter 5 Numbers ";

for(i=0;i<5;i++)
cin>>p[i]; // same as a[i]
//Other form of the above statement is cin>>*(p+i);

cout<<endl<<"You have Entered";

for(i=0;i<5;i++)
cout<<p[i]<<endl; // same as a[i]
// Other form of the above statement is cout<<*(p+i);

return 0;
}
Function Returning a Pointer
If a function return type is a Pointer of any data type
then we say that this function will return Pointer.

// A c++ Example of Function returning Pointer


#include<iostream.h>
int main()
{
int *func(int a); // this function will return a
Pointer
int *p;
int a;
cout<<"Enter a Number";

Page 143 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

cin>>a;
p=func(a); // P will point to the pointer
returned by *func()
cout<<" *p = "<<*p;
return 0;
}
int *func(int a)
{
int *t;
t =&a;
return t; // This statement will return a
Pointer
}

Arrays of Pointers

There may be a situation when we want to maintain an


array which can store pointers to an int or char or any
other data type available. Following is the declaration
of an array of pointers to character:
int *ptr[SIZE];
This declares ptr as an array of SIZE integer pointers.
Thus, each element in ptr, now holds a pointer to an
integer value. Following example makes use of two
integer pointers which will be stored in an array of
pointers as follows:
Array of Pointer Example:
#include <iostream.h>
const int SIZE = 2;
int main ()
{
int i=10,j=20 ,*ip ,*jp;
int *arrp[SIZE];
ip=&i;
jp=&j;
arrp[0]=ip;
arrp[1]=jp;

for (int t = 0; t < SIZE; t++)

Page 144 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

{
cout << "Value of arrp[" << t << "] = ";
cout << *arrp[i] << endl;
}
return 0;
}
When the above code is compiled and executed, it
produces following result:
Value of arrp[0] = 10
Value of arrp[1] = 20

Pointers and Structures


These are fairly straight forward and are easily
defined. Consider the following:
struct Ayan
{
int a,b;
}ap;
struct Ayan *aptr;
aptr = &ap; // assigns pointer to &ap
the -> operator lets us access a member of the
structure pointed to by a pointer i.e.:
aptr->a = 10;
aptr->b = 20;
Example of Pointers and Structure
#include <iostream.h>
struct Ayan
{
int a,b;
}ap; // Structure variable
struct Ayan *aptr; // Pointer Structure variable
int main()
{
aptr = &ap; // Assigns address of ap to pointer aptr
Page 145 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

// Accessing structure members through Pointer


aptr->a=10;
aptr->b=20;
cout<<endl<<"a =" <<aptr->a<<" b = "<<aptr->b;
return 0;
}
Output
a=10
b=20;
Self Referential Structure
Suppose we have a structure declaration linke this
struct list
{
int data;
struct list *next;
//Above statement makes struct list as self
referential
}*node;
Any structure which have a member of type structure
itself is called a Self referential structure. In the
above example structure list contain a member *next
whose data type is structure itself, this will makes
struct list as Self Referential Structure. These types
of structures are generally used for Queue,Stack and
Linked List implementation.

Page 146 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

XII COMPUTER SCIENCE UNIT II C++

Page 147 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Array

An array is a series of elements of the same type


placed in contiguous memory locations that can be
individually referenced by adding an index to a unique
identifier.
That means that, for example, we can store 5 values of
type int in an array without having to declare 5
different variables, each one with a different
identifier. Instead of that, using an array we can
store 5 different values of the same type, int for
example, with a unique identifier.
Arrays come in two flavors: one dimensional and
dimensional arrays.
Declaring an Array
Just like any variable ,an array has to be declared
before being used. Yet the difference this time is that
you need to tell the compiler what kind of array you
are defining. This is because, once more, the compiler
wants to know how much space your array is going to
occupy in the computer memory. This is because when you
declare an array of items, the compiler puts each one
of the items in an appropriate location.
Like any other variable, the syntax of declaring an
array is:
DataType ArrayName[size]

Page 148 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

The array is first identified by its kind, which could


be a char, an int, a float, etc; followed by its name.
The name is then followed by square brackets that
specify the size of the array.
Here are examples of declaring arrays:
int a[4];
float f[100];
double d[100];
int a[4]; declares a group or array of 4 values, each
one being an integer.

float f[100]; declares an array of 100 floating-point


values.
double d[100]; declares an array of double-precision
numbers. There are 100 of these items in the group.
Initializing an Array
Just like any variable can be initialized, an array
also can be initialized. To accomplish this, for a one-
dimensional array, the syntax used is:
DataType ArrayName[size] = { element1, element2, ,
elementn};
Here are examples of declaring an initializing arrays:
int num[5] = {1,2,3,4,5};
If you have decided to initialize the array while you
are declaring it, you can omit the size. Therefore,
array can be declared as follows:
int num[] = {1,2,3,4,5};
Processing the Elements of an Array
Page 149 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

After initializing an array, its elements are counted


from left to right. Each element of the array, also
called a member of the array, has a specific and
constant position. The position of an item is also
called its index. The first member of the array, the
most left, has an index of 0. The second member of the
array has an index of 1. Since each array has a number
of items which can be specified as n, the last member
of the array has an index of n-1
Based on this system of indexing, to locate a member of
an array, use its index in the group. Imagine you
declare and initialize an array as follows:
double weight[] = {20.2,24.5,34.7};
To locate the value of the 3rd member of the array, you
would type weight[2]. In the same way, the 1st member
of the array can be located with weight[0].
Once you can locate a member of the array, you can
display its value. Here is an example:
#include <iostream.h>

int main()
{
double weight[] = {20.2,24.5,34.7};
cout << "2nd member = " << weight[1] << endl;
cout << "3rd member = " << weight[2] << endl;
return 0;
}
This would produce:
2nd member = 24.5
3rd member = 34.7
The Size of an Array

When declaring an array, we saw that you must specify


the number of items that the array is made of. Here is
an example:
float price[5];

Page 150 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Depending on how you want to deal with your array, you


may sometimes need to increase or decrease its
dimension. To do this, you would need to locate the
declaration of the array and change its dimension. If
the program is long and the array is declared in some
unusual place, this could take some time.
The alternative is to define a constant prior to
declaring the array and use that constant to hold the
dimension of the array. Here is an example:

#include <iostream.h>
int main()
{
const int SIZE = 5;
int weight[SIZE] = {20,30,40,50,60};
cout << "weight 1: " << weight[0] << endl;
cout << "weight 2: " << weight[1] << endl;
cout << "weight 3: " << weight[2] << endl;
cout << "weight 4: " << weight[3] << endl;
cout << "weight 5: " << weight[4] << endl;
return 0;
}
We knew the dimensions of the arrays we have used so
far, because we could count the number of members of
the array. Imagine you declare a large array, possibly
made of 50 or 100 members, you wouldn't start counting
the number of members. C++ provides the sizeof operator
that can be used to get the dimension of an array. The
syntax you would use is:
sizeof(NameofArray)
If we declare an array as follows:
int number[] = {1,2,3,4,5};
Instead of counting the number of members of this array
we can use the sizeof operator as follows:
int NumberOfElements = sizeof(Number)/sizeof(int);
Accessing Array Members
int items[5];

Page 151 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Each member of the array can be located using its


index, as we have seen so far. In the same way, you can
request the value of any member of the array using its
index. In the following example, we declare an array of
5 integers and then we request the values of the 2nd
and the 4th members:
#include <iostream.h>
int main()
{
const int count = 5;
int items[count];
cout << "Enter the values of two items\n";
cout << "Item 1: ";
cin >> items[0];
cout << "item 4: ";
cin >> items[3];
cout << "\nYou have Entered following values";
cout << "\nItem 1: " << items[0] ;
cout << "\nItem 4: " << items[3] ;
return 0;
}
Here is an example of running the program:
Enter the values of two items
Item 1: 45
Item 4: 66
You have Entered following values
item 1: 45
item 4: 66
Operations on Arrays
We can add the values of two members of the
array(Number[2]+Number[0]), you can subtract the value
of one of the members from another member(member[1]-
Number[4]). In the same way, you can perform
multiplication, division, or remainder operations on
members of an array.

Deletion from an Array


#include <iostream.h>

Page 152 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

int main()
{
int array[100], position, c, n;
cout<<"Enter number of elements in array\n";
cin>>n;

for ( c = 0 ; c < n ; c++ )


cin>>array[c];
cout<<"Enter the location where you wish to delete \n";
cin>>position;

if ( position >= n+1 )


cout<<"Deletion not possible.\n";
else
{
for ( c = position - 1 ; c < n - 1 ; c++ )
array[c] = array[c+1];
cout<<"Resultant array is\n";
for( c = 0 ; c < n - 1 ; c++ )
cout<<array[c]<<endl;
}
return 0;
}
Concatenation of two Linear Arrays
#include<iostream.h>
#define N 5
int main()
{
int a1[N],a2[N],a3[N+N];
int i,j;
cout<<"Enter Elements of First Array:";
for(i=0;i<N;i++)

Page 153 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

cin>>a1[i];
cout<<"Enter Elements of Second Array:";
for(i=0;i<N;i++)
cin>>a2[i];
// Now we will Concatenate These two Arrays
for(i=0;i<N;i++)
a3[i]=a1[i];
k=i;
for(i=0;i<N;i++)
a3[k++]=a2[i];
cout<<"After Concatenation The third Array Contain:";
for(i=0;i<N+N;i++)
cout<<a3[i]<<endl;
return 0;
}
Merging of Two sorted Arrays
#include <iostream.h>

void merge(int [], int, int [], int, int []);


int main()
{
int a[100], b[100], m, n, c, sorted[200];
cout<<"Input number of elements in first array\n";
cin>>m;

for (c = 0; c < m; c++)


cin>>a[c];

cout<<"Input number of elements in second array\n";


cin>>n;

for (c = 0; c < n; c++)


cin>>b[c];
merge(a, m, b, n, sorted);

cout<<"Sorted array:\n";
for (c = 0; c < m + n; c++)
cout<<sorted[c];
return 0;
}
void merge(int a[], int m, int b[], int n, int
sorted[])
{
int i, j, k;

Page 154 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

j = k = 0;
for (i = 0; i < m + n;)
{
if (j < m && k < n)
{
if (a[j] < b[k])
{
sorted[i] = a[j];
j++;
}
else
{
sorted[i] = b[k];
k++;
}
i++;
}
else if (j == m)
{
for (; i < m + n;)
{
sorted[i] = b[k];
k++;
i++;
}
}
else {
for (; i < m + n;)
{
sorted[i] = a[j];
j++;
i++;
}
}
}
}
Linear Search
Another type of operation regularly performed on an
array consists of looking for a value held by one of
its members. For example, you can try to know if one of
the members holds a particular value you are looking
for. Here is an example:
#include <iostream.h>

Page 155 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

int main()
{
// Declare the members of the array

int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int find;
int i, m = 8;
cout << "Enter a number to search: ";
cin >> find;
for (i = 0;i < m; ++i)
if(numbers[i]== find)
cout << find << " Found" << endl;
//Find whether the number typed is a member of the
array
if (i == m)
cout << find << " Not Found" << endl;
return 0;
}
This would produce:
Enter a number to search: 44
44 Found
Binary Search
Another type of search in an Array is Binary search.
Binary search can work only on sorted array.

Page 156 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

#include <iostream.h>
int main()
{ // Declare the members of the array
int numbers[] = {12, 17, 23, 45, 50, 71, 80, 93};
int find;
int mid,low=0,high=7;
cout << "Enter a number to search: ";
cin >> find;
while(low<=high)
{
mid= (low+high)/2;
if( find==numbers[mid])
{
cout<<"Element Found";
break;
}
else if( find >numbers[mid])

low=mid+1;

Page 157 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

else
high=mid-1;
}
if(low>high)
cout<<"Element not Found";
return 0;
}
This would produce:
Enter a number to search: 23
Element Found

Bubble Sort
The basic idea of Bubble sort is to compare two
adjoining values and exchanged then if are not in
proper order.

// Example of Bubble Sort


#include <iostream.h>
int main()

{ // The members of the array


int numbers[] = {43, 36, 25, 89, 20, 52, 75, 10};
int minimum = numbers[0];
int a = 8,temp;
// Compare the members
for (int i = 0; i < 7; ++i)
for(int j=i+1;j<7;j++)
if (number[i] > number[j])

Page 158 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

{
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
cout << "After Sorting The Array elements are ";
for(i=0;i<7;i++)
cout<<number[i]<<endl;
return 0;
}
This would produce:
10,20,25,36,43,52,75,89.

Selection Sort
The algorithm works as follows:

1. Find the minimum value in the array


2. Swap it with the value in the first position

3. Repeat the steps above for the remainder of the


array (starting at the second position and
advancing each time)
Effectively, the array is divided into two parts: the
sublist of items already sorted, which is built up from
left to right and is found at the beginning, and the
sublist of items remaining to be sorted, occupying the
remainder of the array.

Here is an example of this sort algorithm sorting five


elements:
64 25 12 22 11
11 25 12 22 64
11 12 25 22 64
11 12 22 25 64
11 12 22 25 64
// Example of Selection Sort

Page 159 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

#include<iostream.h>
#define n 10
int main()
{
int a[n];
int i,j,k,temp;
int iMin;
cout<<"Enter Array Elements "<<endl;
for(k=0;k<n;k++)
cin>>a[k];
for (j = 0; j < n-1; j++)
{ /* find the min element in the unsorted a[j .. n-
1]
assume the min is the first element */
iMin = j;
// test against elements after j to find the
smallest
for ( i = j+1; i < n; i++)
{
// if this element is less, then it is the new
minimum
if (a[i] < a[iMin])
iMin = i;
}
// iMin is the index of the minimum element. Swap it
with the current position
if ( iMin != j )
{ temp=a[j];
a[j]=a[iMin];
a[iMin]=temp;
}
}
cout<<"After Selection Sort Array Elements are
"<<endl;
for(k=0;k<n;k++)
cout<<a[k]<<endl;
return 0;
}
Insertion Sort
Insertion sort is a simple sorting algorithm: a
comparison sort in which the sorted array (or list) is
built one entry at a time.

Page 160 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

How it works:
In insertion sort,elements are entered into the array
1-by-1.
When the first element is entered, it is placed at the
1st position in the array.
When a new element is entered, it is compared to our
already entered element and is decided whether to place
before or after it in the array.
Now when the third element is entered is entered, it is
compared with the greater element of the 2 already
existing elements. If smaller, then it is swapped. If
not, then the array can be considered sorted.
If swapped, then is compared with the smaller element
of the 2 already existing elements and swapped again
with it if it is even smaller.

Similarly, all the the numbers to be placed in the


array are entered 1-by-1 and placed into the correct
position right when theyre entered.

Example:

The following table shows the steps for sorting the


sequence 5 7 0 3 4 2 6 1. On the left side the sorted
part of the sequence is shown. For each iteration, the
number of positions the inserted element has moved is
shown in brackets. Altogether this amounts to 17 steps.

5 7 0 3 4 2 6 1 (0)
5 7 0 3 4 2 6 1 (0)
0 5 7 3 4 2 6 1 (2)
0 3 5 7 4 2 6 1 (2)
0 3 4 5 7 2 6 1 (2)
0 2 3 4 5 7 6 1 (4)
0 2 3 4 5 6 7 1 (1)
0 1 2 3 4 5 6 7 (6)

#include<iostream.h>
int main()

Page 161 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

{
double arr[8],temp;
cout<<"Insertion sort Demonstration."<<endl<<endl;
for (int i=0;i<8;i++)
{
cout<<"Enter element number "<<i+1<<": ";
cin>>arr[i];
//Runs until the new number has been placed in its
correct place

while(j>0 && arr[j]<arr[j-1])


{
//Swap if the elements are out of order.
temp=arr[j];
arr[j]=arr[j-1];
arr[j-1]=temp;
j--; //decrease array index
}
}
cout<<endl<<"Array After Sorting = ";
for(i=0;i<8;i++)
cout<<arr[i]<<endl;
return 0;

Arrays and Functions


An array can be passed to a function as argument. An
array can also be returned by a function. To declare
and define that a function takes an array as argument,
declare the function as you would do for any regular

Page 162 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

function and, in its parentheses, specify that the


argument is an array. Here is an example:

You don't have to specify the dimension of the array.


This means that you can leave the square brackets
empty:

#include <iostream.h>
int main()
{
void Display(char items[]);
const int NumberOfItems = 5;
char items[NumberOfItems] = {'A','B','C','D','E'};
Display(items); //The compiler only needs the name of
the array to process it
return 0;
}

void Display(char items[])


{
for(int i = 0; i < 5; ++i)
cout << "\nItmem " << i + 1 << ": " << items[i];
cout << endl;
}

When we call a function that has an array as argument,


the compiler only needs the name of the array to
process it.
Two-Dimensional Arrays
A 2-dimensional array is an array of arrays. In other
words, it is an array where each member of the array is
also an array.

Page 163 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Declaring and Initializing a 2-Dimensional Array

Two-dimensional array is made of rows and columns. Each


column represents one category of data that everyone of
the rows shares with the other rows. To declare it, use
double pair of a opening and closing square brackets.

Data_Type NameOfArray[ROWS][COLUMNS];
int TwoDArray[5][5];
This declarations creates 5 rows and each row contains
5 elements.
You can initialize an array the same way you would
proceed the a one-dimensional array: simply provide a
list of values in the curly brackets.
A multidimensional array is represented as an algebraic
matrix as MxN. This means that the array is made of M
rows and N columns. Total number of elements of a
multidimensional array can be calculated by multiply
the number of rows by the number of columns. Therefore
a 2x3 array contains 2*3=6 elements.
Based on this, when initializing a 2-dimensional array,
make sure you provide a number of values that is less
than or equal to the total number of elements.
Here is an example:
double age[2][3] = {12,14,16,17,18,19};

Page 164 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

To locate a member of the array, this time, each must


be identified by its double index. The first member is
indexed at [0][0]. The second is at [0][1]. For a 2x3
array as this one, the 5th member is at [1][1]. You can
use this same approach to display the values of the
members of the array. Here is an example:
#include <iostream.h>
int main()
{ // A 2-Dimensional array
int TwoDArray[2][3] = {1,2,3,4,5,6};
// Display the array
cout << "Elements of the array";
cout<<"\nTwoDArray [0][0]" << ": " << TwoDArray[0][0];
cout<< "\nTwoDArray [0][1]" << ": " << TwoDArray[0][1];
cout<< "\nTwoDArray [0][2]" << ": " << TwoDArray[0][2];
cout<< "\nTwoDArray [1][0]" << ": " << TwoDArray[1][0];
cout<< "\nTwoDArray [1][1]" << ": " << TwoDArray[1][1];
cout<< "\nTwoDArray [1][2]" << ": " << TwoDArray[1][2];
cout << endl;
return 0;
}
Output:
Elements of the array
TwoDArray [0][0]: 1
TwoDArray [0][1]: 2
TwoDArray [0][2]: 3
TwoDArray [1][0]: 4
TwoDArray [1][1]: 5
TwoDArray [1][2]: 6
C++ also allows you to include each row in its own pair
of curly brackets. You must separate each row from the
next with a comma. Here is an example:

int items[2][3] = { { 1,2,3},{4,5,6} };

Page 165 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Representation of 2D array in memory


Lets assume Arr is an two dimensional 2 X 2 array .The
array may be stored in memory one of the following
way :-

1. Column by column i.e column major order


2. Row by row i.e row major order.
Both representations of the above array.
Column Major Order-Column fixed for each row

Row major Order-Row fixed for each column

We know that computer keeps track of only the base


address. So the address of any specified location of an
array , for example Arr[j,k] of a 2 d array Arr[m,n]
can be calculated by using the following formula :
Column major order
Address(Arr[j][k])= base(Arr)+w[m(k-1)+(j-1)]
Row major order
Address(Arr[j][k])=base(Arr)+w[n(j-1)+(k-1)]
For example Arr[25][4] is an array with base value
200,w=4 for this array. The address of Arr[12][3] can
be calculated using
Row-major order as
Address(Arr[12][3] )= 200+4[4(12-1)+(3-1)]
Page 166 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

=200+4[4*11+2]
=200+4[44+2]
=200+4[46]
=200+184
=384
Column-major order as
Address(Arr[12][3] )= 200+4[25(3-1)+(12-1)]
=200+4[25*2+11]
=200+4[50+11]
=200+4[61]
=200+244
=444
Processing a 2-Dimensional Array
To process a 2D array, we should know how many columns
the array contains. We can use two for loops to process
the array. Here is an example:

#include <iostream.h>
int main()
{
// A 2-Dimensional array
int items[2][3] = {
{ 1,2,3},
{ 4,5,6}
};

// Display all elements


cout << "Elements of the array";
for(int i = 0; i < 2; ++i)
for(int j = 0; j < 3; ++j)
cout << "\nItems[" << i << "][" << j << "]: "
<< items[i][j];
cout << endl;
return 0;
}

Finding Sum and Difference of two N X M Arrays

#include <iostream.h>
#define N 3
#define M 3
int main()

Page 167 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

{
int a1[N][M],a2[N][M],s[N][M],d[N][M];
int sum=0,i,j;
cout<<"Enter Elelemts of First Array";
for(i=0;i<N;i++)
for(j=0;j<M;j++)
cin>>a1[i][j];
cout<<"Enter Elelemts of Second Array";
for(i=0;i<N;i++)
for(j=0;j<M;j++)
cin>>a2[i][j];
// Mow we will find sum and difference
for(i=0;i<N;i++)
for(j=0;j<M;j++)
{
s[i][j] =a1[i][j]+a2[i][j];
d[i][j] =a1[i][j]-a2[i][j];
}
cout<<"Sum of a1 and a2 is";
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
cout<<s[i][j];
cout<<endl;
}
cout<<"Difference of a1 and a2 is";
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
cout<<d[i][j];
cout<<endl;
}
return 0;
}
Interchanging ROWS and COLUMN of a N X M Arrays
#include <iostream.h>
#define N 3
#define M 3
int main()
{
int a1[N][M],a2[N][M];
int i,j;
cout<<"Enter Elements Array";
for(i=0;i<N;i++)
for(j=0;j<M;j++)

Page 168 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

cin>>a1[i][j];
// Mow we will Interchange row and columns
elements
for(i=0;i<N;i++)
for(j=0;j<M;j++)
a2[j][i] =a1[i][j];
cout<<"Original Array is";
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
cout<<a1[i][j];
cout<<endl;
}
cout<<"After interchanging row and columns ";
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
cout<<a2[i][j];
cout<<endl;
}
return 0;
}
2D Array and String
Because strings are in fact sequences of characters, we
can represent them also as plain arrays of char
elements.

For example, the following array:


char Ayan[20];
is an array that can store up to 20 elements of type
char. In this array, we can store sequences of
characters up to 20 characters long. But we can also
store shorter sequences. For example, Ayan could store
at some point in a program either the sequence "Hello"
or the sequence "Happy Diwali", since both are shorter
than 20 characters.
Therefore, since the array of characters can store
shorter sequences than its total length, a special
character is used to signal the end of the valid
sequence: the null character, whose literal constant
can be written as '\0' (backslash, zero).

Our array of 20 elements of type char, called Ayan, can


Page 169 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

be represented storing the characters sequences "Hello"


and "Happy Diwali" as:

Notice how after the valid content a null character


('\0') has been included in order to indicate the end
of the sequence.
Initialization of null-terminated character sequences
If we want to initialize an array of characters with
some predetermined sequence of characters we can do it
just like any other array:
char Ayan[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
In this case we would have declared an array of 6
elements of type char initialized with the characters
that form the word "Hello" plus a null character '\0'
at the end.
Arrays of char elements have an additional method to
initialize their values: using string literals. String
literals enclosed between double quotes always have a
null character ('\0') automatically appended at the end
by the compiler. Therefore we can initialize the array
of char elements called Ayan with a null-terminated
sequence of characters by either one of these two
methods:
char Ayan[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char Ayan[] = "Hello";
In both cases the array of characters Ayan is declared
with a size of 6 elements of type char: the 5
characters that compose the word "Hello" plus a final
null character ('\0') which specifies the end of the
sequence and that, in the second case, when using
double quotes (") it is appended automatically.
Using null-terminated sequences of characters

Page 170 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Null-terminated sequences of characters are the natural


way of treating strings in C++.For example, cin and
cout support null-terminated sequences as valid
containers for sequences of characters, so they can be
used directly to extract strings of characters from cin
or to insert them into cout. For example:

// null-terminated sequences of characters


#include <iostream.h>
int main ()
{
char yourname[] = "Please, enter your first name: ";
char message [] = "Hello, ";
char name [80];
cout << yourname;
cin >> name;
cout << message << name << "!";
return 0;
}

Please, enter your first name: Sanjeev


Hello, Sanjeev!

As you can see, we have declared three arrays of char


elements. The first two were initialized with string
literal constants, while the third one was left
uninitialized. In the first two arrays the size was
implicitly defined by the length of the literal
constant they were initialized to. While for name we
have explicitly specified that it has a size of 80
chars.

Page 171 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Stack
Stack is one of the important data structures that
every computer programmer should be aware of. It
follows the simple LIFO (Last In First Out) principle.
Implementation of stack can be done in many ways. One
of the simplest way is using Arrays. Here an array is
initialized to a maximum value first, lets call it
capacity. As and when we push elements onto the array,
its size will get increased. As and when we pop
elements from the array, its size will get decreased

Array Implementation of stack


//Program for Stack implementation through Array
#include <iostream.h>
#include<ctype.h>
#include<conio.h>
#define MAXSIZE 3
int stack[MAXSIZE];
int top; //index pointing to the top of stack
int main()
{
void push(int);
int pop();
int item,num;
cout<<"Enter the data to stack.";
cin>>num;
push(num);
cout<<"Enter the data to stack.";
cin>>num;

Page 172 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

push(num);
cout<<"Enter the data to stack.";// Use to check stack
full condition
cin>>num;
push(num);
cout<<"Enter the data to stack.";
cin>>num;
push(num);
item=pop();
cout<<endl<<"Top Element of the stack is "<<item;
item=pop();
cout<<endl<<"Top Element of the stack is "<<item;
item=pop();
cout<<endl<<"Top Element of the stack is "<<item;
item=pop(); // use to check stack empty condition
return 0;
}
void push(int y)
{
if(top==MAXSIZE)
{
cout<<endl<<"STACK FULL";
return;
}
else
{
top++;
stack[top]=y;
}
}
int pop()
{
int a;
top--;
if(top<0)
{
cout<<endl<<"STACK EMPTY";
return 0;
}
else
{
a=stack[top];
}
return a;
}

Page 173 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Stack implementation as Linked List


#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *top;
int main()
{
void push(int);
void pop();
void display();
int wish, num,will,a;
wish = 1;
top = NULL;
clrscr();
cout<<"Program for Stack as Linked List demo.";
while(wish == 1)
{
cout<<endl<<"Main Menu \n1.Enter data in
stack\n2.Delete from stack\n0. for Exit";
cin>>will;
switch(will)
{
case 1:
cout<<endl<<"Enter the data";
cin>>num;
push(num);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 0:
exit(0);
}
cout<<endl<<"Do you want to continue, press 1";
cin>>wish;
}
return 0;

Page 174 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

}
//THIS FUNCTION INSERT NODE IN THE TOP OF THE STACK
void push(int y)
{
struct node *x;
x=(node *)malloc(sizeof(struct node));
x->data = y;
x->link = top;
top = x;
}
//THIS FUNCTION REMOVES TOP NODE FROM THE STACK AND
RETURNS ITS VALUE
void pop()
{
int a;
if(top==NULL)
{
cout<<"STACK EMPTY...";
return ;
}
else
{
a=top->data;
cout<<endl<<"The value at the top of stack is "<<a;
top=top->link;
}
}
//THIS FUNCTION DISPLAY ELEMENTS OF STACK
void display()
{
int i =0;
struct node * temp;
temp = top;
while(temp!=NULL)
{
cout<<temp->data<<endl;
temp=temp->link;
}
}

Page 175 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Queue

Queue is a linear data structure in which data can be


added to one end and retrieved from the other. Just
like the queue of the real world, the data that goes
first into the queue is the first one to be retrieved.
That is why queues are sometimes called as First-In-
First-Out data structure.
In case of stack, we saw that data is inserted both
from one end but in case of Queues; data is added to
one end (known as REAR) and retrieved from the other
end (known as FRONT).
The data first added is the first one to be retrieved
while in case of queues the data last added is the
first one to be retrieved.
A few points regarding Queues:

1.Queues: It is a linear data structure; linked lists


and arrays can represent it.
2.Rear: A variable stores the index number in the array
at which the new data will be added (in the queue).
3.Front: It is a variable storing the index number in
the array where the data will be retrieved.
// Array Implementation of Queue
#include <iostream.h>
#define MAX 5
#include <stdlib.h>
int queue[MAX];
int front , rear;
void insertQ();

Page 176 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

void deleteQ();
void insertQ()
{
int value;
cout<<endl<<"Enter the element to be inserted in
queue\n";
cin>>value;
if(rear < MAX-1)
{
rear= rear +1;
queue[rear] = value;
}
else
{
cout<<"The queue is full \n";
exit(1);
}
}
void deleteQ()
{ int value;
if(front == rear)
{
cout<<"The queue is empty \n";
exit(1);
}
front = front + 1;
value = queue[front];
cout<<endl<<"The value deleted is "<<value;
}
int main()
{
int n;
front=rear=-1;
do
{
do
{
insertQ();
cout<<"Enter 1 to continue and 0 for exit\n";
cin>>n;
}while(n == 1);
cout<<endl<<"Enter 1 to delete an element and 0 for
exit" ;

Page 177 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

cin>>n;
while( n == 1)
{
deleteQ();
cout<<endl<<"Enter 1 to delete an element and 0 for
exit";
cin>>n;
}
cout<<endl<<"Enter 1 to continue and 0 for exit\n";
cin>>n;
} while(n == 1);
return 0;
}
// Linked Implementation of Queue data Structure
#include<iostream.h>
#include<stdlib.h>

typedef struct node


{
int data;
struct node *link;
}n;
n *front=NULL;
n *rear=NULL;
void insertQ();
void deleteQ();
void display();
int main()
{
int n;
cout<<"\tMENU\n1.INSERT\n2.DELETE\n3.DISPLAY\n4.EXIT\n"
;
do
{
cout<<"\nEnter your choice\n";
cin>>n;
switch(n)
{
case 1:
insertQ();
break;
case 2:
deleteQ();

Page 178 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

break;
case 3:
display();
break;
case 4:
break;
default:
cout<<"Invalid choice\n";
break;
}
}while(n!=4);
return 0;
}
void insertQ()
{
int item;
n *temp;
cout<<"Enter the item\n";
cin>>item;
temp=(n*)malloc(sizeof(n));
temp->data=item;
temp->link=NULL;
if(rear==NULL)
{
front=temp;
rear=temp;
}
else
{
rear->link=temp;
rear=temp;
}
}
void deleteQ()
{
int item;
if(front==NULL)
cout<<"Queue is empty\n";
else
{
item=front->data;
cout<<"The element deleted = \n"<<item;
}
if(front==rear)
{

Page 179 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

front=NULL;
rear=NULL;
}
else
front=front->link;
}
void display()
{
n *ptr;

if(front==NULL)
cout<<"Queue is empty\n";
else
{
ptr=front;
cout<<"The elements of the queue are :";
while(ptr!=NULL)
{
cout<<ptr->data<<endl;
ptr=ptr->link;
}
}
}
Circular Queue
In circular queue, the insertion of a new element is
performed at the very first location of the queue if
the last location of the queue is full, in which the
first element comes just after the last element.
Advantages :
It overcomes the problem of unutilized space in leaner
queues, when it is implemented as arrays.
Insertion :
Rear = (rear+1)%Maxsize
Algorithm Steps:
Step 1:
create and set the variables front,rear,MAXSIZE,cq[]
step 2:
Read the circular queue operation type.

Page 180 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

step 3:
If operation type is Insertion below steps are
executed.
Assign rear=rear%MAXSIZE.
if front equal to (rear+1)%MAXSIZE then display queue
is overflow.
if front equal to -1 then assign front=rear=0.
Otherwise assign rear=(rear+1)%MAXSIZE and read queue
data
Assign cq[rear] as data.(i.e. cq[rear]=data).
step 4:
If operation type is Deletion below steps are executed.
Check front=-1 then display queue is underflow.
Set temp as cq[front] (i.e. temp=ca[front]).
Check front equal to rear if it is true then assign
front=rear=-1(Move the front to beginning)
Assign front=(front+1)%MAXSIZE.

Page 181 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

//Program for Circular Queue implementation through


Array
#include <iostream.h>
#include<ctype.h>
#include<stdlib.h>
#include<conio.h>

#define MAXSIZE 5
int cq[MAXSIZE];
int front,rear;
int main()
{
void add(int);
void del();
int will=1,i,num;
front = -1;
rear = -1;
//clrscr();
cout<<"\nProgram for Circular Queue through array";
while(1)
{
cout<<"\n\nMENU\n1.INSERTION\n2.DELETION\n3.EXIT";
cout<<"\n\nENTER YOUR CHOICE : ";
cin>>will;
switch(will)
{
case 1:
cout<<"\n\nENTER THE QUEUE ELEMENT : ";
cin>>num;
add(num);
break;
case 2:
del();
break;
case 3:
exit(0);
default:
cout<<"\n\nInvalid Choice . ";
}
} //end of outer while
return 0;
} //end of main
void add(int item)
{
//rear++;

Page 182 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

//rear= (rear%MAXSIZE);
if(front ==(rear+1)%MAXSIZE)
{
cout<<"\n\nCIRCULAR QUEUE IS OVERFLOW";
}
else
{
if(front==-1)
front=rear=0;
else
rear=(rear+1)%MAXSIZE;
cq[rear]=item;
cout<<"\n\nRear = "<<rear<<" Front = "<<front;
}
}
void del()
{
int a;
if(front == -1)
{
cout<<"\nCIRCULAR QUEUE IS UNDERFLOW";
}
else
{
a=cq[front];
if(front==rear)
front=rear=-1;
else
front = (front+1)%MAXSIZE;
cout<<"\n\nDELETED ELEMENT FROM QUEUE IS : "<<a;
cout<<"\n\nRear = "<<rear<<" Front = "<<rear;
}
}

Page 183 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

XII COMPUTER SCIENCE UNITIII MYSQL

Page 184 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Database
Databases are designed to offer an organized mechanism
for storing, managing and retrieving information. They
do so through the use of tables. In simple terms we can
say that in a Database the data is stored in Rows and
Columns.

If youre familiar with spreadsheets like Open Office


Calc, you can easily understand the concept of Database
Storage.
Database Tables
Database tables consist of columns and rows. Each
column contains a different type of attribute and each
row corresponds to a single record. For example,
imagine that we are building a database table that
contained student's details. We will probably set up
columns named Rollno, Name , Class and
"Address" .Then we simply start by adding rows those
contains our data.
If we are building a table of student's information for
our school that has 550 students, then this table will
have 550 rows.
DBMS (Database Management System)

Page 185 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

A Database Management System (DBMS) is a set of


computer programs that controls the creation,
maintenance, and the use of a database. A DBMS is a
system software package that helps the use of
integrated collection of data records and files known
as databases. It allows different application programs
to easily access the same database. A DBMS also
provides the ability to logically present database
information to the users.
Example of Commonly used DBMS
MYSQL,Oracle ,SQL SERVER 2000,MS Access
Advantages and disadvantages of DBMS
Advantages:
Reduced data redundancy (Duplication of data)
Reduced updating errors and increased consistency
Greater data integrity and independence from
applications programs
Improved data security
Reduced data entry, storage, and retrieval costs
Disadvantages

Database systems are complex, difficult, and time-


consuming to design

Page 186 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Damage to database affects virtually all applications


programs
Initial training required for all programmers and
users.
Relational database
Relational database was proposed by Edgar Codd around
1969. It has since become the dominant database model
for commercial applications. Today, there are many
commercial Relational Database Management System
(RDBMS), such as Oracle, IBM DB2 and Microsoft SQL
Server and many free and open-source RDBMS, such as
MySQL, PostgreSQL are available.
A relational database organizes data in tables (or
relations). A table is made up of rows and columns. A
row is also called a record (or tuple). A column is
also called a field (or attribute). A database table is
similar to a spreadsheet. However, the relationships
that can be created among the tables enable a
relational database to efficiently store huge amount of
data, and effectively retrieve selected data.

Relational Model Concepts


Relation - table of values. Row is collection of
related data values corresponding to real-world entity
Tuple Row in a relation

Page 187 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Attribute - Column header or Column name of the


Relation
Domain - Set of atomic values permissible for a Column
or an attribute. If the data type of a particular
column in a relation is Number then the domain of that
attribute is a number formed from the digit 0-9 e.g
123,398 etc.
Atomic - Value is indivisible, as far as relational
model is concerned
Degree - Number of attributes in a relation
Cardinality -Number of rows/tuples in a relation
A language called SQL (Structured Query Language) was
developed to work with relational databases.

Page 188 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Example Table

Relational Algebra
Algebra is a formal structure consisting of sets and
operations on those sets. Relational algebra is a
formal system for manipulating relations.
1. Operands of this Algebra are relations.
2. Operations of this Algebra include the usual set
operations and special operations defined for
relations such as :
selection
projection
join
Set Operations on Relations
For the set operations on relations, both operands must
have the same schema, and the result has that same
schema.
1. R1 U R2 (union) is the relation containing all
tuples that appear in R1, R2, or both.
2. R1 n R2 (intersection) is the relation containing
all tuples that appear in both R1 and R2.
3. R1 - R2 (set difference) is the relation containing
all tuples of R1 that do not appear in R2.

Selection
Selects tuples from a relation whose attributes meet
the selection criteria, which is normally expressed as
a predicate.
R2 = select(R1,P)

Page 189 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

That is, from R1 we create a new relation R2 containing


those tuples from R1 that satisfy the predicate P.
A predicate is a Boolean expression whose operators are
and, or, not and arithmetic comparisons (LT, LE, GT,
GE, EQ, NE), and whose operands are either domain names
or domain constants.
select(students,Class=XII)

Projection
Chooses a subset of the columns in a relation, and
discards the rest.
R2 = project(R1,D1,D2,...Dn)
That is, from the tuples in R1 we create a new relation
R2 containing only the domains D1,D2,..Dn.
project(Students,Name,Address)

Union
R UNION S
Includes all tuples that are in either R or S.
Duplicate tuples are removed.
For a union operation r U s to be valid, two conditions
must hold:

Page 190 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

The relation r and s must be of the same arity, i.e.


they must have the same number of attributes.
The domains of the ith attribute of r and the ith
attribute of s must be the same for all i.
Example:

Join
Combines attributes of two relations into one.
R3 = join(R1,D1,R2,D2)
Given a domain from each relation, join considers all
possible pairs of tuples from the two relations, and if
their values for the chosen domains are equal, it adds
a tuple to the result containing all the attributes of
both tuples (discarding the duplicate domain D2).
Natural join: If the two relations being joined have
exactly one attribute (domain) name in common, then we
assume that the single attribute in common is the one
being compared to see if a new tuple will be inserted
in the result.

Page 191 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

OUTER JOIN
Notice that much of the data is lost when applying a
join to two relations. In some cases this lost data
might hold useful information. An outer join retains
the information that would have been lost from the
tables, replacing missing data with nulls. There are
three forms of the outer join, depending on which data
is to be kept.
LEFT OUTER JOIN - keep data from the left-hand table
RIGHT OUTER JOIN - keep data from the right-hand table
FULL OUTER JOIN - keep data from both tables

Page 192 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Cartesian Product

The Cartesian Product is also an operator which works


on two sets. It is sometimes called the CROSS PRODUCT
or CROSS JOIN. It combines the tuples of one relation
with all the tuples of the other relation.
Example

R X S =

Set Operations on Relations


For the set operations on relations, both operands must
have the same schema, and the result has that same
schema.

R1 U R2 (union) is the relation containing all tu-


ples that appear in R1, R2, or both.

R1 n R2 (intersection) is the relation containing


all tuples that appear in both R1 and R2.

R1 - R2 (set difference) is the relation containing


all tuples of R1 that do not appear in R2.

Page 193 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

What is SQL?
1. SQL stands for Structured Query Language
2. SQL lets you access and manipulate databases
3. SQL is an ANSI (American National Standards
Institute) standard
Note: SQL is not case sensitive. SELECT is the same
as select.

What Can SQL do?


1.SQL can retrieve data from a database/table
2.SQL can insert records in a database/table
3.SQL can update records in a database/table
4.SQL can delete records from a database/table
5.SQL can create new databases/table
6.SQL can create new tables in a database/table
SQL DML and DDL
SQL can be divided into two parts:The Data Manipulation
Language (DML) and the Data Definition Language (DDL).

DML Commands:
1. SELECT - extracts data from a table
2. UPDATE - updates data in a table
3. DELETE - deletes data from a table
4. INSERT INTO - inserts new data into a table

DDL Commands:
1. CREATE DATABASE - creates a new database
2. CREATE TABLE - creates a new table
3. ALTER TABLE - modifies a table
4. DROP TABLE - delete a table
5. CREATE INDEX - creates an index
6. DROP INDEX - deletes an index

Page 194 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Data Types

Max Size:
Data type Description

Variable length character


string having maximum 32767 bytes
VARCHAR2(size)
length size bytes. minimum is 1
You must specify size

Fixed length character


CHAR(size) data of length size bytes. 32767

Integer/INT Integer Number.

Magnitude
Number having
DECIMAL(p,s) 1E-130 ..
precision p and scale s.
10E125

A date and time


DATETIME combination in YYYY-MM-DD
HH:MM:SS format

A date in YYYY-MM-DD
DATE format

The CREATE DATABASE Command


The CREATE DATABASE statement is used to create a
Database.
SQL CREATE DATABASE Syntax
CREATE DATABASE database_name
CREATE DATABASE Example
CREATE DATABASE KVPALAMPUR ;
This command will create a Database with the name
KVPALAMPUR

Page 195 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

The CREATE TABLE Command


The CREATE TABLE statement is used to create a table in
a database.
SQL CREATE TABLE Syntax
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
....
)
The data type specifies what type of data the column
can hold.
CREATE TABLE Example
Now we want to create a table called "Student" that
contains four columns: Roll_No, Name, Class, City.
We use the following CREATE TABLE statement:
CREATE TABLE Student
(
Roll_No integer,
Name varchar(30),
Class varchar(5),
City varchar(30)
)
The Roll_No column is of type integer and will hold a
number. The Name, Class and City columns are of type
varchar and will hold character data. The empty
"Student" table will now look like this:

Page 196 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

The DROP TABLE Command


The DROP TABLE statement is used to delete a table .
Syntax:
DROP TABLE table_name
Example:
Suppose if we want to drop table student, we can use
DROP TABLE command like this
Drop Table Student ;
Note: Before using Drop Command make sure that table
has no records exist. Drop command will not work on a
table if it has has some records.
The ALTER TABLE Command
The ALTER TABLE statement is used to add, delete, or
modify columns in an existing table.
SQL ALTER TABLE Syntax
To add a column in a table, use the following syntax:
ALTER TABLE table_name ADD column_name data-type
To delete a column in a table, use the following
syntax

ALTER TABLE table_name DROP COLUMN column_name


To change the data type of a column in a table, use the
following syntax:
ALTER TABLE table_name MODIFY column_name data-type

Page 197 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

SQL ALTER TABLE Example


Look at the "Student" table:

Now we want to add a column named "DateOfBirth" in the


"Student" table.
We use the following SQL statement:
ALTER TABLE Student ADD DateOfBirth date
The "Student" table will now like this:

Change Data Type Example


Now we want to change the data type of the column named
"Class" in the "Student" table.
We use the following SQL statement:
ALTER TABLE Student ALTER COLUMN Class integer
Notice that the "Class" column is now of type integer.
DROP COLUMN Example
Next, we want to delete the column named "DateOfBirth"
in the "Student" table.
We use the following SQL statement:
ALTER TABLE Student DROP COLUMN DateOfBirth
The "Student" table will now like this:

Page 198 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

DML Commands:
Quotes Around Text Fields
SQL uses single quotes around text values (most
database systems will also accept double quotes).
However, numeric values should not be enclosed in
quotes.
For text values:
This is correct:

SELECT * FROM Student WHERE Name='Abhey'


This is wrong:
SELECT * FROM Student WHERE Name=Abhey
For numeric values:
This is correct:
SELECT * FROM Student WHERE Roll_No=2
This is wrong:
SELECT * FROM Student WHERE Roll_No='2'
The INSERT INTO Command
The INSERT INTO Command is used to insert a new record
in a table.
INSERT INTO Syntax
We can write INSERT INTO command in two forms.
The first form doesn't specify the column names where
the data will be inserted, only their values:
Page 199 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in

INSERT INTO table_name VALUES (value1, value2,


value3,...)
The second form specifies both the column names and the
values to be inserted:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
SQL INSERT INTO Example
We have the following "Persons" table:

Now we want to insert some records in the "Student"


table.
We use the following SQL statement:
INSERT INTO Student VALUES (1,'Amisha', 'XII',
'Palampur')
INSERT INTO Student VALUES (2,'Usha', 'XII', 'Holta')
INSERT INTO Student VALUES (3,'Sneh', 'XII',
'Palampur)
INSERT INTO Student VALUES (4,'Nishant', 'XI',
'Baijnath')
INSERT INTO Student VALUES (5,'Gaurav', 'XI',
'Paprola')
The "Student" table will now look like this:

Page 200 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Insert Data Only in Specified Columns


It is also possible to only add data in specific
columns.
The following SQL statement will add a new row, but
only add data in the "Roll_No", "Name" and the "Class"
columns:
INSERT INTO Student (Roll_No, Name, Class)
VALUES (6, 'Abhay', 'XI')
The "Student" table will now look like this:

The UPDATE Statement


The UPDATE statement is used to update existing records
in a table.
SQL UPDATE Syntax
UPDATE table_name SET column1=value, column2=value2,...
WHERE some_column=some_value
Note: If you omit the WHERE clause, all records will be
updated!
SQL UPDATE Example
The "Student" table:

Page 201 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Now we update the record of student "Abhey" in the


"Student" table.
We use the following SQL command:
UPDATE Student SET City='Sagoor' WHERE Name='Abhey'
The "Student" table will now look like this:

The DELETE Statement


The DELETE statement is used to delete rows in a table.
SQL DELETE Syntax
DELETE FROM table_name WHERE some_column=some_value
Note: If we omit the WHERE clause, all records will be
deleted .Be very careful when deleting records. You
cannot undo this command!
The SQL SELECT Statement
The SELECT statement is used to select data from a
database.
SQL SELECT Syntax

Page 202 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

SELECT column_name(s) FROM table_name


and
SELECT * FROM table_name
SQL SELECT Example
The "Student" table:

Now we select all the records from the table above.


We use the following SELECT statement:
SELECT * from Student ;
The use of asterisk (*) is an easy way to list all
the records from a table.
The result of this command will look like this:

Now we select the contents of the columns named "Name"


and "Class" from Student table.
We use the following SELECT statement:
SELECT Name,Class FROM Student ;

Page 203 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

The result will look like this:

The SQL SELECT DISTINCT Statement


In a table, some of the columns may contain duplicate
values. Sometimes we want to list only the different
(distinct) values from a table.
The DISTINCT keyword can be used to return only
distinct (different) values.
SQL SELECT DISTINCT Syntax
SELECT DISTINCT column_name(s)FROM table_name
The "Student" table:

Now we want to select only the distinct values from the


column named "City" from the table above.
We use the following SELECT statement:
SELECT DISTINCT City FROM Persons
The result will look like this:

Page 204 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

The WHERE Clause


The WHERE clause is used to extract only those records
that fulfill a specified criterion.
SQL WHERE Syntax
SELECT column_name(s)FROM table_name WHERE column_name
operator value
WHERE Clause Example
The "Student" table:

Now we want to select only the students living in the


city "Palampur" from the table above.
We use the following SELECT statement:
SELECT * FROM Student WHERE City='Palampur' ;

Page 205 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Operators Allowed in the WHERE Clause


With the WHERE clause, the following operators can be
used:

Operator Description

= Equal

<> Not equal

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

BETWEEN Between an inclusive range

LIKE Search for a pattern

To specify multiple possible values for a


IN
column

The AND & OR Operators


The AND operator displays a record if both the first
condition and the second condition is true.
The OR operator displays a record if either the first
condition or the second condition is true.
AND Operator Example
The "Student" table:

Page 206 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Now we want to select only the students with the name


equal to "Sneh" AND the City equal to "Palampur":
We use the following SELECT statement:
SELECT * FROM Student WHERE Name='Sneh' AND
City='Palampur'
The result will look like this:

OR Operator Example
Now we want to select only those students with the name
equal to "Nishant" OR City equal to "Sagoor":
We use the following SELECT statement:
SELECT * FROM Student WHERE Name='Nishant' OR
City='Sagoor'
The result will look like this:

The ORDER BY Keyword


The ORDER BY keyword is used to sort the result by a
specified column. The ORDER BY keyword sort the records
in ascending order by default. If we want to sort the
records in a descending order, we can use the DESC
keyword.
SQL ORDER BY Syntax
SELECT column_name(s) FROM table_name ORDER BY
column_name(s) ASC|DESC

Page 207 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

ORDER BY Example
The "Student" table:

Now we select all records from the table above,


however, we want to sort the students by their name.
We use the following SELECT statement:
SELECT * FROM Student ORDER BY Name
The result will look like this:

The GROUP BY Statement


The GROUP BY statement is used in conjunction with the
aggregate functions to group the result-set by one or
more columns.
SQL GROUP BY Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name WHERE column_name operator value GROUP
BY column_name
SQL GROUP BY Example
We have the following "Order" table:

Page 208 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Now we want to find the total sum of each Customer. We


will have to use the GROUP BY clause to group the
items. We use the following SQL statement:
SELECT Cname,SUM(Price) FROM Order GROUP BY Customer
The result will look like this:

The HAVING Clause


The HAVING clause was added to SQL because the WHERE
keyword could not be used with aggregate functions.
SQL HAVING Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name WHERE column_name operator value GROUP
BY column_name HAVING aggregate_function(column_name)
operator value
SQL HAVING Example
We have the following "Order" table:

Page 209 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Now we want to find if any of the customers have a


total order of greater than 25000.
We use the following SQL statement:
SELECT CName,SUM(Price) FROM Order GROUP BY CName
HAVING SUM(Price)>25000
The result will look like this:

Now we want to find if the customers "Ayan" or "Abhay"


have a total order of more than 40000.
We add an ordinary WHERE clause to the SQL statement:
SELECT CName,SUM(Price) FROM Order WHERE CName='Ayan'
OR CName='Abhay' GROUP BY CName HAVING SUM(Price)>30000
The result will look like this:

The IN Operator
The IN operator allows you to specify multiple values
in a WHERE clause.

Page 210 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

SQL IN Syntax
SELECT coumn_name(s)FROM table_name WHERE column_name
IN (value1,value2,...)
IN Operator Example
The "Order" table:

Now we want to select all the records with IName equal


to "TV" or "AC" from the table above.
We use the following SELECT statement:
SELECT * FROM Order WHERE IName IN ('TV','AC')
The result will look like this:

The BETWEEN Operator


The BETWEEN operator selects a range of data between
two values. The values can be numbers, text, or dates.
BETWEEN Syntax
SELECT column_name(s) FROM table_name WHERE column_name
BETWEEN value1 AND value2
BETWEEN Operator Example
The "Order" table:

Page 211 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Now we want to select the orders with Price between


15000 and 40000 from the table above.
We use the following SELECT statement:
SELECT * FROM Order WHERE Price BETWEEN 15000 AND 40000
The result will look like this:

SQL Date Data Types


MySQL comes with the following data types for storing a
date or a date/time value in the database:

DATE - format YYYY-MM-DD


DATETIME - format: YYYY-MM-DD HH:MM:SS
TIMESTAMP - format: YYYY-MM-DD HH:MM:SS
YEAR - format YYYY or YY
Note: The date types are chosen for a column when you
create a new table in your database!
SQL Working with Dates
The "Order" table:

Page 212 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Now we want to select the records with an OrderDate of


"2014-12-25" from the table above.
We use the following SELECT statement:
SELECT * FROM Order WHERE OrderDate='2014-12-25'
The result will look like this:

Page 213 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

SQL Functions
SQL has many built-in functions for performing
calculations on data.
SQL Aggregate Functions
SQL aggregate functions return a single value,
calculated from values in a column.
Useful aggregate functions:
AVG() - Returns the average value
COUNT() - Returns the number of rows
MAX() - Returns the largest value
MIN() - Returns the smallest value
SUM() - Returns the sum
The SUM() Function
The SUM() function returns the total sum of a numeric
column.
SQL SUM() Syntax
SELECT SUM(column_name) FROM table_name
SQL SUM() Example
We have the following "Order" table:

Now we want to find the sum of all "OrderPrice"


fields".
We use the following SQL statement:
SELECT SUM(OrderPrice) AS OrderTotal FROM Order

Page 214 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

The result-set will look like this:

OrderTotal

5700

The AVG() Function


The AVG() function returns the average value of a
numeric column.
SQL AVG() Syntax
SELECT AVG(column_name) FROM table_name
SQL AVG() Example
We have the following "Order" table:

Now we want to find the average value of the


"OrderPrice" fields. We use the following SQL
statement:
SELECT AVG(OrderPrice) AS OrderAverage FROM Order
The result-set will look like this:

OrderAverage

950

Now we want to find the customers that have an


OrderPrice value higher than the average OrderPrice
value. We use the following SQL statement:

Page 215 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

SELECT Customer FROM Order


WHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Order)
The result-set will look like this:

Customer

Ayan

Anya

Aneesh

SQL COUNT() Function

The COUNT() function returns the number of rows that


matches a specified criteria.
SQL COUNT(column_name) Syntax
The COUNT(column_name) function returns the number of
values (NULL values will not be counted) of the
specified column:
SELECT COUNT(column_name) FROM table_name
SQL COUNT(*) Syntax
The COUNT(*) function returns the number of records in
a table:
SELECT COUNT(*) FROM table_name
SQL COUNT(DISTINCT column_name) Syntax
The COUNT(DISTINCT column_name) function returns the
number of distinct values of the specified column:
SELECT COUNT(DISTINCT column_name) FROM table_name
Note: COUNT(DISTINCT) works with ORACLE and Microsoft
SQL Server, but not with Microsoft Access.
SQL COUNT(column_name) Example
We have the following "Order" table:

Page 216 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Now we want to count the number of orders from


"Customer Ayan".We use the following SQL statement:
SELECT COUNT(Customer) AS CustomerAyan FROM Order
WHERE Customer='Ayan'
The result of the SQL statement above will be 1,
because the customer Ayan has made 1 order in total:

CustomerAyan

SQL COUNT(*) Example


If we omit the WHERE clause, like this:
SELECT COUNT(*) AS NumberOfOrders FROM Order
The result-set will look like this:

NumberOfOrders

which is the total number of rows in the table.


SQL COUNT(DISTINCT column_name) Example
Now we want to count the number of unique customers in
the "Orders" table. We use the following SQL statement:
SELECT COUNT(DISTINCT Customer) AS NumberOfCustomers
FROM Order

Page 217 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

The result-set will look like this:

NumberOfCustomers

The MAX() Function


The MAX() function returns the largest value of the
selected column.
SQL MAX() Syntax
SELECT MAX(column_name) FROM table_name
SQL MAX() Example
We have the following "Order" table:

Now we want to find the largest value of the


"OrderPrice" column. We use the following SQL
statement:
SELECT MAX(OrderPrice) AS LargestOrderPrice FROM Order
result will look like this:

LargestOrderPrice

2000

The MIN() Function


The MIN() function returns the smallest value of the
selected column.

Page 218 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

SQL MIN() Syntax


SELECT MIN(column_name) FROM table_name
SQL MIN() Example
Now we want to find the smallest value of the
"OrderPrice" column. We use the following SQL
statement:
SELECT MIN(OrderPrice) AS SmallestOrderPrice FROM Order
result will look like this:

SmallestOrderPrice

100

Page 219 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

CLASS-XII
COMPUTER SCIENCE
(Subject Code 083)
SAMPLE PAPER 2014 - 15

Time allowed : 3 hours Maximum Marks: 70

Instructions: (i) All questions are compulsory.


(ii) Programming Language: Section A C+ +.
(iii) Programming Language : Section B Python.
(iv) Answer either Section A or B, and Section C is
compulsory.

Section A (C++)

Q1. a. Differentiate between ordinary function and member functions in C++.


Explain with an example. [2]

b. Write the related library function name based upon the given information in
C++.

(i) Get single character using keyboard. This function is available in stdio.h file.
(ii) To check whether given character is alpha numeric character or not. This

function is available in ctype.h file. [1]

c. Rewrite the following C++ program after removing all the syntactical errors (if
any), underlining each correction. : [2]

include<iostream.h>
#define PI=3.14
void main( )
{ float r;a;
cout<<enter any radius;
cin>>r;
a=PI*pow(r,2);
cout<<Area=<<a
}

d. Write the output from the following C++ program code: [2]

#include<iostream.h>
#include<ctype.h>

Page 220 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

void strcon(char s[])


{
for(int i=0,l=0;s[i]!='\0';i++,l++);
for(int j=0; j<l; j++)
{
if (isupper(s[j]))
s[j]=tolower(s[j])+2;
else if ( islower(s[j]))
s[j]=toupper(s[j])-2;
else
s[j]='@';
}
}
void main()
{
char *c="Romeo Joliet";
strcon(c);
cout<<"Text= "<<c<<endl;
c=c+3;
cout<<"New Text= "<<c<<endl;
c=c+5-2;
cout<<"last Text= "<<c
}

e. Find the output of the following C++ program: [3]

#include<iostream.h>
#include<conio.h>
#include<ctype.h>
class Class
{
int Cno,total;
char section;
public:
Class(int no=1)
{
Cno=no;
section='A';
total=30;
}
void addmission(int c=20)
{
section++;
total+=c;
}
void ClassShow()
{
cout<<Cno<<":"<<section<<":"<<total<<endl;

Page 221 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

}
};
void main()
{
Class C1(5),C2;
C1.addmission(25);
C1.ClassShow();
C2.addmission();
C1.addmission(30);
C2.ClassShow();
C1.ClassShow();
}

f. Study the following C++ program and select the possible output(s) from it :
Find the maximum and minimum value of L. [2]

#include<stdlib.h>
#include<iostream.h>
#include<string.h>
void main()
{
randomize();
char P[]="C++PROGRAM";
long L;
for(int I=0;P[I]!='R';I++)
{
L=random (sizeof(L)) +5;
cout<<P[L]<<"-";
}
}
}

i) R-P-O-R-
ii) P-O-R-+-
iii) O-R-A-G-
iv) A-G-R-M-

Q2.a. How encapsulation and abstraction are implemented in C++ language?


Explain with an example. [2]

b. Answer the questions (i) and (ii) after going through the following C++ class:
[2]
class Stream
{
int StreamCode ; char Streamname[20];float fees;
public:
Stream( ) //Function 1
{

Page 222 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

StreamCode=1; strcpy (Streamname,"DELHI");


fees=1000;
}
void display(float C) //Function 2
{
cout<<StreamCode<<":"<<Streamname<<":"<<fees<<endl;
}
~Stream( ) //Function 3
{
cout<<"End of Stream Object"<<endl;
}
Stream (int SC,char S[ ],float F) ; //Function 4
};

i) In Object Oriented Programming, what are Function 1 and Function 4


combined together referred as? Write the definition of function 4.

ii) What is the difference between the following statements?


Stream S(11,Science,8700);
Stream S=Stream(11,Science,8700);

c. Define a class Customer with the following specifications. [4]

Private Members :
Customer_no integer
Customer_name char (20)
Qty integer
Price, TotalPrice, Discount, Netprice float
Member Functions:
Public members:
* A constructer to assign initial values of Customer_no as
111,Customer_name as Leena, Quantity as 0 and Price, Discount and
Netprice as 0.
*Input( ) to read data members(Customer_no, Customer_name, Quantity
and Price) call Caldiscount().
* Caldiscount ( ) To calculate Discount according to TotalPrice and
NetPrice
TotalPrice = Price*Qty
TotalPrice >=50000 Discount 25% of TotalPrice
TotalPrice >=25000 and TotalPrice <50000 - Discount 15% of TotalPrice
TotalPrice <250000 - Discount 10% of TotalPrice
Netprice= TotalPrice-Discount
*Show( ) to display Customer details.

d. Answer the questions (i) to (iv) based on the following code: [4]

class AC
{

Page 223 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

char Model[10];
char Date_of_purchase[10];
char Company[20];
public( );
AC( );
void entercardetail( );
void showcardetail( );
};
class Accessories : protected AC
{
protected:
char Stabilizer[30];
char AC_cover[20];
public:
float Price;
Accessories( );
void enteraccessoriesdetails( );
void showaccessoriesdetails( );
};
class Dealer : public Accessories
{
int No_of_dealers;
char dealers_name[20];
int No_of_products;
public:
Dealer( );
void enterdetails( );
void showdetails( );
};

(i) How many bytes will be required by an object of class Dealer and class
Accessories?

(ii) Which type of inheritance is illustrated in the above c++ code? Write the base
class and derived class name of class Accessories.

(ii) Write names of all the members which are accessible from the objects of
class Dealer.

(iv) Write names of all the members accessible from member functions of class
Dealer.

Q3a) An array T[-1..35][-2..15] is stored in the memory along the row with each
element occupying 4 bytes. Find out the base address and address of element
T[20][5], if an element T[2][2] is stored at the memory location 3000. Find the
total number of elements stored in T and number of bytes allocated to T
[3]

Page 224 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

b. Write a function SORTSCORE() in C++ to sort an array of structure IPL in


descending order of score using selection sort .
[3]
Note : Assume the following definition of structure IPL.
struct IPL
{
int Score;
char Teamname[20];
};

c. Write member functions to perform POP and PUSH operations in a


dynamically allocated stack containing the objects of the following structure:
[4]
struct Game
{ char Gamename[30];
int numofplayer;
Game *next; };

d. Write a function in C++ to print the sum of all the non-negative elements
present on both the diagonal of a two dimensional array passed as the argument
to the function. [2]

e. Evaluate the following postfix expression. Show the status of stack after
execution of each operation separately:

2,13, + , 5, -,6,3,/,5,*,< [2]

Q4. a. Write the command to place the file pointer at the 10th and 4th record
starting position using seekp() or seekg() command. File object is file and record
name is STUDENT. [1]

b. Write a function in C++ to count and display the no of three letter words in
the file VOWEL.TXT. [2]
Example:
If the file contains:
A boy is playing there. I love to eat pizza. A plane is in the sky.
Then the output should be: 4
c. Given the binary file CAR.Dat, containing records of the following class CAR
type: [3]
class CAR
{
int C_No;
char C_Name[20];
float Milage;
public:
void enter( )

Page 225 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

{
cin>> C_No ; gets(C_Name) ; cin >> Milage;
}
void display( )
{
cout<< C_No ; cout<<C_Name ; cout<< Milage;
}
int RETURN_Milage( )
{
return Milage;
}
};

Write a function in C++, that would read contents from the file CAR.DAT and
display the details of car with mileage between 100 to 150.

Section B (Python)

Q1.a) How is a static method different from an instance method? [2]

b) Name the function / method required for [1]

i) Finding second occurrence of m in madam.


ii) get the position of an item in the list

c) Rewrite the following python code after removing all syntax error(s). Underline
the corrections done. [2]

def main():
r = raw-input(enter any radius : )
a = pi * math.pow(r,2)
print Area = + a

d) Give the output of following with justification [2]


x=3
x+= x-x
print x

e) What will be printed, when following python code is executed [3]


class person:
def __init__(self,id):
self.id = id
arjun = person(150)
arjun.__dict__[age] = 50
print arjun.age + len(arjun.__dict__)

Justify your answer.

Page 226 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

f) What are the possible outcome(s) expected from the following python code?
Also specify maximum and minimum value, which we can have. [2]

def main():
p = 'MY PROGRAM'
i=0
while p[i] != 'R':
l = random.randint(0,3) + 5
print p[l],'-',
i += 1
i) R - P - O - R -
ii) P - O - R - Y -
iii) O -R - A - G -
iv) A- G - R - M -

Q2. a) How data encapsulation and data abstraction are implemented in python,
explain with example. [2]

b) What will following python code produce, justify your answer [2]
x=5
y=0
print A
try :
print B
a=x/y
print C
except ZerorDivisionError:
print F
except :
print D

c) Write a class customer in python having following specifications [4]

Instance attributes:

customernumber - numeric value


customername - string value
price, qty, discount, totalprice, netprice - numeric value
methods :

init() to assign initial values of customernumber as 111, customername as


Leena, qty as 0 and price, discount & netprice as 0.
caldiscount ( ) To calculate discount, totalprice and netprice
totalprice = price * qty
discount is 25% of totalprice, if totalprice >=50000
discount 15% of totalprice, if totalprice >=25000 and totalprice <50000
discount 10% of totalprice, if totalprice <250000

Page 227 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

netprice= totalprice - discount

input() to read data members customername, customernumbar, price, qty and


call caldiscount() to calculate discount, totalprice and netprice.
show( ) to display Customer details.

d) What are the different ways of overriding function call in derived class of
python ? Illustrate with example. [2]

e) Write a python function to find sum of square-root of elements of a list. List is


received as argument, and function returns the sum. Ensure that your function is
able to handle various situations viz. list containing numbers & strings, module
required is imported etc. [2]

Q3. a) What will be the status of following list after third pass of bubble sort and
third pass of selection sort used for arranging elements in ascending order?
40, 67, -23, 11, 27, 38, -1 [3]

b) Write a python function to search for a value in the given list using binary
search method. Function should receive the list and value to be searched as
argument and return 1 if the value is found 0 otherwise. [2]

c) Define stack class in python to operate on stack of numbers. [4]

d) Write a python function using yield statement to generate prime numbers till
the value provided as parameter to it. [3]

e) Evaluate the following postfix expression. Show the status of stack after
execution of each operation separately:
2,13, + , 5, -,6,3,/,5,*,< [2]

Q4.a) How is method write() different from writelines() in python? [1]

b) Given a pickled file - log.dat, containing list of strings. Write a python function
that reads the file and looks for a line of the form

Xerror: 0.2395

whenever such line is encountered, extract the floating point value and compute
the total of these error values. When you reach end of file print total number of
such error lines and average of error value. [3]

c) Given a text file car.txt containing following information of cars


carNo, carname, milage. Write a python function to display details of all those
cars whose milage is from 100 to 150. [2]

Section C

Page 228 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

Q5. a. Define degree and cardinality. Based upon given table write degree and
cardinality. [2]

PATIENTS

PatNo PatName Dept DocID

1 Leena ENT 100

2 Surpreeth Ortho 200

3 Madhu ENT 100

4 Neha ENT 100

5 Deepak Ortho 200

b. Write SQL commands for the queries (i) to (iv) and output for (v) & (viii) based

on a table COMPANY and CUSTOMER [6]

COMPANY
CID NAME CITY PRODUCTNAME

111 SONY DELHI TV

222 NOKIA MUMBAI MOBILE

333 ONIDA DELHI TV

444 SONY MUMBAI MOBILE

555 BLACKBERRY MADRAS MOBILE

666 DELL DELHI LAPTOP

CUSTOMER
CUSTID NAME PRICE QTY CID

101 Rohan Sharma 70000 20 222

102 Deepak Kumar 50000 10 666

103 Mohan Kumar 30000 5 111

104 Sahil Bansal 35000 3 333

Page 229 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

105 Neha Soni 25000 7 444

106 Sonal Aggarwal 20000 5 333

107 Arjun Singh 50000 15 666

(i) To display those company name which are having prize less than 30000.
(ii) To display the name of the companies in reverse alphabetical order.
(iii) To increase the prize by 1000 for those customer whose name starts with S
(iv) To add one more column totalprice with decimal(10,2) to the table customer
(v) SELECT COUNT(*) ,CITY FROM COMPANY GROUP BY CITY;
(vi) SELECT MIN(PRICE), MAX(PRICE) FROM CUSTOMER WHERE QTY>10 ;
(vii) SELECT AVG(QTY) FROM CUSTOMER WHERE NAME LIKE %r%;
(viii) SELECT PRODUCTNAME,CITY, PRICE FROM COMPANY,CUSTOMER
WHERE COMPANY.CID=CUSTOMER.CID AND PRODUCTNAME=MOBILE;

Q6. a) State and define principle of Duality. Why is it so important in Boolean


Algebra? [2]

b) Write the equivalent boolean expression for the following logic circuit [2]

c) Write Product Of Sum expression of the function F (a,b,c,d) from the given
truth table [1]

a b c d F

0 0 0 0 0
0 0 0 1 0
0 0 1 0 1
0 0 1 1 1
0 1 0 0 0
0 1 0 1 1
0 1 1 0 1
0 1 1 1 0
1 0 0 0 0
1 0 0 1 0
1 0 1 0 1

Page 230 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

1 0 1 1 1
1 1 0 0 0
1 1 0 1 0
1 1 1 0 0
1 1 1 1 1

d) Obtain the minimal SOP form for the following boolean expression using K-
Map.
F(w,x,y,z) = (0,2,3,5,7,8,10,11,13,15) [3]

Q7.a.Give any two advantage of using Optical Fibres. [1]

b. Indian School, in Mumbai is starting up the network between its different


wings. There are Four Buildings named as SENIOR, JUNIOR, ADMIN and
HOSTEL as shown below.: [4]

SENIOR

JUNIOR

ADMIN

HOSTEL

The distance between various buildings is as follows:


ADMIN TO SENIOR 200m
ADMIN TO JUNIOR 150m
ADMIN TO HOSTEL 50m
SENIOR TO JUNIOR 250m
SENIOR TO HOSTEL 350m
JUNIOR TO HOSTEL 350m

Number of Computers in Each Building


SENIOR 130
JUNIOR 80
ADMIN 160
HOSTEL 50

(b1) Suggest the cable layout of connections between the buildings.


(b2) Suggest the most suitable place (i.e. building) to house the server of this
School, provide a suitable reason.

Page 231 of 232


http://KVSeContents.in http://eTeacher.KVSeContents.in

(b3) Suggest the placement of the following devices with justification.


Repeater
Hub / Switch
(b4) The organization also has Inquiry office in another city about 50-60 Km
away in Hilly Region. Suggest the suitable transmission media to interconnect to
school and Inquiry office out of the following .

Fiber Optic Cable


Microwave
Radio Wave

c. Identify the Domain name and URL from the following. [1]
http://www.income.in/home.aboutus.hml
d. What is Web Hosting? [1]
e. What is the difference between packet & message switching? [1]
f. Define firewall. [1]
g. Which protocol is used to creating a connection with a remote machine? [1]

Page 232 of 232

Вам также может понравиться