Computer Science for Class 12th
Computer Science for Class 12th
BY
Contents
Structure Page No’s
************************
1
A complete energized Study material of Computer Science for Class XII
Objectives:
In this Chapter you will learn about:
Historical Perspective:
The C++ programming language was created by Bjarne Stroustrup and his team
at Bell Laboratories (AT&T, USA) to help implement simulation projects in an
object-oriented and efficient way. The earliest versions, which were originally
referred to as ―C with classes,‖ date back to 1980. As the name C++ implies, C++
was derived from the C programming language: ++ is the increment operator in C.
As early as 1989 an ANSI Committee (American National Standards Institute) was
founded to standardize the C++ programming language. The aim was to have as
many compiler vendors and software developers as possible agree on a unified
description of the language in order to avoid the confusion caused by a variety of
dialects. In 1998 the ISO (International Organization for Standardization)
approved a standard for C++ (ISO/IEC 14882).
Characteristics of C++:
2
A complete energized Study material of Computer Science for Class XII
C++ is not a purely object-oriented language but a hybrid that contains the
functionality of the C programming language. This means that you have all the
features that are available in C:
■ Universally usable modular programs
■ Efficient, close to the machine programming
■ Portable programs for various platforms.
The large quantities of existing C source code can also be used in C++ programs.
C++ supports the concepts of object-oriented programming (or OOP for short),
which are:
Various language elements were added to C++, such as references, templates, and
exception handling. Even though these elements of the language are not strictly
object-oriented programming features, they are important for efficient program
implementation.
Object-Oriented Programming:
Traditional Concept:
Both of these points can lead to errors and neither support low program
maintenance
requirements.
Object-oriented concept:
Object-oriented programming shifts the focus of attention to the objects, that is, to
the
aspects on which the problem is centered. A program designed to maintain bank
accounts would work with data such as balances, credit limits, transfers, interest
calculations, and so on. An object representing an account in a program will have
properties and capacities that are important for account management.
OOP objects combine data (properties) and functions (capacities). A class
defines a certain object type by defining both the properties and the capacities of
the objects of that type. Objects communicate by sending each other ―messages,‖
which in turn activate another object‘s capacities.
Advantages of OOP:
Object-oriented programming offers several major advantages to software
development:
o Reduced susceptibility to errors: an object controls access to its own data.
More specifically, an object can reject erroneous access attempts
o Easy re-use: objects maintain themselves and can therefore be used as
building
blocks for other programs.
o Low maintenance requirement: an object type can modify its own internal
data representation without requiring changes to the application.
4
A complete energized Study material of Computer Science for Class XII
1. First, a text editor is used to save the C++ program in a text file. In other
words, the source code is saved to a source file. In larger projects the programmer
will normally use modular programming. This means that the source code will be
stored in several source files that are edited and translated separately.
3. Finally, the linker combines the object file with other modules to form an
executable file. These further modules contain functions from standard libraries or
parts of the program that have been compiled previously.
It is important to use the correct file extension for the source file‘s name.
Although the file extension depends on the compiler you use, the most commonly
found file extensions are .cpp and .cc.
Prior to compilation, header files, which are also referred to as include files,
can be copied to the source file. Header files are text files containing information
needed by various source files, for example, type definitions or declarations of
variables and functions. Header files can have the file extension .h, but they may
not have any file extension.
The C++ standard library contains predefined and standardized functions that
are
available for any compiler.
Modern compilers normally offer an integrated software development
environment, which combines the steps mentioned previously into a single task. A
graphical user interface is available for editing, compiling, linking, and running the
application. Moreover, additional tools, such as a debugger, can be launched.
5
A complete energized Study material of Computer Science for Class XII
6
A complete energized Study material of Computer Science for Class XII
Screen output
Hello! The program starts in main().
At the end of main().
Start with the main() function as this function controls the program flow. In other
words, main() calls functions that have yet to be defined. This is made possible by
supplying the compiler with a function prototype that includes all the information
the compiler needs. This example also introduces comments. Strings enclosed in /*
. . . */ or starting with // are interpreted as comments.
7
A complete energized Study material of Computer Science for Class XII
Oh what
a happy day!
Oh yes,
what a happy day!
1.6 SOLUTIONS:
Q1:
#include <iostream>
using namespace std;
int main()
{
cout << " Oh what " << endl;
cout << " a happy day! " << endl;
cout << " Oh yes, " << endl;
cout << " what a happy day! " << endl;
return 0;
}
Q2:
If this text
appears on your display
you can pat yourself on
8
A complete energized Study material of Computer Science for Class XII
C++ Tokens:
The smallest individual unit in a program is known as token. Tokens used in C++
are:
KEYWORDS :
Keywords are the certain reserved words that convey a special meaning to the
compiler. These are reserve for special purpose and must not be used as identifier
name.eg for , if, else , this , do, etc.
IDENTIFIERS:
Identifiers are programmer defined names given to the various program elements
such as variables, functions, arrays, objects, classes, etc.. It may contain digits,
letters and underscore, and must begin with a letter or underscore. C++ is case
sensitive as it treats upper and lower case letters differently. The following are
some valid identifiers: Pen time580 s2e2r3 _dos _HJI3_JK
LITERALS:
The data items which never change their value throughout the program run. There
are several kinds of literals:
· Integer literals
· Character literals
· Floating literals
· String literals
INTEGER LITERALS:
Integer literals are whole numbers without any fractional part. An integer literal
must have at least one digit and must not contain any decimal point. It may contain
either + or - sign. A number with no sign is assumed as positive. C++ allows three
types of integer literals:
9
A complete energized Study material of Computer Science for Class XII
(ii) Octal Integer Literals:- A sequence of octal digit starting with 0 (zero) is
taken to be an octal integer literal ( zero followed by octal digits). e.g.,
0345, 0123 , etc.
CHARACTER LITERALS:
Any single character enclosed within single quotes is a character literal. e.g ‗ A‘ ,
‗3‘
FLOATING LITERALS:
Numbers which are having the fractional part are referred as floating literals or real
literals. It may be a positive or negative number. A number with no sign is
assumed to be a positive number. e.g 2.0, 17.5, -0.00256
STRING LITERALS:
It is a sequence of character surrounded by double quotes. e.g., ―abc‖ , ―23‖.
PUNCTUATORS:
The following characters are used as punctuators which are also known as
separators in C++ [ ] { } ( ) , ; : * ……….. = #
10
A complete energized Study material of Computer Science for Class XII
OPERATORS:
(i) Unary operators: Those which require only one operand to operate upon.
e.g. unary - , unary + , ++ , - - ! .
Comments are the pieces of code that compiler ignores to compile. There are two
types of comments in C++.
1. Single line comment: The comments that begin with // are single line
comments. The Compiler simply ignores everything following // in the same
line.
2. Multiline Comment: The multiline comment begin with /* and end with */ .
This means everything that falls between /* and */ is consider a comment
even though it is spread across many lines.
11
A complete energized Study material of Computer Science for Class XII
(i) The cout Object: The identifier cout is a predefined object of ostream class
that represents the standered
output stream in C++ and tied to slandered output. cout stands for console output .
cout sends all output to the standard output device i.e. monitor. The syntax of cout
is as follows:
cout<< data;
Output Operator (<<): The output operator (<<) is also known as ‗stream insertion‘
or ‗put to‘ operator. It directs the contents of the variable (or value) on its right to
the object on its left (i.e. cout).
(ii) The cin Object: The cin object is an istream class object tied to slandered
input. cin stands for console input. cin object used to get input from the keyboard.
When a program reaches the line with cin, the user at the keyboard can enter
values directly into variables.
The syntax of cin is as follows:
Input Operator (>>): The input operator (>>) is also known as extraction or
‗get from‘ operator. It extracts (or takes) the value from the keyboard and assign it
to the variable on its right.
CASCADING OF OPERATOR:
When input or output ( >>or <<) are used more than one time in a single statement
then it is called as cascading of operators.
12
A complete energized Study material of Computer Science for Class XII
1. Fundamental or Built-in data types: These data types are already known to
compiler. These are the data types those are not composed of other data types.
There are following fundamental data types in C++:
(i) int data type (for integer) :- int data type is used for integer value. An identifiers
declare as int cannot have fractional part.
(ii) char data type (for characters):- An identifiers declare as char can store a
character.
(iv) float data type (for floating point numbers):- An identifier declare as float can
hold
a floating point number.
(v) double data type (for double precision floating point numbers):- The double
data
type is also used for handling floating point numbers but it occupies twice as
much
memory as float and store numbers with much larger range and precision.
Data Type Modifiers:-There are following four data type modifiers in C++ ,
which may be used to modify the fundamental datatypes to fit various situations
more precisely:
(i) signed
(ii) unsigned
(iii) long
(iv) short
signed, unsigned, long, short data type modifiers may be apply to char & int data
types. However you may also apply long to double
13
A complete energized Study material of Computer Science for Class XII
2.Derived Data Types:- These are the data types that are composed of
fundamental data types. e.g., array, class, structure, etc.
Declaration of Variables:- All variables must be declared before they are used in
executable statements. Variable declaration reserves memory required for data
storage and associates it with a name. Syntax for variable declaration is:
datatypes variable_name1, variable_name2, variable_name3,……………. ;
e.g.,
int num;
int num, sum, avg;
2. The setw( ) Manipulator: The setw( ) manipulator sets the width of the field
assign for the output. It takes the size of the field (in number of character) as a
parameter. The
output will be right justified e.g., the code:
cout<<setw(6)<<”R” ;
Generates the following output on the screen (each underscore represent a blank
space)
_ _ _ _ _ R
OPERATORS:-
Arithmetic operators:- Those operators are operates only on numeric data types
operands are known as arithmetic operators.
15
A complete energized Study material of Computer Science for Class XII
16
A complete energized Study material of Computer Science for Class XII
var = expression ;
17
A complete energized Study material of Computer Science for Class XII
This shorthand works for all binary arithmetic operators. The general form of this
shorthand is
Conditional operator ( ? : ):
The conditional operator (? :) is a ternary operator i.e., it require three operands.
The general form of conditional operator is:
expression1? expression2: expression3;
Where expression1 is a logical expression, which is either true or false. If
expression1 evaluates to true i.e., 1, then the value of whole expression is the value
of expression2, otherwise, the value of the whole expression is the value of
expression3. For example
min = a<b? a : b;
Here if expression (a<b ) is true then the value of a will be assigned to min
otherwise value of b will be assigned to min.
Comma operator ( , ):
The comma operator (,) is used to separate two or more expressions that are
included where only one expression is expected. When the set of expressions has to
be evaluated for a value, only the rightmost expression is considered.
For example, the following code:
a = (b =3 , b +2 );
Would first assign the value 3 to b, and then assign b+2 to variable a. So, at the
end, variable a would contain the value 5 while variable b would contain value 3.
18
A complete energized Study material of Computer Science for Class XII
sizeof():
This operator returns the size of its operand in bytes. The operand may be an
expression or identifier or it may be a data type.
a= sizeof (char);
This will assign the value 1 to a because char is a one-byte long type.
EXPRESSIONS:-
An expression in C++ is any valid combination of operators, constants, and
variables. Pure Expressions:-If an expression have all operand of same data types
then it is called a pure expression.
Mixed Expressions:- If an expression have operands of two or more different data
types then it is called a mixed expression.
Arithmetic Expressions:- Arithmetic expression can either be integer expressions
or real expressions. Sometimes a mixed expression can also be formed which is a
mixture of real and integer expressions.
Integer Expressions:- Integer expressions are formed by connecting all integer
operands using integer arithmetic operators.
Real Expressions:- Real expressions are formed by connecting real operands by
using real arithmetic operators.
Logical Expressions:- The expressions which results evaluates either 0 (false) or 1
(true) are called logical expressions. The logical expressions use relational or
Logical operators.
TYPE CONVERSION:- The process of converting one predefined data type into
another is called type conversion. C++ facilitates the type conversion in two forms:
19
A complete energized Study material of Computer Science for Class XII
TYPE CASTING:-
The explicit conversion of an operand to a specific type is called type casting.
Type Casting Operator - (type) :-Type casting operators allow you to convert a
data item of a given type to another data type. To do so , the expression or
identifier must be preceded by the name of the desired data type , enclosed in
parentheses . i. e.,
Where data type is a valid C++ data type to which the conversion is to be done. For
example , to make sure that the expression (x+y/2) evaluates to type float , write it
as:
(float) (x+y/2)
Statements:
STATEMENTS:-
Statements are the instructions given to the Computer to perform any kind of
action.
Null Statement:- A null statement is useful in those case where syntax of the
language
requires the presence of a statement but logic of program does not give permission
to do anything then we can use null statement. A null statement is nothing only a ;.
A null (or empty statement have the following form:
20
A complete energized Study material of Computer Science for Class XII
St-1;
St-2;
:
:
}
Statement Flow Control:- In a program , statements may be executed
sequentially,
selectively, or iteratively.
21
A complete energized Study material of Computer Science for Class XII
22
A complete energized Study material of Computer Science for Class XII
SELECTION STATEMENTS :-
There are two types of selection statements in C++:
1. if statement
2. switch statement
If the <conditional expression> is evaluated to true then the < statement-1 or block-
1>
(statement under if ( ) block ) will be executed otherwise the <statement-2 or
block-2>
(statements under else block) would be executed. if there exists only one program
statement under if( ) block then we may omit curly braces { }.
23
A complete energized Study material of Computer Science for Class XII
24
A complete energized Study material of Computer Science for Class XII
(c) The if-else-if ladder :- This statement allows you to test a number of mutually
exclusive cases and only execute one set of statements for which condition
evaluates true first. The syntax is:
if ( <condition -1> )
statement-1; // do something if condition-1 is satisfied (True)
else if ( <condition – 2 >)
statement-3 ; // do something if condition -2 is satisfied (True)
else if (<condition – 3 >)
statement-3 ; // do something if condition- 3 is satisfied (True)
:
: // many more n-1 else - if ladder may come
:
25
A complete energized Study material of Computer Science for Class XII
In the above syntax there are ladder of multiple conditions presented by each if( ) ,
all of these conditions are mutually exclusive. If one of them would evaluates true
then the statement followed that condition will be executed and all the conditions
below it would not be evaluated (checked).
Say suppose if condition-3 gets satisfy (i.e. evaluates true value for the condition),
then
statement-3 gets executed and all other conditions below it would be discarded.
If none of the n if ( ) conditions gets satisfied then the last else part always gets
executed. It is not compulsory to add an else at the last of the ladder.
26
A complete energized Study material of Computer Science for Class XII
Syntax 2:-
if ( <outer- condition > )
{
if ( <inner-condition> )
{
//some statements to be executed
// on satisfaction of inner if ( ) condition.
}
else
{
// statements on failure of inner if( )
}
<> in syntax is known as a place holder, it is not a part of syntax, do not type it
while writing program. It only signifies that anything being kept there varies from
program to program.
[ ] is also not a part of syntax , it is used to mark optional part of syntax i.e. all part
of syntax between [ ] is optional.
27
A complete energized Study material of Computer Science for Class XII
{
case value_1: statement -1;
break;
case value_2: statement -2;
break;
:
:
case value_n: statement -n;
break;
[ default: statement -m ]
}
Note: expression/variable should be integer or character type only.
When the switch statement is executed, the expression/variable is evaluated and
control is transferred directly to the statement whose case label value matches the
value of expression/ variable. If none of the case label value matches the value of
expression/variable then only the statement following the default will be executed.
If no default statement is there and no match is found then no action take place. In
this case control is transferred to the statement that follows the switch statement.
Example:
// Evaluates given input.
int command = menu(); // The function menu() reads
// a command.
switch( command ) // Evaluate command.
{
case 'a':
case 'A':
action1(); // Carry out 1st action.
break;
case 'b':
case 'B':
action2(); // Carry out 2nd action.
break;
default:
cout << '\a' << flush; // Beep on
} // invalid input
ITRATIVE STATEMENTS:
Loops in C++:- There are three loops or iteration statements are available in C++
28
A complete energized Study material of Computer Science for Class XII
1. for loop
2. while loop
3. do…. while loop
1. The for Loop: For loop is a entry control loop the syntax of for loop is :
Example:
for (int i = 0; i < 7; i++)
cout<< i * i << endl;
Interpretation:
An int i is declared for the duration of the loop and its value initialized to 0. i2 is
output in the body of the loop and then i is incremented. This continues until i is 7.
Sample Programe:
// Euro1.cpp
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double rate = 1.15; // Exchange rate:
// one Euro to one
Dollar
cout << fixed << setprecision(2);
cout << "\tEuro \tDollar\n";
for( int euro = 1; euro <= 5; ++euro)
29
A complete energized Study material of Computer Science for Class XII
cout << "\t " << euro << "\t " << euro*rate << endl;
return 0;
}
Screen output
Euro Dollar
1 0.95
2 1.90
3 2.85
4 3.80
5 4.75
2. While Loop:- while loop is also an entry controlled loop. The syntax of while
loop is:
while (loop_condition)
{
Loop_body
}
The loop iterates (Repeatedly execute) while the loop_condition evaluates to true.
When the loop_condition becomes false, the program control passes to the
statement after the loop_body.
In while loop , a loop control variable should be initialized before the loops begins.
The loop variable should be updated inside the loop body.
// average.cpp
Sample Programe for While loop:
// Computing the average of numbers
#include <iostream>
using namespace std;
int main()
{
int x, count = 0;
float sum = 0.0;
cout << "Please enter some integers:\n"
"(Break with any letter)"
<< endl;
30
A complete energized Study material of Computer Science for Class XII
do
{
Loop_body
}while (loop_condition);
In do-while loop first of all loop_body will be executed and then loop_condition
will be evaluates if loop_condition is true then loop_body will be executed again,
When the
loop_condition becomes false, the program control passes to the statement after the
loop_body.
Sample Programe:
// tone.cpp
#include <iostream>
using namespace std;
const long delay = 10000000L;
31
A complete energized Study material of Computer Science for Class XII
int main()
{
int tic;
cout << "\nHow often should the tone be output? ";
cin >> tic;
do
{
for( long i = 0; i < delay; ++i );
cout << "Now the tone!\a" << endl;
}
while( --tic > 0 );
cout << "End of the acoustic interlude!\n";
return 0;
}
Nested Loops:- Any looping construct can also be nested within any other looping
construct . Let us look at the following example showing the nesting of a for( )
loop within the scope of another for( ) loop :
For each iteration of the outer for loop the inner for loop will iterate fully up to the
last value of inner loop iterator. The situation can be understood more clearly as :
i= 1
j = 1 , output : 1 * 1 = 1
j = 2 , output : 1 * 2 = 2
j = 3 , output : 1 * 3 = 3
i= 2
j = 1 , output : 2 * 1 = 1
j = 2 , output : 2 * 2 = 4
j = 3 , output : 2 * 3 = 6
You can observe that j is iterated from 1 to 2 every time i is iterated once.
JUMP STATEMENTS:-
1. return
2. goto
3. break
4. continue
(i) An immediate exit from the function and the control passes back to the
operating system which is main‘s caller.
(ii) It is used to return a value to the calling code.
2. Goto statement :- A goto Statement can transfer the program control anywhere
in the program. The target destination of a goto statement is marked by a label. The
33
A complete energized Study material of Computer Science for Class XII
target label and goto must appear in the same function. The syntax of goto
statement is:
goto label;
:
label :
Example :
a= 0;
start :
cout<<―\n‖ <<++a;
if(a<50) goto start;
3. Break Statement :- The break statement enables a program to skip over part of
the code. A break statement terminates the smallest enclosing while, do-while, for
or switch statement. Execution resumes at the statement immediately following the
body of the terminated statement.
4. Continue Statement:- The continue is another jump statement like the break
statement as both the statements skip over a part of the code. But the continue
statement is somewhat different from break. Instead of forcing termination, it
forces the next iteration of the loop to take place, skipping any code in between.
Functions in C++
FUNCTION:
Function is a named group of programming statements which perform a specific
task and return a value. There are two types of functions:-
Following are some important Header files and useful functions within them:
34
A complete energized Study material of Computer Science for Class XII
The above list is just few of the header files and functions available under them ,
but actually there are many more. The calling of library function is just like User
defined function , with just few differences as follows:
Library functions also may or may not return values. If it is returning some values
then the value should be assigned to appropriate variable with valid datatype.
gets( ) and puts( ) : these functions are used to input and output strings on the
console during program run-time.
gets( ) accept a string input from user to be stored in a character array.
puts() displays a string output to user stored in a character array.
35
A complete energized Study material of Computer Science for Class XII
randomize( ) : This function provides the seed value and an algorithm to help
random() function in generating random numbers. The seed value may be taken
from current system‘stime.
To generate random numbers between a lower and upper limit we can use
following
Formula
random(U – L +1 ) + L
where U and L are the Upper limit and Lower limit values between which we want
to find out random values.
User-defined function:- The functions which are defined by user for a specific
purpose is known as user-defined function. For using a user-defined function it is
required, first define it and then using.
Function Prototype:- Each user define function needs to be declared before its
usage in the program. This declaration is called as function prototype or function
declaration. Function prototype is a declaration statement in the program and is of
the following form :
Return_type function_name(List of formal parameters) ;
36
A complete energized Study material of Computer Science for Class XII
Where Return_type is the data type of value return by the function. If the function
does not return any value then void keyword is used as return_type.
#include <iostream>
int addition (int a, int b)
{
int r;
r=a+b;
return (r);
}
void main ( )
{
int z ;
z = addition (5,3);
cout<< "The result is " << z;
}
37
A complete energized Study material of Computer Science for Class XII
The result is 8
void main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout <<"x="<< x <<", y="<< y <<", z="<< z;
}
The ampersand (&) (address of) is specifies that their corresponding arguments are
to be passed by reference instead of by value.
38
A complete energized Study material of Computer Science for Class XII
The qualifier const tell the compiler that the function should not modify the
argument. The compiler will generate an error when this condition is violated.
si_int= interest(5600,4);
Formal Parameters:- The parameters that appear in function definition are formal
parameters.
Actual Parameters:- The parameters that appears in a function call statement are
actual parameters.
Functions with no return type (The use of void):- If you remember the syntax of
a function declaration:
you will see that the declaration begins with a type, that is the type of the function
itself (i.e., the data type of value that will be returned by the function with the
return statement). But what if we want to return no value?
Imagine that we want to make a function just to show a message on the screen. We
do not need it to return any value. In this case we should use the void type specifier
for the function. This is a special specifier that indicates absence of type.
return ( value);
39
A complete energized Study material of Computer Science for Class XII
(iii) File Scope ( Global Scope):- An identifier has file scope or global
scope if it is declared outside all blocks i.e., it can be used in all blocks
and functions.
(iv) Class Scope :- A name of the class member has class scope and is
local to its class.
Lifetime :- The time interval for which a particular identifier or data value lives in
the memory is called Lifetime of the identifier or data value.
Examples 1:
// function example
#include <iostream>
using namespace std;
int addition (int a, int b)
{
int r;
r=a+b;
return (r);
}
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;
} The result is 8
Examples 2:
// function example
#include <iostream>
using namespace std;
40
A complete energized Study material of Computer Science for Class XII
Output on Screen:
The first result is 5
The second result is 5
The third result is 2
The fourth result is 6
Output on Screen:
I'm a function!
Output on Screen:
Output on Screen:
6
5
42
A complete energized Study material of Computer Science for Class XII
Need for Arrays:- Suppose we have to store roll number & marks of 50 students
in a program , then in all we need 100 variable each having a different name. Now
remembering and managing these 100 variables is not easy task and it will make
the program a complex and not understandable program.
But if we declare two array each having fifty elements one for roll numbers and
another for marks. Now, we have only two names to remember. Elements of these
array will be referred to as Arrayname[n], where n is the element number in in the
array. Therefore arrays are very much useful in a case where quit many elements of
the same data types need to be stored and processed.
The element number s in parenthesis are called subscripts or index. The subscript
or index of an element designates its position in the array‘s ordering.
TYPES OF ARRAY :-
1. One-dimensional Arrays
2. Multi-dimensional Arrays
Data_type Array_name[size];
43
A complete energized Study material of Computer Science for Class XII
For example the following statement declares an array marks of int data type ,
which have 50 elements marks[0] to marks[49].
int marks[50] ;
int scores[9];
char p[6];
44
A complete energized Study material of Computer Science for Class XII
int age[5];
Accepting Data in Array from User (Inputting Array elements) and Printing
Array elements:- Since we can refer to individual array elements using numbered
indexes, it is very common for programmers to use for (or any) loops when
processing arrays.
45
A complete energized Study material of Computer Science for Class XII
1. Initializing arrays.
When we declare an array, we have the possibility to assign initial values to each
one of its elements by enclosing the values in braces { }. Syntax for initialization
of one-dimensional array is:
For example:
num
The amount of values between braces { } must not be larger than the number of
elements that we declare for the array between square brackets [ ].
C++ allows us to skip the size of the array in an array initialization statement ( by
leaving the square brackets empty [ ] ). In this case, the compiler will assume a size
for the array equal to the number of values given between braces { }:
After this declaration, the size of array num will be 5, since we have provided 5
initialization values.
// arrays example
#include <iostream>
using namespace std;
int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{
46
A complete energized Study material of Computer Science for Class XII
result += billy[n];
}
cout << result;
return 0;
}
Screen output:
12206
String as an array:- C++ does not have a string data type rather it implements
string as single dimensional character array. A string is defined as a character array
terminated by a null character ‗\0‘. Hence to declare an array strg that holds a 10
character string, you would write :
char strg[11];
Example program:
#include <iostream>
using namespace std;
int main ()
{
char question[] = "Please, enter your first
name: ";
char greeting[] = "Hello, ";
char yourname [80];
cout << question;
cin >> yourname;
cout << greeting << yourname << "!";
return 0;
}
Screen output:
Please, enter your first name: John
Hello, John!
Two dimensional array : A two dimensional array is a continuous memory
location holding similar type of data arranged in row and column format (like a
matrix structure).
Declaration of 2-D array:- The general syntax used for 2-Darray declaration is:
Data_type Array_name [R][C] ;
47
A complete energized Study material of Computer Science for Class XII
For example,
and, for example, the way to reference the second element vertically and fourth
horizontally in an expression would be:
marks[1][3]
Initialization of 2-D Array:- Two dimensional arrays are also initialize in the
same way as single dimensional array . e. g.,
is also valid.
Accepting Data in 2-D Array from User (Inputting 2-D Array elements) and
Printing 2-D Array elements:- Since We must reference both, a row number and a
column number to input or output values in a two-dimensional array. So, we use a
nested loop (generally nested for loop) , when processing 2-D arrays.
48
A complete energized Study material of Computer Science for Class XII
char string[10][51] ;
Notice that the second index has been given 51, because 1 extra size is given for
store null character ‗\0‘.
Example Program:
#define WIDTH 5
#define HEIGHT 3
int jimmy [HEIGHT][WIDTH];
int n,m;
int main ()
{
for (n=0;n<HEIGHT;n++)
for (m=0;m<WIDTH;m++)
{
jimmy[n][m]=(n+1)*(m+1);
}
return 0;
}
STRUCTURES:-
Defining Structure :-
49
A complete energized Study material of Computer Science for Class XII
A Structure is defined by using the Keyword struct. The General Syntax for
defining a Structure is :
Syntax:
struct< Name of Structure >
{
<datatype>< data-member 1>;
<datatype>< data-member 2>;
<datatype>< data-member 3>;
…
…
<datatype>< data-member n>;
};
Example:
A Proper example following the previous syntax could be:
float rate ;
};
Declaring Structure Variable :-
This is similar to variable declaration. We can declare the variable of structure type
using two different ways either with structure definition or after structure
definition.
The following syntax shows the declaration of structure type variables with
structure
definition:
We can declare the structure type variables separately (after defining of structure)
using following syntax:
Structure_Variable_Name.element_name
First Method:-
#include <iostream.h>
#include <conio.h>
void main()
{
// Declaring structure at here
struct Employee
{
int empcode;
float empsalary;
};
Employee emp1 = {100, 8980.00} ; // emp1 is the structure variable ,
// which is also initialize with declaration
clrscr();
int i; // declares a temporary variable for print a line
// Printing the structure variable emp1 information to the
screen
cout<< "Here is the employee information : \n";
for (i = 1; i <= 32; i++)
cout<< "=";
cout<< "\nEmployee code : " << emp1.empcode;
cout<< "\nEmployee salary : " << emp1.empsalary;
}
51
A complete energized Study material of Computer Science for Class XII
Second Method:-
#include <iostream.h>
#include <conio.h>
void main()
{
// Declaring structure here
struct Employee
{
int empcode;
float empsalary;
} emp1; // emp1 is the structure variable
clrscr();
int i; // declares a temporary variable for print a line
// Initialize members here
emp1.empcode = 100;
emp1.empsalary = 8980.00;
// Printing the structure variable emp1 information to the
screen
cout<< "Here is the employee information : \n";
for (i = 1; i <= 32; i++)
cout<< "=";
cout<< "\nEmployee code : " << emp1.empcode;
cout<< "\nEmployee salary : " << emp1.empsalary;
}
We know that every variable in C++ can be assigned any other variable of same
data type i,e :
if int a = 7 ; b = 3;
we can write :
52
A complete energized Study material of Computer Science for Class XII
WORKER w2 = w1;
Note: Both structure variables must be of same type (i,e WORKER in this
case).
<structure_name><array_name>[ size ];
where : structure_name is the name of the structure which you have created.
array_name is any valid identifier size is a positive integer constant.
Worker W[20];
53
A complete energized Study material of Computer Science for Class XII
Each of the elements of the array is itself a structure hence each of them have all
the four components.
<return_type> function_name(<structure_name><var> , … , … );
Let us understand the concept with following function, which increases the wage
of a female worker by passed percent
Similarly, if we don't want to pass our structure variable as reference we can do so,
but then we have to return the modified structure variable back. This can be
achieved in above function, if we take return type as structure name. Let us modify
the function so that it returns a structure :
54
A complete energized Study material of Computer Science for Class XII
struct address
{
int houseno;
char city[20];
char area[20];
long int pincode;
};
struct employee
{
int empno;
char name[30];
char design[20];
char department[20];
address ad; // nested structure
}
Declaration:
employee e;
Input /Output :
typedef :- The typedef keyword allows to create a new names for data types. The
syntax is:
When this line appears in a file, all subsequent occurances of identifier in that file
will be replaced by replacement_text automatically before the program is
compiled. e.g.,
55
A complete energized Study material of Computer Science for Class XII
#include <iostream.h>
#define PI 3.14159
#define CIRCLE_AREA(x) (PI * (x) * (x))
void main()
{
float area;
int r;
cout<< "Enter the radius : ";
cin>> r;
area = CIRCLE_AREA(r);
cout<< "Area is : " << area;
}
**************************
56
A complete energized Study material of Computer Science for Class XII
Objectives:
In this Chapter you will learn about:
o Classes & Objects
o Constuctor And Destructor
o Inheritance -Extending Classes
o Data File Handling In C++
o Pointers
Class:-
A class is a user defined data that contained data as well as function together.
or
A class is a way to bind the data and function together in a single unit.
or
A class is a group of objects that share common properties and relationships
Note:-
1. The variables and functions enclosed in a class are called data member and
member functions.
2. The variable of class are called objects or instance of a class .
3. Classes are basic user defined data type of object oriented programming
language
4. The difference between a class and structure is that ,by default ,all the
members of a class are private while by default ,all the members of structure
are public
Class Declaration:-
Class <classname>
{
private:
data members;
member functions;
protected:
data members;
57
A complete energized Study material of Computer Science for Class XII
member functions;
public:
data members ;
member functions:
};
Note:- The data members and member functions of class are grouped under three
sections.
1. private
2. protected
3. public
Explanation of private ,protected & public access modifier:-
Private :-
o By private we mean that members can be accessed only from within
the class i.e member data can be accessed by the member function .
o The private data members are not accessible to the outside worls (i.e
outside the class)
o By default members of a class are private.
o Private members are not inheritable.
Protected:-
o The members which are declared as protected ,can only be accessed by
member functions and friends function function of that class.
o Protected members are similar to private members, the only difference
is that protected members are inheritable.
Public:-
The members which are declared as public can be accessed from outside classes
also.
Note:- By default ,the members of a class are private .if both the labels, are
missing, then by default, all the members are private .Such a class is completely
hidden from outside world.
Example:-
class Student
{
int rollno;
float marks;
public:
58
A complete energized Study material of Computer Science for Class XII
Array of Objects:- An array of variables that are of the type Class .such variables
are called array of objects.
Example:
class employee
{
char name[50];
int age;
public:
void getdata(void);
void showdata(void);
};
The employee is a user defined data type and can be used to create objects that
relate to different categories of employees.
employee manager[4];
employee engineer[15];
employee workers[200];
Creating Objects:-
----------------
} S1,S2;
Accessing Class Members:- After creating the objects there is a need to access the
class members .This can be done using ( . ) operator.
Syntax:
S1.getdata(129,100)
s1.display()
s1.rollno=129 // illegal statement
Note:- A variable declared public can be accessed by the objects directly.
60
A complete energized Study material of Computer Science for Class XII
#include <iostream.h>
#include<conio.h>
class calculator
{
private :
int x;
int y;
public :
void getdata();
{
cout<<― Enter the two numbers:‖ << endl;
cin>> x >> y;
}
void display()
{
cout<<―x=―<<x<<endl;
cout<<―y=―<<y<<endl;
}
void sum()
{
cout<<― addition of x & y =―<<x+y<<endl;
}
void diff()
{
cout << ― diff of x & y =― <<x-y<<endl;
}
void mul()
{
cout<<― mul of x & y =―<<x*y<<endl;
}
void div()
{
cout<< ― div of x & y=―<< x/y<<endl;
}
};
61
A complete energized Study material of Computer Science for Class XII
Void main()
{
clrscr();
calculator C1;
c1.getdata();
c1.display();
c1.sum();
c1.diff();
c1.mul();
c1.div();
getch();
}
Class method definition:- The data members of a class must be declared within
the body of the class ,whereas member functions of the class can be defined in
following ways:
Syntax:-
Example:
#include<iostream.h>
#include<conio.h>
class product
{
int qty;
float cost;
Public:
void getdata(int a, float b);
62
A complete energized Study material of Computer Science for Class XII
void putdata(void);
};
void main()
{
clrscr();
product p;
cout<<― The object ps is ―<< endl;
p.getdata(75,255.60);
p.putdata();
product Q;
cout<<― The object Q is =― << endl;
Q.getdata(100,125.25);
Q.putdata();
getch();
}
Note:- When a function is defined inside a class ,it is treated as inline function.
Normally small functions are defined inside the class definition.
Example:-
#include<iostream.h>
#include< conio.h>
class date
{
private:
63
A complete energized Study material of Computer Science for Class XII
int day;
int month;
int year;
public:
void getdata(int x,int y,int z)
{
day=x;
month=y;
year=z;
}
void display()
{
cout<< day<<month<<year <<endl;
}
}
Void main()
{
clrscr();
date d1,d2,d3;
d1.getdata(30,12,2012);
d2.getdata(23,11,2011)
d3.getdata(24,05,2010);
cout<< ― you have entered following date‖;
d1.display();
d2.display();
d3.display();
getch();
}
Array of Objects:-
An array of variables that are of the type Class .Such variables are called array of
objects.
Example:
class employee
{
char name[50];
64
A complete energized Study material of Computer Science for Class XII
int age;
public:
void getdata(void);
void showdata(void);
};
The employee is a user defined data type and can be used to create objects that
relate to different categories of employees.
employee manager[4];
employee engineer[15];
employee workers[200];
Example:-
#include<iostream.h>
#include<conio.h>
class employee
{
char name[50];
int age;
public:
void getdata(void);
void showdata(void);
};
void employee::showdata(void)
{
cout<<name<<endl<<age;
}
void main()
{
clrscr();
65
A complete energized Study material of Computer Science for Class XII
int size=4;
employee manager[size];
for(int i=0; i<size;i++)
{
cout<<―Enter Details of managers‖;
manager[i].getdata();
}
cout<<endl;
for(i=0;i<size;i++)
{
cout<<―Details of Managers is=―;
manager[i].putdata();
}
getch();
}
Friend Function:-
A friend function is not a member function ,has full access rights to the private
members of the class.
Syntax :-
class ABC
{
------------
------------
public:
--------------
--------------
friend void xyz(void);
}
o It is not in the scope of the class to which it has been declared as friend.
o Since it is not in the scope of the class ,it cannot be called using the object of
that
class.
o It can be invoked like a normal function without the help of any object.
66
A complete energized Study material of Computer Science for Class XII
o Unlike member functions, it cannot access the member names directly and
has to use an object name and dot membership operator with each member
name.
o It can be declared either in the public or the private part of a class without
affecting its meaning.
Usually ,it has the objects as arguments.
Example:-
#include<iostream.h>
#include<conio.h>
Class sample
{
int a;
int b;
public:
void setvalue()
{
a=25;
b=40;
}
void main()
{
sample x;
x.setvalue();
cout<<mean(x);
}
#include<iostream.h>
class XYZ
67
A complete energized Study material of Computer Science for Class XII
{
int x;
public:
void setvalue(int i)
{
x=I;
}
friend void max(XYZ,ABC);
};
class ABC
{
int a;
public:
void setvalue(int i)
{
a=i;
}
friend void max(XYZ,ABC);
};
void main()
{
ABC abc;
abc.setvalue(10);
XYZ xyz;
xyz.setvalue(20);
max(xyz,abc);
}
68
A complete energized Study material of Computer Science for Class XII
o pass by value
o pass by reference.
#include<iostream.h>
#include<conio.h>
class class_2;
class class_1
{
int value1;
public:
void indata(int a)
{
value1=a;
}
void display(void)
{
cout<<value1<<―\n‖;
friend void exchange(class _1 obj1, class_2 obj2);
}
class class2
{
int value2;
public:
void indata(int a)
{
value2=a;
}
void display(void )
{
cout<<value2<<―\n‖;
}
friend void exchange (class _1 t1, class_2 t2);
};
69
A complete energized Study material of Computer Science for Class XII
T1.value1=T2.value2;
T2.value2=temp;
}
void main()
{
class_1 C1;
class_2 C2;
C1.indata(100);
C2.indata(200);
cout<<― values before exchange ―<<―\n‖;
C1.display();
C2.display();
exchange(C1,C2);
cout<<― values after exchange‖<<―\n‖;
C1.display();
C2.display();
}
Constructor:-
Note:-
o A constructor is distinct from other member functions because its name is
same as the name of the class .It is executed automatically when an object is
declared. The only restriction that applies to constructor is that it must not
have a return type not even void.
o Constructor of a class is the first member function to be executed
automatically when an object of the class is created.
class classname
{
-------------
-------------
70
A complete energized Study material of Computer Science for Class XII
-------------
classname( parameter list);
-----------------
};
Example:
class Bank
{
private:
int x,y;
---------
----------
public:
Bank( );
};
Bank :: Bank( )
{
x=0;
y=0;
}
void main()
{
Bank B;
}
Example:-
#include<iostream.h>
#include<conio.h>
class fibonacci
71
A complete energized Study material of Computer Science for Class XII
{
private:
int fo,f1,fib;
public:
fibonacci();
void increment();
void display();
};
fibonacci::fibonacci()
{
fo=0;
f1=1;
fib=fo+f1;
}
void fibonacci::increment()
{
fo=f1;
f1=fib;
fib=fo+f1;
}
void fibonacci:: display()
{
cout<< fib<<―\t‖;
}
void main()
{
clrscr();
fibonacci F;
for(int i=0;i<=15;++i)
{
F.display();
F.increment();
getch();
}
}
Default Constructor:
A constructor that accepts no parameters is called default constructor.
72
A complete energized Study material of Computer Science for Class XII
Syntax:
class First
{
private:
-----------
----------
public:
first();
----------
----------
};
First :: First()
{
}
#include<iostream.h>
#include<conio.h>
class student
{
private:
char name[50];
int roll_no;
char sex;
int age;
float marks;
public:
student();
void putdata();
};
student:: student()
{
gets(name,‖Donald‖);
roll_no=12;
sex=‗M‘;
age=34;
marks=90;
}
73
A complete energized Study material of Computer Science for Class XII
Parameterized constructor:-
The constructor that can take arguments are called Parameterized constructor.
Example:
class Bank
{
private:
int x,y;
public:
Bank(int a, int b)
-----------------------
-------------------
};
Implicit call
74
A complete energized Study material of Computer Science for Class XII
Explicit call
Implicit call:
Bank b1(5,11);
Explicit Call:
Bank B1=Bank(5,11);
Example:-
#include<iostream.h>
#include<conio.h>
class Bank
{
int x,y;
public:
Bank(int ,int);
void putdata()
{
cout<<x<<―\n‖<<y;
}
};
void main()
{
clrscr();
Bank B1(5,11);
Bank B2=Bank(6,34);
cout<<― object 1‖;
B1.putdata();
cout<<―object 2‖;
B2.putdata();
getch();
}
75
A complete energized Study material of Computer Science for Class XII
Copy Constructor:-
A copy constructor takes a reference to its own class as parameter i.e a constructor
having a reference to an instance of its own class as an argument is known as copy
constructor. Copy constructor are used in following situations:
Example:
Sample S1; //default constructor
Sample S2(S1);
or
Sample S2=S1;
void main()
{
76
A complete energized Study material of Computer Science for Class XII
clrscr();
Sample P(45);
Sample Q(P);
Sample R=P;
Sample T;
T=P;
cout<<― \n value of p:‖;
P.display();
cout<<―\n value of Q:‖;
Q.display();
cout<<― \n value of R‖;
R.display();
cout<<―\nValue of T:‖;
T.display();
getch();
}
Example:
Example:
class student
{
private :
char name[50];
int age;
char sex;
float marks;
77
A complete energized Study material of Computer Science for Class XII
public:
student(); // Constructor
~ student(); // Destructor
void getdata();
void putdata();
};
DESTRUCTOR:
A destructor is a member function having same name as its class but preceded by ~
sign and it deinitialises an object before it goes out of scope.
Program:-
#include<iostream.h>
#include<conio.h>
class sample
{
public:
sample( )
{
cout<<― object is born\n‖;
}
~sample ()
{
cout <<― object is dead‖
}
};
void main()
{
clrscr();
sample S;
cout<<― Main terminated ―<<endl;
getch();
}
78
A complete energized Study material of Computer Science for Class XII
Inheritance is the process of creating new classes called derived classes from
existing ones. i.e base classes.
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance.
Derived and Base Class:- A derived class extends its features by inheriting the
properties of another class, called base class and adding features of its own.
79
A complete energized Study material of Computer Science for Class XII
Public Derivation:-
Example:-
#incude <iostream.h>
#include<conio.h>
class item
{
int x;
public:
int y;
void getdata();
int getvalue(void);
void display(void);
};
80
A complete energized Study material of Computer Science for Class XII
cout<<―x=―<<x<<endl;
}
void main()
{
clrscr();
newitem n;
n.getdata();
n.mul();
n.display();
n.show();
n.y=45;
n.mul();
n.show();
getch();
}
81
A complete energized Study material of Computer Science for Class XII
2. Multilevel Inheritance:-
Derivation of class from another derived class is called inheritance i.e when one
derived class inherits from a class that itself inherits from another class is called
multilevel inheritance.
Syntax:
#include<iostream.h>
#include<conio.h>
const int size=50;
class person
{
char name[size];
int age;
char sex;
public:
void getdata()
{
cout<<― name=―;
cin>>name;
cout<<―Age‖;
cin>>age;
cout<<―sex=―;
cin>>sex;
}
void display()
{
cout<<―name =― << name <<endl;
cout<<―Age=―<<Age<<endl;
cout<<―sex=―<<sex<<endl;
}
};
82
A complete energized Study material of Computer Science for Class XII
int rollno;
char branch[50];
public:
getdata()
{
Person::getdata();
cout<<―Rollno=―;
cin>>rollno;
cout<<―Branch‖;
cin>>branch;
};
void display()
{
person:: display();
cout<<―Rollno =―<<rollno<<endl;
cout<<―Branch=―<<branch<<endl;
}
};
83
A complete energized Study material of Computer Science for Class XII
int Totalmarks()
{
return marks1+marks2;
}
};
void main()
{
clrscr();
Exam e;
e.getdata();
e.display();
}
3. Multiple Inheritance:
A class can be derived from more than one base class i.e a class can inherit the
properties of two or more than two classes .This is called multiple inheritance.
Syntax:-
class derived class : Visibility BaseClass1, Visibility Base Class2, …………E.g.
class X
{
84
A complete energized Study material of Computer Science for Class XII
------
------
};
class y
{
-------
--------
};
class Z
{
--------------
--------------
};
#include<iostream.h>
#include<conio.h>
class X
{
protected:
int a;
public:
void getdata(int);
};
class Y
{
protected :
int b;
public:
void getdata1(int);
};
85
A complete energized Study material of Computer Science for Class XII
{
public:
void display(void );
};
void X :: getdata(int m)
{
a=m;
}
void Z::display(void)
{
cout<<―a=―<<a<<endl;
cout<<―b=―<<b<<endl;
cout<<―a+b=―<<a+b<<endl;
cout<<―a/b=―<<a/b<<endl;
}
void main()
{
clrscr();
Z d;
d.getdata(30);
d.getdata1(15);
d.display();
getch();
}
4. Hierarchical Inheritance:
When many derived classes are inherited from single base class it is called
hierarchical Inheritance .
86
A complete energized Study material of Computer Science for Class XII
Syntax:-
class A: public X
class B : public X
class C: public X
Example:
# include<iostream.h>
#include< conio.h>
class personal
{
private:
int rollno;
char name[15];
char sex;
public:
void getdata();
void putdata();
};
87
A complete energized Study material of Computer Science for Class XII
88
A complete energized Study material of Computer Science for Class XII
o Text file: A text file stores information in readable and printable form. Each
line of text is terminated with an EOL (End of Line) character.
o Binary file: A binary file contains information in the non-readable form i.e.
in the same format in which it is held in memory.
There are three file I/O classes used for file read / write operations.
o ifstream - can be used for read operations.
o fstream - can be used for write operations.
o fstream - can be used for both read & write operations.
o fstream.h:
This header includes the definitions for the stream classes ifstream,
ofstream and fstream. In C++ file input output facilities implemented
through fstream.h header file. It contain predefines set of operation for
handling file related input and output fstream.h class ties a file to the
program for input and output operation.
o A file can be opened using:
o By the constructor of the stream. This method is preferred when single
file is used with the stream. (only for input / only for output)
o By the open() function of the stream.
89
A complete energized Study material of Computer Science for Class XII
File modes:
o ios::out - It creates file in output mode and allows writing into the file.
o ios::in - It creates file in input mode and permit reading from the file.
o ios::app - To retain the previous contents of the file and to append to the end
of existing file.
o ios::ate - To place the file pointer at the end of the file, but you can write
data any where in the file.
o ios::trunc - It truncates the existing file (empties the file).
o ios::nocreate - If file does not exist this file mode ensures that no file is
created and open() fails.
o ios::noreplace - If file does not exist, a new file gets created but if the file
already exists, the open() fails.
o ios::binary – Opens a file in binary.
o eof(): This function determines the end-of-file by returning true for end of
file otherwise returning false.
o open():If you want to manage multiple file with same stream use open().
Stream_object.open(―Filename‖,(Filemode));
e.g., fstream fio;
o close(): This function terminates the connection between the file and stream
associated with it.
Stream_object.close();
o read(): The read() function reads a fixed number of bytes from the specified
stream and puts them in the buffer.
o write(): The write() function writes fixed number of bytes from a specific
memory location to the specified stream.
90
A complete energized Study material of Computer Science for Class XII
tellg(): This function returns the current position of the get pointer in a stream.
tellp(): This function returns the current position of the put pointer in a stream.
int countalpha()
{
ifstream Fin(―BOOK.txt‖);
char ch;
int count=0;
while(!Fin.eof())
{
Fin.get(ch);
if (islower(ch))
count++;
}
Fin.close();
return count;
}
2.Write a function in C++ to count and display the number of lines starting
with
alphabet „A‟ present in a text file “LINES.TXT”.
void counter( )
{
char Aline[80];
int Count=0;
ifstream Fin (―LINES.TXT‖);
while(!fin.eof())
91
A complete energized Study material of Computer Science for Class XII
{
Fin.getline(Aline,80, ‗\n‘))
if (Aline[0]== ‗A‘)
Count++;
}
cout<<Count<<endl;
Fin.close( );
}
void COUNT_DO ()
{
fstream f;
Clrscr();
f.open (―MEMO.TXT‖, ios :: in);
char are [80];
char ch;
int i = 0, sum = 0,n = 0 ;
While (f)
{
f. get (ch);
are [i] = ch;
i++;
if (strcpy (ch, ―do‖))
{
i– –;
sum = sum + i;
n++;
}
}
cout<<―The total no. of the do is:‖<<n;
}
4.Write a function in C++ to count the number of vowels present in a text file
“STORY.TXT”.
Ans: void vowelcount( )
{
ifstream file(―STORY.TXT‖);
int n=0;
92
A complete energized Study material of Computer Science for Class XII
while(file.get(ch))
{
if(ch==‘a‘|| ch==‘A‘|| ch==‘e‘|| ch==‘E‘|| ch==‘i‘|| ch==‘I‘|| ch==‘o‘||
ch==‘O‘||ch==‘u‘||ch==‘U‘)
n++;
}
cout<<‖\n Total no. of vowels are‖<<n;
file.close();
}
5. Write a function in C++ to count the number of lines present in a text file
“STORY.TXT”.
Ans : void CountLine()
{
ifstream FIL(―STORY.TXT‖);
int LINES=0;
char STR[80];
while (FIL.getline(STR,80))
LINES++;
cout<<‖No. of Lines:‖<<LINES<<endl;
FIL.close();
}
6. Write a function in C++ to count the word “this” /”THIS” present in Text
file
“ Diary.TXT”
Ans : void wordcount( )
Fstream file;
file.open(―Diary.TXT‖,ios::in);
char word[20];
int count=0;
while (!file.eof( ))
{
file>>word;
if(!strcmp(word,‖this‖)||strcmp(word,‖THIS‖)||!strcmp(word,‖THIS‖))
count++;
}
cout<<‖ Number of this/This/THIS=‖<<count<<endl;
file. Close( );
}
7. Write a function in C++ to read the content of a text file "PLACES.TXT"
anddisplay all those lines on screen, which are either starting with 'P' or
starting with 'S'.
93
A complete energized Study material of Computer Science for Class XII
Q1. Write a function in C++ to add more new objects at the bottom of a
binary file STUDENT.DAT”, assuming the binary file is containing the
objects of the following class.
class STUD
{
int Rno;
char Name[20];
public:
void Enter(){cin>>Rno;gets(Name);}
void Display(){cout<<Rno<<Name<<endl;}
};
94
A complete energized Study material of Computer Science for Class XII
}
Q2. Write a function in C++ to read & display the details of all the members
whose membership type is „L‟ or „M‟ from a binary file “CLUB.DAT”.
Assume the binary file contains object of class CLUB.
class CLUB
{
int mno;
char mname[20];
char type;
public:
void register ( );
void dis();
char whattype( )
{
return type;
}
};
95
A complete energized Study material of Computer Science for Class XII
void register();
void show();
int check(char ac[ ])
{
return strcmp(area,ac)
}
};
Write a function TRANSFER( ) in C++, that would copy all records which are
having
area as ‖DEL‖ from PHONE.DAT to PHONBACK.DAT.
Ans:
void transfer( )
{
ifstream Fin;
ofstream Fout;
Phonlist ph;
Fin.open(―PHONE.DAT‖, ios::in | ios::binary);
Fout.open(―PHONBACK.DAT‖, ios::out | ios:: binary);
while(Fin.read((char*)&ph, sizeof(ph)))
{
if(ph.check(―DEL‖) == 0)
Fout.write((char*)&ph, sizeof(ph));
}
Fin.close();
Fout.close();
}
96
A complete energized Study material of Computer Science for Class XII
void EnterData()
{
gets(S_Admno);gets(S_Name);cin>>Percentage;
}
void DisplayData()
{
cout<<setw(12)<<S_Admno;
cout<<setw(32)<<S_Name;
cout<<setw(3)<<Percentage<<endl;
}
int ReturnPercentage()
{
return Percentage;
}
};
Write a function in C++, that would read contents of file STUDENT.DAT and
display the details of those Students whose Percentage is above
1. Observe the program segment given below carefully and fill the blanks
marked as Line 1 and Line 2 using fstream functions for performing the
required task. 1
#include <fstream.h>
class Library
{
long Ano; //Ano – Accession Number of the Book
char Title[20]; //Title – Title of the Book
97
A complete energized Study material of Computer Science for Class XII
Ans:
File. seekp (position, ios :: beg); // Line–1
File. write ((char *) & L, sizeof (L)); // Line–2
2. Observe the program segment given below carefully and fill the blanks
marked as Statement 1 and Statement 2 using seekg() and tellg() functions for
performing the required task.
98
A complete energized Study material of Computer Science for Class XII
#include <fstream.h>
class Employee
{
int Eno;char Ename[20];
public:
//Function to count the total number of records
int Countrec();
};
int Item::Countrec()
{
fstream File;
File.open(―EMP.DAT‖,ios::binary|ios::in);
______________________ //Statement 1
int Bytes = ______________________ //Statement 2
int Count = Bytes / sizeof(Item);
File.close();
return Count;
}
Ans:
File.seekg(0,ios::end); //Statement 1
File.tellg(); //Statement 2
POINTERS:
Pointer is a variable that holds a memory address of another variable of same
type.
It supports dynamic allocation routines.
It can improve the efficiency of certain routines.
C++Memory Map :
Program Code : It holds the compiled code of the program.
Global Variables : They remain in the memory as long as program
continues.
Stack : It is used for holding return addresses at function calls, arguments
passed tothe functions, local variables for functions. It also stores the current
state of the CPU.
Heap : It is a region of free memory from which chunks of memory are
allocated via DMA functions.
99
A complete energized Study material of Computer Science for Class XII
Syntax :
Datatype *variable_name;
Two special unary operator * and & are used with pointers. The & is a unary
operator that returns the memory address of its operand.
Pointer arithmetic:
Two arithmetic operations, addition and subtraction, may be performed on
pointers. When you add 1 to a pointer, you are actually adding the size of whatever
the pointer is pointing at. That is, each time a pointer is incremented by 1, it points
to the memory location of the next element of its base type.
100
A complete energized Study material of Computer Science for Class XII
If current address of p is 1000, then p++ statement will increase p to 1002, not
1001.
Adding 1 to a pointer actually adds the size of pointer‘s base type.
Base address : A pointer holds the address of the very first byte of the memory
location where it is pointing to. The address of the first byte is known as BASE
ADDRESS.
101
A complete energized Study material of Computer Science for Class XII
Array of Pointers :
To declare an array holding 10 int pointers –
int * ip[10];
That would be allocated for 10 pointers that can point to integers. Now each of the
pointers, the elements of pointer array, may be initialized. To assign the address
of an integer variable phy to the forth element of the pointer array, we have to
write ip[3] = & phy; Now with *ip[3], we can find the value of phy. int *ip[5];
Index 0 1 2 3 4
Variable a b c d e
Value 12 23 34 45 56
102
A complete energized Study material of Computer Science for Class XII
ip[0] = &a; ip[1] = &b; ip[2] = &c; ip[3] = &d; ip[4] = &e;
ip is now a pointer pointing to its first element of ip. Thus ip is equal to address of
ip[0], i.e. 1000
void main()
{
char str[] = ―computer‖;
char *cp;
cp=str;
cout<<str ; //display string
cout<<cp; // display string
for (cp =str; *cp != ‗\0‘; cp++) // display character by character by character
cout << ‖--―<<*cp;
// arithmetic
str++; // not allowed because str is an array and array name is constant pointer
cp++; // allowed because pointer is a variable
cout<<cp;
}
Output :
Computer
Computer
--c--o--m--p--u--t--e—r
Computer
103
A complete energized Study material of Computer Science for Class XII
In the above given declaration subject[] is an array of char pointers whose element
pointers contain base addresses of respective names. That is, the element pointer
subject[0] stores the base address of string ―Chemistry‖, the element pointer
subject[1] stores the above address of string ―Physics‖ and so forth.
An array of pointers makes more efficient use of available memory by consuming
lesser number of bytes to store the string.
An array of pointers makes the manipulation of the strings much easier. One can
easily exchange the positions of strings in the array using pointers without actually
touching their memory locations.
o Call by value
o Call by reference
104
A complete energized Study material of Computer Science for Class XII
For example the program of swapping two variables with reference method:
#include<iostream.h>
void main()
{
void swap(int &, int &);
int a = 5, b = 6;
cout << ―\n Value of a :‖ << a << ― and b :‖ << b;
swap(a, b);
cout << ―\n After swapping value of a :‖ << a << ―and b :‖ << b;
}
105
A complete energized Study material of Computer Science for Class XII
Output :
Value of a : 5 and b : 6
After swapping value of a : 6 and b : 5
#include<iostream.h>
void main()
{
void swap(int *m, int *n);
int a = 5, b = 6;
cout << ―\n Value of a :‖ << a << ― and b :‖ << b;
swap(&a, &b);
cout << ―\n After swapping value of a :‖ << a << ―and b :‖ << b;
}
Input:
Value of a : 5 and b : 6
After swapping value of a : 6 and b : 5
106
A complete energized Study material of Computer Science for Class XII
Dynamic structures :
The new operator can be used to create dynamic structures also i.e. the structures
for which the memory is dynamically allocated.
A called function receiving an object as a parameter creates the copy of the object
without invoking the constructor. However, when the function terminates, it
destroys this copy of the object by invoking its destructor function.
107
A complete energized Study material of Computer Science for Class XII
If you want the called function to work with the original object so that there is no
need to create and destroy the copy of it, you may pass the reference of the object.
Then the called function refers to the original object using its reference or alias.
Also the object pointers are declared by placing in front of an object pointer‘s
name.
Classname * object-pointer;
e.g. Student *stu;
The member of a class is accessed by the arrow operator (->) in object pointer
method. e.g :
#include<iostream.h>
class Point
{
int x, y;
public :
Point()
{
x = y = 0;
}
void getPoint(int x1, int y1)
{
x = x1; y = y1;
}
void putPoint()
{
cout << ―\n
Point : (― << x<< ―, ―<< y<< ―)‖;
}
};
void main()
{
Point p1, *p2;
cout << ―\n Set point at 3, 5 with object‖;
p1.getPoint(3,5);
cout << ―\n The point is :‖;
p1.putPoint();
p2 = &p1;
cout << ―\n Print point using object pointer :‖;
p2->putPoint();
108
A complete energized Study material of Computer Science for Class XII
You can even make a pointer point to a data member of an object. Two points
should be considered:
this Pointer:
In class, the member functions are created and placed in the memory space only
once. That is only one copy of functions is used by all objects of the class.
Therefore if only one instance of a member function exists, how does it come to
know which object‘s data member is to be manipulated?
For the above figure, if Member Function2 is capable of changing the value of
Data Member3 and we want to change the value of Data Member3 of Object3.
How would the Member Function2 come to know which Object‘s Data Member3
is to be changed?
To overcome this problem this pointer is used.
109
A complete energized Study material of Computer Science for Class XII
*************************
110
A complete energized Study material of Computer Science for Class XII
Unit 3
Data Structure
Objectives:
In this Chapter you will learn about:
o Arrays
o Searching techniques
o Sorting Algorithms
o Stacks, Queues And Linked List
o Exercise
Data Structure:
In Computer Science, a data structure is a particular way of storing and organizing
data in a computer so that it can be used efficiently. Different kinds of data
structures are suited to different kinds of applications, and some are highly
specialized to specific tasks. For example, Stacks are used in function call during
execution of a program, while B-trees are particularly well-suited for
implementation of databases. The data structure can be classified into following
two types:
Simple Data Structure: These data structures are normally built from primitive
data types like integers, floats, characters. For example arrays and structure.
Array:
Array is a collection of elements of similar data type stored in continuous memory
location under a single name.
Declaration of array:
Syntax:-
111
A complete energized Study material of Computer Science for Class XII
The statement written above will create an array namely arr having 10 integer
elements. To differentiate array elements index value is used. Index value is an
integer value that starts from 0 and moves upto N-1, where N is total number of
elements in the array. For example if we have an array of 10 elements then the
index value will be from 0 to 9
void main()
{
int arr[10],i;
cout<<‖enter the elements in array‖<<endl;
for(i=0;i<10;i++)
{
cin>>arr[i];
}
cout<<‖The Array elements are‖<<endl;
for(i=0;i<10;i++)
{
cout<<arr[i]<<endl;
}
}
#include<iostream.h>
#include<conio.h>
void main()
{
112
A complete energized Study material of Computer Science for Class XII
int lsearch(int[],int,int);
int a[50],item,n,index;
clrscr();
cout<<"\n Enter size of array";
cin>>n;
cout<<"\n Enter array elements";
for(int i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"Enter the item to be searched";
cin>>item;
index=lsearch(a,n,item);
if(index= = -1)
cout<<"\n Element not found";
else
cout<<"\n Element found at position "<<index+1;
getch();
}
113
A complete energized Study material of Computer Science for Class XII
less than the middle item then the item is present in first half segment of the array
(i.e. between 0 to middle-1), so the next iteration will continue for first half only, if
the item is larger than the middle element then the item is present in second half of
the array (i.e. between middle+1 to size-1), so the next iteration will continue for
second half segment of the array only. The same process continues until either the
item is found (search successful) or the segment is reduced to the single element
and still the item is not found (search unsuccessful).
#include<iostream.h>
#include<conio.h>
void main()
{
int bsearch(int[],int,int);
int a[50], item, n, index;
clrscr();
cout<<"\n Enter total elements";
cin>>n;
cout<<"\n Enter array elements in sorted form:";
for(int i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"Enter the item to be searched";
cin>>item;
index=bsearch(a, n, item);
if(index= = -1)
cout<<"\n Element not found";
else
cout<<"\n Element found at position "<<index+1;
getch();
}
114
A complete energized Study material of Computer Science for Class XII
mid=(beg+last)/2;
if(item= =a[mid])
{
return mid;
found=1;
break‘
}
else if(item>a[mid])
beg=mid+1;
else
last=mid-1;
}
If(found==0)
return -1;
}
#include<iostream.h>
#include<conio.h>
void bubblesort (int[],int);
void main()
{
int a[50],n;
clrscr();
cout<<"\nHow many elements do you want to create array with? ";
cin>>n;
cout<<"\nEnter array elements\n";
for(int i=0;i<n;i++)
cin>>a[i];
bubblesort(a,n);
cout<<"\n\nThe sorted array is as shown below\n";
for(i=0;i<n;i++)
cout<<a[i]<<"\n";
getch();
}
115
A complete energized Study material of Computer Science for Class XII
{
int temp;
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-i-1;j++)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
Q1. Write a function in C++ which accepts an integer array and its size as
arguments/parameters and reverses the array example : if the array is
1,2,3,4,5 then rearrange the array as 5,4,3,2,1
Ans :
void reverse(int arr[ ], int n)
{
int temp;
for(int i=0,j=n-1; i<=j; i++,j--)
{
temp= arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Q2. Write a function in C++ which accepts an integer array and its size as
arguments/parameters and exchange the array in the given manner
example : if the array is 1,2,3,4,5,6,7,8,9,10 then rearrange the array
as2,1,4,3,6,5,8,7,10,9
Ans :
void change(int arr[ ], int n)
{
int temp;
116
A complete energized Study material of Computer Science for Class XII
Q3 Write a function in C++ to merge the contents of two sorted arrays A & B
into third array C. Assuming array A is sorted in ascending order, B is sorted
in descending order, the resultant array is required to be in ascending order.
Ans:
void MERGE(int A[ ], int B[ ], int C[ ], int M, int N, int &K)
{
int I,J, K;
for(I=0, J=N – 1, K=0; I<M && J>=0;)
{
if (A[I]<=B[J])
C[K++]=A[I++];
else
C[K++]=B[J--];
}
for (int T=I;T<M;T++)
C[K++]=A[T];
for (T=J;T>=0;T--)
C[K++]=B[T];
}
int arr[5][3];
In the example given above a two dimensional array is declared with the name arr
where there are 5 rows and three columns i.e total 15 (5 x 3) elements
117
A complete energized Study material of Computer Science for Class XII
Program for entering and displaying data(in matrix form) in two dimensional
array
void main()
{
int arr[5][3],I,j;
cout<<‖Enter array elements ―<<endl;
for(i=0;i<5;i++)
{
for(j=0;j<3;j++)
{
cin>>arr[i][j];
}
}
cout<<‖the array elements are‖<<endl;
for(i=0;i<5;i++)
{
for(j=0;j<3;j++)
{
cout<<arr[i][j]<<‖\t‖;
}
cout<<endl;
}
getch();
}
Q1. Write a function in C++ that will accept a two D array and its row and
column size as argument and find sum of rows and columns
Ans :
void rowcolsum(int A[ ][ ],int N, int M)
{
for (int i=0;i<N;i++)
{
int SumR=0;
for (int j=0;j<M;j++)
SumR+=A[i][j];
cout<<SumR<<endl;
}
for (int i=0;i<N;i++)
{
118
A complete energized Study material of Computer Science for Class XII
int SumC=0;
for (int j=0;j<M;j++)
SumC+=A[j][i];
cout<<SumC<<endl;
}
}
Q2. Write a function in C++ to find the sum of both left and right diagonal
elements from a two dimensional array (matrix).
Ans :
void DiagSum(int A[ ][ ], int N)
{
int SumD1=0,SumD2=0;
for (int I=0;I<N;I++)
{
SumD1+=A[I][I];
SumD2+=A[N-I-1][I];
}
cout<<‖Sum of Diagonal 1:‖<<SumD1<<endl;
cout<<‖Sum of Diagonal 2:‖<<SumD2<<endl;
}
In Row Major Order the elements are shown Row Wise where as in Column Major
Order the array elements are shown Column wise e,g
1,2,3,4,5,6,7,8,9
119
A complete energized Study material of Computer Science for Class XII
1,4,7,2,5,8,3,6,9
To find the address of a particular row and column the formula in Row Major
Order is
Where
B= Base address of the array
w= Word size
n= total no of columns in the array
To find the address of a particular row and column the formula in Column Major
Order is
Where
B= Base address of the array
w= Word size
n= total no of rows in the array
Q1. An array x[30][10] is stored in the memory with each element requiring 4
bytes of storage. If the base address of x is 4500, find out memory locations of
x[12][8] if the content is stored along the row.
Ans:
Here the array is stored in Row Major Order so
B=4500
W= 4
N= 10
As per the formula
Address of A[row][column]=B +w*(n(row)+column)
=4500+4*(10(12)+8)
=4500+4*(128)
=4500+512
=5012
Q2. An array x[30][10] is stored in the memory with each element requiring 4
bytes of storage. If the base address of x is 4500, find out memory locations of
x[12][8] if the content is stored along the row.
Ans:
120
A complete energized Study material of Computer Science for Class XII
Q 3. An array P[20][30] is stored in the memory along the column with each of
the element occupying 4 bytes, find out the Base Address of the array, if an
element P[2][20] is stored at the memory location 5000.
Ans :
Given, W=4, N=20, M=30, Loc(P[2][20])=5000
Column Major Formula:
Loc(P[I][J]) =Base(P)+W*(N*J+I)
Loc(P[2][20]) =Base(P)+4*(20*20+2)
Base(P) =5000 – 4*(400+2)
=5000 – 1608
=3392
1. Push
2. Pop
121
A complete energized Study material of Computer Science for Class XII
void main()
{
stack s1;
s1.push(3);
s1.push(5);
cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl;
cout<<s1.pop();
}
122
A complete energized Study material of Computer Science for Class XII
Queue
In computer science, a Queue is a First in, First out (FIFO) data structure. It simply
means that an element that is inserted at the beginning will be deleted first. To
Manage a queue all the insertion and deletion takes place from two different
positions called ―front‖ and ―rear‖. Every element is inserted from the rear position
and deleted from the front position in the queue.
int deletion()
{
if (front= =-1)
{
cout<<‖queue is empty ―;
return -1;
}
else
return a[front++];
}
};
123
A complete energized Study material of Computer Science for Class XII
void main()
{
queue q1;
q1.insert(3);
q1.insert(5);
cout<<q1.deletion()<<endl;
cout<<q1.deletion()<<endl;
}
Linked List
A linked list is a data structure consisting of a group of nodes which together
represent a sequence. Under the simplest form, each node is composed of a data
and a reference (in other words, a link) to the next node in the sequence; more
complex variants add additional links. This structure allows for efficient insertion
or removal of elements from any position in the sequence.
Here in the figure is an example of a linked list whose nodes contain two fields: an
integer value and a link to the next node. The last node is linked to a terminator
used to signify the end of the list. Linked lists are among the simplest and most
common data structures. They can be used to implement several other common
abstract data types, stacks, queues etc though it is not uncommon to implement the
other data structures directly without using a list as the basis of implementation.
The principal benefit of a linked list over an array is that the list elements can
easily be inserted or removed without reallocation or reorganization of the entire
structure because the data items need not be stored contiguously in memory or on
disk. Linked lists allow insertion and removal of nodes at any point in the list, and
can do so with a constant number of operations if the link previous to the link
being added or removed is maintained during list traversal. Linked list are dynamic
structure where memory allocation takes place at run time.
124
A complete energized Study material of Computer Science for Class XII
125
A complete energized Study material of Computer Science for Class XII
{
start=NULL;
}
void insert_at_beg();
void insert_at_mid();
void insert_at_end();
int remove();
void display();
};
void linked :: insert_at_end()
{
node *temp;
if(start==NULL)
{
start=new node [1];
start->p=NULL;
cout<<"\n Enter Data to insert \n";
cin>>start->d;
}
else
{
temp=start;
while(temp->p!=NULL)
temp=temp->p;
temp->p= new node [1];
temp=temp->p;
cout<<"\n Enter Data to insert \n";
cin>>temp->d;
temp->p=NULL;
}
}
126
A complete energized Study material of Computer Science for Class XII
next=temp->p;
temp->p=new node [1];
temp=temp->p;
temp->p=next;
cout<<"\n Enter data to insert \n";
cin>>temp->d;
}
127
A complete energized Study material of Computer Science for Class XII
128
A complete energized Study material of Computer Science for Class XII
break;
case 2:
l.insert_at_mid();
break;
case 3:
l.insert_at_end();
break;
case 4:
l.remove();
break;
case 5:
l.display();
break;
case 6:
n=1;
break;
default :
cout<<"\n Invalid Entry \n";
break;
}
}while(n!=1);
return 0;
}
Implementation of stacks using a linked list
The stack which is implemented using linked list is called linked stack or dynamic
stack
#include<iostream.h>
#include<conio.h>
struct node
{
int data;
node * next;
};
class stack
{
node *top;
public:
stack()
{
129
A complete energized Study material of Computer Science for Class XII
top=NULL;
}
void stackpush();
void stackpop();
void displaystack();
};
void stack::stackpush()
{
node *ptr;
ptr=new node;
cout<<"Enter the element to be pushed"<<endl;
cin>>ptr->data;
if(top==NULL)
ptr->next=NULL;
else
ptr->next=top;
top=ptr;
}
130
A complete energized Study material of Computer Science for Class XII
void main()
{
clrscr();
char ans;
stack s1;
do
{
s1.stackpush();
cout<<"wish to continue "<<endl;
cin>>ans;
}while(ans=='y');
s1.displaystack();
cout<<"Press any key to pop an element"<<endl;
getch();
s1.stackpop();
getch();
}
#include<iostream.h>
#include<conio.h>
struct node
{
int data;
node * next;
};
class queue
{
node *front,*rear;
public:
queue()
{
rear=front=NULL;
}
void insqueue();
131
A complete energized Study material of Computer Science for Class XII
void delqueue();
void dispqueue();
};
void queue::insqueue()
{
node *ptr;
ptr=new node;
cout<<"Enter the element to be insert"<<endl;
cin>>ptr->data;
ptr->next=NULL;
if(rear==NULL)
front=rear=ptr;
else
{
rear->next=ptr;
rear=ptr;
}
}
132
A complete energized Study material of Computer Science for Class XII
ptr=ptr->next;
}
}
void main()
{
clrscr();
char ans;
queue q1;
do
{
q1.insqueue();
cout<<"wish to continue "<<endl;
cin>>ans;
}while(ans=='y');
q1.dispqueue();
cout<<"Press any key to delete an element ...."<<endl;
getch();
q1.delqueue();
getch();
}
Exercise
Q1. Write a function in C++ to delete a node containing customer‟s
information, from a dynamically allocated Queue of Customers implemented
with the help of the following structure:
struct Customer
{
int CNo;
char CName[20];
Customer *Link;
};
Ans:
struct Customer
{
int CNo;
char CName[20];
Customer *Link;
} *Front, *Rear, *ptr;
133
A complete energized Study material of Computer Science for Class XII
void DELETE()
{
if(Front = = NULL)
cout<<‖\n Queue Underflow\n‖;
else
{
ptr = Front;
Front = Front®Link;
delete ptr;
}
}
struct Book
{
int BNo;
char BName[20];
Book *Next;
};
Ans:
struct Book
{
int BNo;
char BName[20];
Book *Next;
}*Front, *Rear, *ptr;
void POP()
{
if(Front = = NULL)
cout<<‖\n Stack Underflow\n‖;
else
{
ptr = Front;
Front = Front®Link;
delete ptr;
}
}
134
A complete energized Study material of Computer Science for Class XII
Unit 4
DATABASES MANAGEMENT SYSTEM AND SQL
Objectives:
In this Chapter you will learn about:
o Basic database concepts
o Key Constraints
o Syntax of some SQL commands
Introduction:
Database is a collection of related information that is organized in such a way that
supports for easy access, modify and maintain data. The contents of a database are
obtained by combining data from all the different sources in an organization.
Generally, the database is managed by some special software packages known
as Database Management Systems (DBMSs). DBMSs are specially designed
applications to create connection between user and program, and to store data in an
organized manner. The purpose of DBMSs software is to allow the user to create,
modify and administration of database. Examples of database management systems
are:
Ms-Access, MySQL, PostgreSQL, SQLite, Microsoft SQL Server, Oracle, SAP,
dBASE, FoxPro, etc.
Relation:
In database, a relation means a 'table', in which data are organized in the form of
rows and columns. Therefore in database, relations are equivalent to tables.
For example
Relation: Student
135
A complete energized Study material of Computer Science for Class XII
Domain:
A domain is the original sets of atomic values used to model data. In data base
management and database, a domain refers to all the possible unique values of a
particular column.
For example:
1. The domain of gender column has a set of two possible values i.e, Male or
Female.
2. The domain of marital status has a set of four possible values i.e, Married,
Unmarried, Widows and Divorced.
136
A complete energized Study material of Computer Science for Class XII
Database: Collection of logically related data along with its description is termed
as database.
Example:
Relation: Student
KEYS:
Keys are an important part of a relational database and a vital part of the structure
of a table. They help enforce integrity and help identify the relationship between
tables. There are three main types of keys - candidate keys, primary keys, foreign
keys and alternate keys.
137
A complete energized Study material of Computer Science for Class XII
Primary Key: Primary key is a key that can uniquely identifies the records/tuples
in a relation. This key can never be duplicated and NULL.
Foreign Key: Foreign Key is a key that is defined as a primary key in some other
relation. This key is used to enforce referential integrity in RDBMS.
Candidate Key: Set of all attributes which can serve as a primary key in a relation.
Alternate Key: All the candidate keys other than the primary keys of a relation are
alternate keys for a relation.
Select Operation: The select operation selects tuples from a relation which satisfy
a given condition. It is denoted by lowercase Greek Letter σ (sigma).
Project Operation: The project operation selects columns from a relation which
satisfy a given condition. It is denoted by lowercase Greek Letter π (pi). It can be
thought of as picking a sub set of all available columns.
Characteristics of SQL
3. View Definition:
DDL contains set of command to create a view of a relation.
e.g : create view
Operators in SQL:
The following are the commonly used operators in SQL
1. Arithmetic Operators +, -, *, /
2. Relational Operators =, <, >, <=, >=, <>
3. Logical Operators OR, AND, NOT
139
A complete energized Study material of Computer Science for Class XII
5. LONG
6. RAW/LONG RAW
Constraints:
Constraints are the conditions that can be enforced on the attributes of a relation.
The constraints come in play whenever we try to insert, delete or update a record in
a relation. Not null ensures that we cannot leave a column as null. That is a value
has to be supplied for that column.
Unique constraint means that the values under that column are always unique.
Primary key constraint means that a column can not have duplicate values and not
even a null value.
The main difference between unique and primary key constraint is that a column
specified as unique may have null value but primary key constraint does not allow
null values in the column.
Foreign key is used to enforce referential integrity and is declared as a primary key
in some other table.
it declares cust_id column as a foreign key that refers to cust_id field of table
master. That means we cannot insert that value in cust_id filed whose
corresponding value is not present in cust_id field of master table.
Check constraint limits the values that can be inserted into a column of a table.
The above statement declares marks to be of type number and while inserting or
updating the value in marks it is ensured that its value is always greater than or
equal to zero.
140
A complete energized Study material of Computer Science for Class XII
141
A complete energized Study material of Computer Science for Class XII
Name
Ajaz
Farooq
Sajad
e.g. SELECT Roll_no, name FROM student WHERE Roll_no BETWENN 100
AND 103;
The above command displays Roll_no and name of those students whose Roll_no
lies in the range 100 to 103 (both 100 and 103 are included in the range).
142
A complete energized Study material of Computer Science for Class XII
The above command displays all those records whose city is either
‗Srinagar‘,‘Sopore‘,‘Baramullah‘
SQL provides two wild card characters that are used while comparing the strings
with LIKE operator.
e.g SELECT Roll_no, name, city FROM student WHERE Roll_no LIKE ―%3‖;
displays those records where last digit of Roll_no is 3 and may have any number of
characters in front.
e.g SELECT Roll_no, name, city FROM student WHERE Roll_no LIKE ―1_3‖;
displays those records whose Roll_no starts with 1 and second letter may be any
letter but ends with digit 3.
ORDER BY Clause
ORDER BY clause is used to display the result of a query in a specific order(sorted
order). The sorting can be done in ascending or in descending order. It should be
kept in mind that the actual data in the database is not sorted but only the results of
the query are displayed in sorted order.
143
A complete energized Study material of Computer Science for Class XII
The above query returns name and city columns of table student sorted by name in
increasing/ascending order.
It displays all the records of table student ordered by city in descending order.
Note:- If order is not specifies that by default the sorting will be performed in
ascending order.
GROUP BY Clause
The GROUP BY clause can be used in a SELECT statement to collect data across
multiple records and group the results by one or more columns.
Aggregate Function:
aggregate_function can be a function such as SUM, COUNT, MAX, MIN, AVG
etc.
144
A complete energized Study material of Computer Science for Class XII
Syntax:
Example :
Enter a new record in student table
Syntax:
DELETE FROM <table-name>
WHERE <condition>;
Example:
Delete all the records of employee whose salary is less than 3000
DELET FROM<table-name>;
145
A complete energized Study material of Computer Science for Class XII
The UPDATE command is used to changes some values in existing rows. The
UPDATE command specifies the rows to be changed using the WHERE clause,
and new data using the SET keyword.
Example:
Update the salary of employee to 5000 whose employee code is 1011.
UPDATE emp
SET sal=5000
WHERE empno=1011;
Example:
To modify column job of table emp to have new width of 30 character
Practice work:
Consider the following partial relation EMP. Let us create some sub-queries for
them.
146
A complete energized Study material of Computer Science for Class XII
OUTPUT:
ENAME JOB SAL
Nirmal MANAGER 2975
Example 2: Display the employees whose job title is the same as that of employee
7566 and salary is more than the salary of employee 7788
OUTPUT:
ENAME JOB
Ashwini MANAGER
DEPTNO SAL
10 2975
Example 20 3000 4: Find the name, department no and
salary of employees drawing minimum salary in that department.
Example:
Table: Student
148
A complete energized Study material of Computer Science for Class XII
Relational Operator (< less than , > greater than < = less than or equal to,> = greater
than or equal to, = equal to, ! = not equal to)
Example 6: Display students' name, who are paying below 3000 fees.
SELECT name
FROM student
WHERE fees<3000;
Output:
Example 7: Display students' name, who are paying above or equal to 3000 fees.
SELECT name
FROM student
WHERE fees>=3000;
Output:
149
A complete energized Study material of Computer Science for Class XII
Example 11: Display students' information, who are not in 10th class.
SELECT *
FROM student
WHERE NOT class = 10;
Output:
150
A complete energized Study material of Computer Science for Class XII
Unit 5
Boolean Algebra
Objectives:
In this Chapter you will learn about:
o Boolean Algebra & Theorems
o Basic Logic Gates
o Canonical and Standard Forms (SOP & POS)
BOOLEAN ALGEBRA:
Boolean Algebra was introduced by George Boole in 1854. He was an English
mathematician, who primarily worked on differential equations and the calculus of
variations. But the work for which he is best known is - application of algebraic
systems to non-mathematical reasoning. He proposed that logical propositions
should be expressed as algebraic equations, so now logic was reduced to algebra.
In his logical deductions he replaced the operation of multiplication by AND, and
addition by OR. However, it is Claude Shannon, whose work on using Boolean
Algebra to design Switching Circuits in late 1930s, became the foundation of
computer Logic and Design. As Boolean logic allows things to be mapped into bits
and bytes, it has application in telephone switching circuits, electronics, computers
(both hardware and software), etc.
Boolean Algebra, which is algebra of two values may be (True, False) or (Yes, No)
or (0, 1), is an important tool in analyzing, designing and implementing digital
circuits.
Distributive: law states that, ORing variables and then ANDing the result with
single variable is equivalent to ANDing the result with a single variable with each
of the several variables and then ORing the products. Vice versa with respect to
operators and terms is also true.
A . ( B + C ) = A . B + A . C and A + ( B . C ) = ( A + B ) . ( A + C )
Indempotency: states that when we sum or product a boolaen quantity to itself, the
resultant is original quantity.
A + A = A and A . A = A
152
A complete energized Study material of Computer Science for Class XII
Null Element: No matter what the value of Boolean variable, the sum of variable
and 1 will always be 1. Also the product of Boolean variable and 0 will always be
0.
A + 1 = 1 and A . 0 = 0
Associative: this property tells us that we can associate, group of sum or product
variables together with parenthesis without altering the truth of the expression
A + ( B + C ) = ( A + B ) + C and A . ( B . C ) = ( A . B) . C
De Morgan's Theorem: states that the complement of a sum / product, equals the
product / sum of the complements.
( A + B ) ' = A' . B' and ( A . B )' = A' + B'
Apart from these axioms and theorems, there is a principle. Duality Principle
which states that starting with Boolean relation, you can device another Boolean
relation by
1. Changing each OR operation to AND
2. Changing each AND operation to OR
3. Complementing the identity (0 or 1) elements.
For example dual of relation
A + 1 = 1 is A . 0 = 0.
You must have noticed that second part of axioms and theorems is actually the
result of this principle only. Practical consequence of this theorem is, it is sufficient
to prove half the theorem, the other half comes gratis from the principle.
2. Logical subtraction and logical division are not available in Boolean algebra,
as there is no additive or multiplicative inverse available.
3. Complement is available in Boolean algebra
4. Two valued Boolean algebra contains 0 & 1 only.
154
A complete energized Study material of Computer Science for Class XII
Since the table is for one variable there will be only two rows 2 1 = 2 rows. For two
variables - a & b, the table will have 4 rows (22 = 4 ), listed below
a b
0 0
0 1
1 0
1 1
a b c
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
155
A complete energized Study material of Computer Science for Class XII
and so on. The trick for filling the table is, starting from right most column of the
table - 1st column will be combination of 0,1,0,1,…… (20 zeros and then same
number of 1s. In 2nd column it will be 0,0,1,1,0,0,….. 2 1 zeros and then same
number of ones. In 3rd column 0,0,0,0,1,1,1,1,0,0, …… (22 number of zeros and
ones), and so on.
Now let's use one variable table, to represent a simple boolean function f (a) = a'
a F(a)
0 1
1 0
Second column of table gives the value of Boolean function i.e. a'. This table tells
that if a is true, a' will be false and vice versa, as is evident from 2nd column of
table.
Truth table for the boolean function applied on two variables with all basic
Boolean operators i.e. AND, OR will be
a b F=a.b F=a+b
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
Now let's represent some more functions written earlier in algebraic form using
truth table:
F2 (x,y,z) = xyz'
156
A complete energized Study material of Computer Science for Class XII
From our earlier explanation we know that F will be one for x = 1, y = 1 and
z = 0.2
f3 (a, b, c) = (a+b).c
For now let's move on to proving the various theorems of Boolean algebra:
Theorems can be proved in two ways:
Associative:
Theorem states that A + (B+C) = (A+B) + C and A.(B.C) = (A.B).C
Let's algebraically prove it:
Let X = [A + (B + C)] [(A + B) + C]
157
A complete energized Study material of Computer Science for Class XII
then
X = [(A + B) + C] A + [(A + B) + C] (B + C)
= [(A + B) A + C . A] + [(A + B) + C] (B + C)
= A + [ (A + B) + C] (B + C)
= A + [(A + B) + C] B + [(A + B) + C] C
= A + (B + C)
But also
X = (A + B) [A + (B + C)] + C [A + (B + C)]
= (A + B) [A + (B + C)] + C
= A [A + (B + C)] + B [A + (B + C)] + C
= (A + B) + C
Thus A + (B + C) = (A + B) + C
We know, second form of the theorem will also be true. (Duality Principle)
159
A complete energized Study material of Computer Science for Class XII
Absorption Law:
i) A + AB = A and A . (A + B) = A
Algebraic method:
Taking LHS
A + AB = (A.1) + (A.B) by Identity
= A. (1+B) by Distribution
= A.1 by Null Element
=A
Using Duality, we know that A.(A+B) = A is also true
160
A complete energized Study material of Computer Science for Class XII
iii) ((A+B).(A'+C). (B+C)) = (A+B). (A'+C) AND ((A.B) + (A'.C) + (B.C)) = A.B + A'.C
Taking LHS
= (A+B).(A'+C). (B+C)
= (A+B).(A'+C). (B+C). (B+C) by Idempotency
= (A+B).(B+C).(A'+C). (B+C) by Commuting
= (B+A).(B+C).( C+A'). (C+B) by Commuting
= (B+A.C) . ( C+ A'B ) by Distributive
= (B+AC).C + (B+AC). A'B by Distribution
= B.C + A.C.C + B. A.'.B + A.C.A'B by Distribution
= B.C + A.(C.C) + (B.B). A'+ C. (A. A').B by Associativity and Idempotency
= B.C + A.C + B.A'+ 0 by Complement and Idempotency
= (B+A).C + B.A'+ A. A' by Complement and Distributive
= (B+A).C + (B+A).A' by Distributive
= (B+A).(C + A') by Distributive
= (A+B). (A'+C) by Commuting
Using Duality Principle we can say that A.B + A'+C + B. C = A. B. A'.C is also
true
161
A complete energized Study material of Computer Science for Class XII
De Morgan's Theorem:
States that (A+B)' = A'.B' and (A.B)' = A' + B'
Algebraic method:
Assuming that DeMorgan's theorem is true, then through this we can find
complement of a function/expression.
So by showing that
i) (A+B) + A'.B' = 1
ii) (A+B). (A'.B') = 0
Logic Gates:
A gate is simply an electronic circuit, which operates on one or more signals to
produce an output signal. Gates are digital circuits because the input and output
signals are either low (0) or high (1). Gates also called logic circuits.
This logic circuit diagram can be composed of basic gates AND, OR and NOT or
advance gates, NAND and NOR, etc.
Logic circuits that perform logical operations such as AND, OR and NOT are
called gates. A gate is block of hardware that produces a logic 0 or a logic 1 output,
in response to the binary signal(s) applied to it as input.
163
A complete energized Study material of Computer Science for Class XII
164
A complete energized Study material of Computer Science for Class XII
Similarly if we combine them using OR operator, again there are four possible
ways viz. a+b, a'+b, a+b', a'+b'
For now we will concentrate on the terms formed using AND operator only. Each
of them is called a minterm or Standard Product Term. A minterm, is obtained
from AND term, with each variable being complemented, if the corresponding bit
of binary number (in the truth table) is 0 and normal (i.e. non complemented) if the
bit is 1. These terms are designated using m.
165
A complete energized Study material of Computer Science for Class XII
We already have maxterms for 2 variables, maxterms for 3 variables will be:
Maxterm for four variables can be obtained in similar manner and they are
designated as M0 to M15 . If we put both maxterms and minterms together, we will
have following table
By now you might have noted that each maxterm is complement of its
corresponding minterm. For n variables, there will be 2n, minterms (i.e. Standard
Product Term) denoted as mi, 0 < i < 2n - 1, and 2n i maxterms (i.e. Standard Sum
Term), their complement, denoted as M, 0 < i < 2n - 1.
Now let's use this information for algebraic representation of boolean function
from the truth table. This is done by forwarding a minterm for each combination of
variables which produces a 1 in the function, and then by ORing these minterms.
For e,g.
166
A complete energized Study material of Computer Science for Class XII
Since a'b'c, ab'c', abc' and abc minterms are resulting into 1, in function (F1 )
column, so algebraic representation of the function F1 will be
This is a boolean expression, expressed as sum of minterms and , will give value 1.
This form of expression is known as Sum of Products or SOP expression. F1 in
SOP form can also be represented as
i) m1 + m4 + m6 +m7
Instead of using Product terms, we can just mention the minterm designation.
ii) ∑ (1, 4, 6, 7)
This one is mathematical representation of the above expression.
Let's take some more examples:
167
A complete energized Study material of Computer Science for Class XII
What if we have to represent the function in complement form i.e. for its value 0.
Simple, we will OR the
minterms, from the truth table, for which function value is 0. So we have,
F1' = x'y'z' + x'yz' + x'yz + xy'z (the remaining minterms)
On evaluating it for complement, we get
What we get is the Products of Sum form (POS) of the function F1.
POS form of the expression gives value 0, and we work on the complements. POS
is formed by ANDing maxterms.
POS also can be represented in many ways. One way we have seen, others are
i) F1 = M0 .M2 .M3 .M5
168
A complete energized Study material of Computer Science for Class XII
Expressions which were written till now, are in Canonical form. In this form, every
term of the function should have all the literals. When, minterms or maxterms from
truth table, are used for representation, the function is in canonical form only, as
terms contains all variables (may be in any form). Since we can use either
minterms or maxterms to form expression, we can have Canonical SOP expression
or Canonical POS expressions.
Till now, we were given truth table and we were representing Boolean Function in
algebraic form. Vice versa of it, i.e. for a given Boolean function in algebraic
representation, we can represent it in Truth table.
What we have worked on was Canonical Boolean functions. There is another form
of representation, also - both for SOP & POS. It is known as reduced / simplified
form.
169
A complete energized Study material of Computer Science for Class XII
Simplified expressions are usually more efficient and effective when implemented
in practice. Also simpler expressions are easier to understand, and less prone to
errors. So the Canonical expressions are simplified/minimized to obtain a reduced
expression (Standard form).
Minimization of Gates:
Boolean function may be reduced in many ways, but we will be taking up the
following two ways of reduction in this course.
1. Algebraic Manipulations
2. Karnaugh Map.
Example 2:
F (a, b) = ab+ ab'+ a'b
= a(b+b') + a'b by Distribution
= a.1 + a'b by complement
= a + a'b by Identity
= a+b by absorption
170
A complete energized Study material of Computer Science for Class XII
1. Drawing K-map:
171
A complete energized Study material of Computer Science for Class XII
The cells of the map are marked by the minterms as explained in first map. For e,g.
If you look at the square assigned m (minterm), it corresponds to binary no. 0100
of the truth table.
Now to understand, why the squares have been marked, as they are?
If you look at any two adjacent cell in the map, they differ only by one variable,
which is normal in one cell and complemented in other or vice-versa. For eg. From
m to m only a changes its state from complemented to normal. And we know,
using Boolean axiom (a'+a=1) that we can eliminate the variable from the resultant
reduced term.
2. Cells which are grouped, should be adjacent cells, i.e. horizontal or vertical,
not diagonal.
172
A complete energized Study material of Computer Science for Class XII
6. Groups may wrap around the table. The left most cell(s) in a row may be
grouped with right most cell(s), and the top cell(s) in a column may be
grouped with the bottom cells(s). Cells in corners of the map are also
adjacent, for that purpose.
7. There should be as few groups as possible, as long as this does not contradict
any of the previous rule. Once the grouping is done, last step is.
173
A complete energized Study material of Computer Science for Class XII
What we have to do is, find the variable(s) listed on top and / or side, which are the
same for entire group and ignore variable(s) which are not same in the group.
Using the above strategy, write the result. Let‘s look at some examples
Step 3: Grouping
174
A complete energized Study material of Computer Science for Class XII
Exercise
Q1: Reduce the following Boolean Expression using K-Map:
F( A, B, C, D ) = p ( 0, 3, 5, 6, 7, 8, 11, 15 )
Ans:
There are 1 quad and 3 pairs after eliminating the redundant groups.
Quad (M3, M7, M11, M15) reduces to C' + D'
Pair ( M5, M7) reduces to A + B ' + D'
Pair ( M6, M7) reduces to A + B ' + C'
Pair ( M0, M8) reduces to B + C + D
Q2. Write the equivalent Boolean Expression for the following Logic Circuit
Ans: F(P,Q)=(P'+Q).(P+Q')
Q3. Write the equivalent Boolean Expression F for the following circuit diagram:
175
A complete energized Study material of Computer Science for Class XII
Ans: A‘B+AB+AB‘
Q4. Convert the following Boolean expression into its equivalent Canonical Sum
of Product Form((SOP)
(X‘+Y+Z‘).(X‘+Y+Z).(X‘+Y‘+Z).(X‘+Y‘+Z‘)
Ans: F(X, Y, Z) =π(4 , 5 , 6 , 7)
=Σ(0, 1 , 2 , 3)
= X‘. Y‘. Z‘ + X‘. Y‘. Z + X‘. Y. Z‘ + X‘. Y. Z
Q5. Draw a Logical Circuit Diagram for the following Boolean expression:
A.(B+C‘)
Ans:
176
A complete energized Study material of Computer Science for Class XII
Unit 6
COMMUNICATION & OPEN SOURCES CONCEPTS
Objectives:
In this Chapter you will learn about:
o Switching Techniques
o Data Communication Terminologies
o Transmission Media
o Network Security Concepts
o Web Servers
o Open Source Terminologies
Communication:
Communication means to convey. In today's fast changing world, data needs to be
transferred efficiently, frequently and speedily. To move data at a fast speed and
that too with minimum data loss, networking plays an important role. Computer
networks have made a major impact on the society as a whole. As we are moving
ahead in the 21st century, the world seems to be converging. The merging of
computers and communication technology has changed the very perspective of
communication today. It has had a profound influence on the way the computer
systems are organized and used today. The old model of a single computer serving
all of the organization's computational needs has been replaced by one in which
large number of separate but interconnected computers do the same job. These
systems together form a computer network.
Network:
We often need peripheral devices and data to be shared among various computers.
In fact, in your school's computer lab, you must have seen one printer which is
connected to only one computer, serving to the needs of all the computers in the
lab. How does this happen? This happens because all your lab's computers and
peripherals are forming a network. They are interconnected with each other
enabling you to send and receive data from one computer to another. Hence it can
be said that two computers are interconnected if they are able to exchange
information.
collection of two or more computers linked together for the purpose of sharing
information and resources. When these computers are joined in a network, people
can share files and peripherals such as modems, printers, backup drives, or CD-
ROM drives. Each computer on the network is called a node and hence, a network
is a series of points or nodes interconnected by communication paths (transmission
media). A network can be as small and simple as two computers that share a printer
or as complex as the world's largest network, the Internet. When networks at
multiple locations are connected using services available from phone companies,
people can send e-mail, share links to the global Internet, or conduct video
conferences in real time with other remote users. As companies rely on
applications like electronic mail and database management for core business
operations, computer networking becomes increasingly more important.
Needs:
1. Resource Sharing
2. Reliability
3. Cost Factor
4. Communication Medium
Resource Sharing means to make all programs, data and peripherals available to
anyone on the network irrespective of the physical location of the resources and the
user.
178
A complete energized Study material of Computer Science for Class XII
Reliability means to keep the copy of a file on two or more different machines, so
if one of them is unavailable (due to some hardware crash or any other) them its
other copy can be used.
Cost factor means it greatly reduces the cost since the resources can be shared.
Communication Medium means one can send messages and whatever the
changes at one end are done can be immediately noticed at another.
Evolution Of Networking:
Networking started way back in 1969 with the development of the first network
called the ARPANET. The U.S. department of defense sponsored a project named
ARPANET (Advanced Research Projects Agency Network) whose goal was to
connect computers at different universities and U.S. defense. Soon engineers,
scientists, students and researchers who were part of this system began exchanging
data and messages on it. Gradually they could play long distance games and also
socialize with people. Hence ARPANET expanded rapidly. In mid 80s, the
National Science Foundation created a new high capacity network called NSFnet
which allowed only academic research on its network. So many private companies
built their own networks, which were later interconnected along with ARPANET
and NSFnet to form Internet - a network formed by linking two or more networks.
Diagrammatic presentation
179
A complete energized Study material of Computer Science for Class XII
Internet:
The Internet is a system of linked networks that are worldwide in scope and
facilitate data communication services such as remote login, file transfer, electronic
mail, the World Wide Web and newsgroups. The internet is made up of many
networks each run by a different companies and are interconnected at peering
points. It is really a network of networks spread across the globe, all of which are
connected to each other. This super network is a glorified WAN in many respects.
It connects many smaller networks together and allows all the computers to
exchange information with each other through a common set of rules for
communication. These rules are called protocols and the internet uses
Transmission Control Protocol/Internet Protocol (TCP/IP). Programs such as web
browsers, File Transfer Protocol (FTP) clients, and email clients are some of the
most common ways through which the users work on the Internet. With the
meteoric rise in demand for connectivity, the Internet has become a
communications highway for millions of users. The Internet was initially restricted
to military and academic institutions, but now it is a full-fledged conduit for any
and all forms of information and commerce. Internet websites now provide
personal, educational, political and economic resources to every corner of the
planet.
Inter Space:
It is a client/server software program that allows multiple users to communicate
online with real time audio, video and text chat in dynamic 3D environments. It
provides the most advanced form of communication technology available today. It
is a vision of what internet will become tomorrow. The users will be able to
communicate in multiple ways and from multiple sources instantly.
SWITCHING TECHNIQUES:
Switching techniques are used for transmitting data across networks.
Different types are :
1. Circuit Switching
2. Message Switching
3. Packet Switching
Circuit Switching
o Circuit switching is the transmission technology that has been used
since the first communication networks in the nineteenth century.
o First the complete physical connection between two computers is
established and then the data are transmitted from the source computer
to the destination.
180
A complete energized Study material of Computer Science for Class XII
o When a call is placed the switching equipment within the system seeks
out a physical copper path all the way from the sender to the receiver.
o It is must to setup an end-to-end connection between computers before
any data can be sent.
o The circuit is terminated when the connection is closed.
o In circuit switching, resources remain allocated during the full length
of a communication, after a circuit is established and until the circuit is
terminated and the allocated resources are freed.
Message Switching
o In this the source computer sends data or the message to the switching
circuit which stores the data in its buffer.
o Then using any free link to the switching circuit the data is send to the
switching circuit.
o Entire message is sent to the destination. It reaches through different
intermediate nodes following the ―store and forward‖ approach.
o No dedicated connection is required.
Packet Switching
o Conceived in the 1960's, packet switching is a more recent technology
than circuit switching.
o Packet switching introduces the idea of cutting data i.e. at the source
entire message is broken in smaller pieces called packets which are
transmitted over a network without any resource being allocated.
o Then each packet is transmitted and each packet may follow any rout
available and at destination packets may reach in random order.
o If no data is available at the sender at some point during a
communication, then no packet is transmitted over the network and no
resources are wasted.
o At the destination when all packets are received they are merged to
form the original message.
o In packet switching all the packets of fixed size are stored in main
memory.
Before we proceed with our study of networks, let us learn about some data
communication terminologies being used.
pathway over which data is transferred between remote devices. It may refer to the
entire physical medium, such as a telephone line, optical fibre, coaxial cable or
twisted pair wire, or, it may refer to one of the several carrier frequencies
transmitted simultaneously within the line.
TRANSMISSION MEDIA:
A transmission medium (plural media) is one which carries a signal from one
computer to another. It is also known as communication channel. Transmission
medium can be wired or wireless. We also name them as Guided and Unguided
Media respectively. Wired transmission media includes twisted pair cable, Ethernet
cable, coaxial cable and optical fibre whereas wireless transmission media includes
microwave, radio wave, satellite, infrared, Bluetooth, WIFI etc.
182
A complete energized Study material of Computer Science for Class XII
Types:
o Unshielded Twisted Pair (UTP)
o Shielded Twisted Pair (STP
STP offers greater protection from interference and crosstalk due to shielding.
But it is heavier and costlier than UTP.
USE:
o In local telephone communication
o For digital data transmission over short distances upto 1 km
Advantages:
o Easy to install and maintain
o Simple
o Inexpensive
o Low weight
o Suitable for small (Local) Networks
Disadvantages:
o Not suitable for long distance due to high attenuation.
o Low bandwidth support.
o Low Speed
2. Coaxial cable:
183
A complete energized Study material of Computer Science for Class XII
Advantages:
o Better than twisted wire cable.
o Popular for TV networks.
o Offers higher bandwidth & Speed
Disadvantages:
o Expensive than twisted wires.
o Not compatible with twisted wire cable.
3. Optical Fibres:
o Thin strands of glass or glass like material designed to carry light from
one source to another.
o Source converts (Modulates) the data signal into light using LED
(Light Emitting Diodes) or LASER diodes and send it over the Optical
fiber.
Advantages
o Not affected by any kind of noise.
184
A complete energized Study material of Computer Science for Class XII
Microwaves:
Microwaves are transmitted from the transmitters placed at very high towers to the
receivers at a long distance.
Microwaves are transmitted in line of sight fashion, and also propagated through
the surfaces.
185
A complete energized Study material of Computer Science for Class XII
Advantages:
o Maintenance easy than cables.
o Suitable when cable cannot be used.
Disadvantages:
o Repeaters are required for long distance communication.
o Less Bandwidth available.
Satellite:
Geostationary satellites are placed around 36000 KM away from the earth‘s
surface. In satellite communication transmitting station transmits the signals to the
satellite. (It is called up-linking). After receiving the signals (microwaves) it
amplifies them and transmit back to earth in whole visibility area. Receiving
stations at different places can receive these signals. (It is called down-linking).
Advantage
o Area coverage is too large
Disadvantage
o High investment
Network devices:
For efficient working of any network, many devices are required. Some of the
common network devices are discussed below:
186
A complete energized Study material of Computer Science for Class XII
Modem
o A modem is a computer peripheral that allows you to connect and
communicate with other computers via telephone lines.
o Modem means Modulation/ Demodulation.
o Modulation: A modem changes the digital data from your computer into
analog data, a format that can be carried by telephone lines.
o Demodulation: The modem receiving the call then changes the analog signal
back into digital data that the computer can digest.
o The shift of digital data into analog data and back again, allows two
computers to speak with one another.
RJ- 45 Connector:
RJ-45 is short for Registered Jack-45. It is an eight wire connector which is
commonly used to connect computers on the local area networks i.e., LAN.
187
A complete energized Study material of Computer Science for Class XII
Repeaters:
A repeater is an electronic device that receives a signal and retransmits it at a
higher level or higher power, or onto the other side of an obstruction, so that the
signal can cover longer distances without degradation. In most twisted pair
Ethernet configurations, repeaters are required for cable runs longer than 100
meters.
Hubs:
A hub contains multiple ports. When a packet arrives at one port, it is copied to all
the ports of the hub. When the packets are copied, the destination address in the
frame does not change to a broadcast address. It does this in a rudimentary way, it
simply copies the data to all of the Nodes connected to the hub.
Bridges:
A network bridge connects multiple network segments at the data link layer (layer
2) of the OSI model. Bridges do not promiscuously copy traffic to all ports, as hubs
188
A complete energized Study material of Computer Science for Class XII
do, but learn which MAC addresses are reachable through specific ports. Once the
bridge associates a port and an address, it will send traffic for that address only to
that port. Bridges do send broadcasts to all ports except the one on which the
broadcast was received.
o Bridges learn the association of ports and addresses by examining the source
address of frames that it sees on various ports. Once a frame arrives through
a port, its source address is stored and the bridge assumes that MAC address
is associated with that port. The first time that a previously unknown
destination address is seen, the bridge will forward the frame to all ports
other than the one on which the frame arrived.
o Bridges come in three basic types:
o Local bridges: Directly connect local area networks (LANs)
o Wireless bridges: Can be used to join LANs or connect remote stations to
LANs.
Switches:
Switch is a device that performs switching. Specifically, it forwards and filters OSI
layer 2 datagrams (chunk of data communication) between ports (connected
cables) based on the Mac- Addresses in the packets. This is distinct from a hub in
that it only forwards the datagrams to the ports involved in the communications
rather than all ports connected. Strictly speaking, a switch is not capable of routing
traffic based on IP address (layer 3) which is necessary for communicating
between network segments or within a large or complex LAN. Some switches are
capable of routing based on IP addresses but are still called switches as a marketing
term. A switch normally has numerous ports with the intention that most or all of
the network be connected directly to a switch, or another switch that is in turn
connected to a switch.
Routers:
o Routers are networking devices that forward data packets between networks
using headers and forwarding tables to determine the best path to forward the
189
A complete energized Study material of Computer Science for Class XII
packets. Routers work at the network layer of the TCP/IP model or layer 3 of
the OSI model. Routers also provide interconnectivity between like and
unlike media (RFC 1812).
o A router is connected to at least two networks, commonly two LANs or
WANs or a LAN and its ISP's network.
Gateway:
A Gateway is a network device that connects dissimilar networks. It established an
intelligent connection between a local area network and external networks with
completely different structures.
The computers that control traffic within your company's network or at your local
Internet Service Provider (ISP) are gateway nodes. A network gateway can be
implemented completely in software, completely in hardware, or as a combination
of both. In the network for an enterprise, a computer server acting as a gateway
node is often also acting as a proxy server and a firewall server. Here a proxy
server is a node that is not actually a server but just appears to be so and a firewall
is a system designed to prevent unauthorized access to or from a private network.
A gateway is often associated with both a router, which knows where to direct a
given packet of data that arrives at the gateway, and a switch, which furnishes the
actual path in and out of the gateway for a given packet. It expands the
functionality of the router by performing data translation and protocol conversion.
You will sometimes see the term default gateway on network configuration screens
in Microsoft Windows.
In computer networking, a default gateway is the device that passes traffic from the
local subnet to devices on other subnets. The default gateway often connects a
local network to the Internet, although internal
gateways for local networks also exist.
190
A complete energized Study material of Computer Science for Class XII
Star Topology:
The type of network topology in which each of the nodes of the network is
connected to a central node with a point-to-point link in a 'hub' and 'spoke' fashion,
the central node being the 'hub' and the nodes that are attached to the central node
being the 'spokes' (e.g., a collection of point-to-point links from the peripheral
nodes that converge at a central node) – all data that is transmitted between nodes
in the network is transmitted to this central node, which is usually some type of
device that then retransmits the data to some or all of the other nodes in the
network, although the central node may also be a simple common connection point
(such as a 'punch- down' block) without any active device to repeat the signals.
191
A complete energized Study material of Computer Science for Class XII
Bus Topology:
The type of network topology in which all of the nodes of the network are
connected to a common transmission medium which has exactly two endpoints
(this is the 'bus', which is also commonly referred to as the backbone, or trunk) –
all data that is transmitted between nodes in the network is transmitted over this
common transmission medium and is able to be received by all nodes in the
network virtually simultaneously (disregarding propagation delays).
Ring Topology:
The type of network topology in which each of the nodes of the network is
connected to two other nodes in the network and with the first and last nodes
being connected to each other, forming a ring – all data that is transmitted between
nodes in the network travels from one node to the next node in a circular manner
and the data generally flows in a single direction only.
Computer Networks:
A communications network is two or more computers connected to share data and
resources are ―networked.‖ The simple idea behind computer networking is to
allow users to access more information and give them access to devices not
directly attached to their ―local‖ system, such as printers or storage devices.
192
A complete energized Study material of Computer Science for Class XII
Network Protocols:
In information technology, a protocol is the special set of rules that two or more
machines on a network follow to communicate with each other. They are the
standards that allow computers to communicate. A protocol defines how computers
identify one another on a network, the form that the data should take in transit, and
how this information is processed once it reaches its final destination. A protocol is
needed every time we want to perform any task on a network. It may be
transferring data or taking a printout on a network printer or accessing the central
database.
Although each network protocol is different, they all share the same physical
cabling. This common method of accessing the physical network allows multiple
protocols to peacefully coexist over the network media, and allows the builder of a
network to use common hardware for a variety of protocols. This concept is known
as "Protocol Independence." Thus it is clear that:
193
A complete energized Study material of Computer Science for Class XII
194
A complete energized Study material of Computer Science for Class XII
Example:
140.179.220.200
195
A complete energized Study material of Computer Science for Class XII
POP3:- POP3 (Post Office Protocol 3) is the standard way which has been around
for decades. It is very similar regular mail. Messages are delivered to our
computer, put in our mailbox, and are then our responsibility.
Advantage of POP3:
1. Email is available when we are offline
2. Email is not stored on the server, so our disk usage on the server is less
3. Just about any email client (software) supports POP3
IMAP:- IMAP (Interactive Mail Access Protocol).It is not like the mailbox on
your house. With IMAP mail is delivered to the server, and we connect to the
server to see our mail. The mail is not stored on our machine. When a message is
marked as read, it is marked as read on the server, not on our computer.
Advantages of IMAP:-
1. Email is available from any machine we happen to use
2. Email is stored on the server, so our email cannot be deleted/destroyed
if our computer should happen to crash, be stolen, or destroyed
3. We can access IMAP mail via the web, without even needing a mail
client installed. This means We can check our mail from someone
else's machine or even a public terminal and not have to worry about
the security of your passwords.
Telnet- It is an older internet utility that lets us log on to remote computer system.
It also facilitates for terminal emulation purpose. Terminal emulation means using
a pc like a mainframe computer through networking.
1. Run telnet client- Type telnet in run dialog box.
2. Connect to telnet site -specify the host name, port and terminal
type.
3. Start browsing- surf the shown site with provided instruction.
4. Finally disconnect-press Alt+F4.
Wireless/Mobile Computing
Wireless communication is simply data communication without the use of
landlines. Mobile computing means that the computing device is not continuously
connected to the base or central network.
1. GSM(Global System for Mobile communication): it is leading digital
cellular system. In covered areas, cell phone users can buy one phone that
will work anywhere the standard is supported. It uses narrowband TDMA,
which allows eight simultaneous calls on the same radio frequency.
2. CDMA(Code Division Multiple Access): it is a digital cellular technology
that uses spread-spectrum techniques. CDMA does not assign a specific
196
A complete energized Study material of Computer Science for Class XII
frequency to each user. Instead ,every channel uses the full available
spectrum.
3. WLL(Wireless in Local Loop) : WLL is a system that connects subscribers
to the public switched telephone network using radio signals as a substitute
for other connecting media.
4. Email(Electronic Mail): Email is sending and receiving messages by
computer.
5. Chat: Online textual talk in real time , is called Chatting.
6. Video Conferencing: a two way videophone conversation among multiple
participants is called video conferencing.
7. SMS(Short Message Service): SMS is the transmission of short text
messages to and from a mobile phone, fax machine and or IP address.
8. 3G and EDGE: 3G is a specification for the third generation of mobile
communication of mobile communication technology. 3G promises
increased bandwidth, up to 384 Kbps when a device is stationary.
9. EDGE(Enhanced Data rates for Global Evolution ) is a radio based high
speed mobile data standard.
10. Wi-Fi---Wi-Fi is short for Wireless Fidelity . Wi-Fi is a wireless
technology that uses radiofrequency to transmit data through the air. An
Access Point is a separate wireless unit, which has the ability to extend from
the router to maximize wireless reception. Up to 16 users can connect to one
access point .It allows several wireless clients to connect to a single
device.Wi-fi hot spot is defined as any location in which wireless
technology both exists and is available for use to consumers. Wi-fi was
intended to be used for wireless devices and LANS, but is now often used
for internet access.
11. IPR:- The term "Intellectual Property Rights" refers to the legal rights
granted with the aim to protect the creations of the intellect. These rights
include Industrial Property Rights (e.g. patents, industrial designs and
trademarks) and Copyright (right of the author or creator) and Related
Rights (rights of the performers, producers and broadcasting organizations
12. Cloud Computing :- The practice of using a network of remote
servers hosted on the Internet to store, manage, and process data, rather than
a local server or a personal computer.
Advantages:-
1) Cost efficient
2) Backup & Restore
3) Almost unlimited storage
4) Automatic Software Integration
5) Easy access of Information
197
A complete energized Study material of Computer Science for Class XII
Disadvantages:-
1) Technical Issue
2)Security in the cloud
3) Prone to attack
Protection methods:
1. Authorization - Authorization confirms the service requestor's credentials. It
determines if the service requestor is entitled to perform that operation.
2. Authentication - Each entity involved in using a web service the requestor,
the provider and the broker(if there is one) - is what it actually claims to be.
3. Encryption – conversion of the form of data from one form to another form.
4. Biometric System - involves unique aspect of a person's body such as Finger-
prints, retinal patterns etc to establish his/her Identity.
5. Firewall - A system designed to prevent unauthorized access to or from a
private network is called firewall. it can be implemented in both hardware
and software or combination or both.
There are several types of firewall techniques-
Packet filter- accepts or rejects of packets based on user defined rules.
Application gateway- security mechanism to specific application like FTP
and Telnet servers.
Circuit level gateway - applies security mechanism when a connection is
established.
Proxy Server - Intercepts all messages entering and leaving the network.
Cookies - Cookies are messages that a web server transmits to a web browser
so that the web server can keep track of the user‘s activity on a specific web
site. Cookies have few parameters name, value, expiration date.
Cyber Law -
It is a generic term, which refers to all the legal and regulatory aspects of internet
and the World Wide Web.
198
A complete energized Study material of Computer Science for Class XII
WEB SERVERS
WWW (WORLD WIDE WEB)
It is a small part of Internet. It is a kind of Application of internet.It is a set of
protocols that allows us to access any document on the Net through a naming
system based on URLS. Internet was mainly used for obtaining textual
information. But post-WWW the internet popularity grew tremendously because of
graphic intensive nature of www.
Attributes of WWW:
1. User friendly- www resources can be easily used with the help of browser.
2. Multimedia documents-A web page may have graphic, audio, video, and
animation etc at a time.
3. Hypertext and hyperlinks-the dynamic links which can move towards
another web page is hyperlink.
4. Interactive -www with its pages support and enable interactivity between
users and servers.
5. frame-display of more than one section on single web page.
Web server- It is a WWW server that responds to the requests made by web
browsers. e.g. : Apache, IIS, PWS(Personal web server for Windows 98).
Web browser- It is a WWW client that navigates through the World Wide Web
and displays web pages. E.g.: Fire Fox Navigator, Internet Explorer etc.
Web sites- A location on a net server where different web pages are linked
together by dynamic links is called a web site. Each web site has a unique address
called URL.
Web page - A document that can be viewed in a web browser and residing on a
web site is a web page.
Home page- a web page that is the starting page and acts as an indexed page is
home page.
Web portal - that facilitates various type of the functionality as web site. for e.g.
www.yahoo.com,www.rediff.com
Domain name- An internet address which is a character based is called a Domain
name. Some most common domains are com, edu, gov, mil, net, org, and co.Some
domain names are location based also. For e.g. au for Australia, a for Canada, in
for India etc.
URL- A URL (uniform resource locator) that specifies the distinct address for each
resource on the internet. e.g. http://encycle.msn.com/getinfo/stypes.asp
Web hosting - means hosting web server application on a computer system
through which electronic content on the internet is readily available to any web
browser client.
199
A complete energized Study material of Computer Science for Class XII
HTML -
It stands for Hyper Text Markup Language that facilitates to write web document
that can be interpreted by any web browser. It provide certain tags that are
interpreted by the browser how to display and act with the text, graphics etc. tags
are specified in <>.
For e.g.
<body bgcolor=green> it is opening tag
</body> it is closing tag.
body is the tag with bgcolor attributes.
geographic location
time of the day
previous pages viewed by the user
profile of the reader
Types of Scripts:
1. Client Side Script: Client side scripting enables interaction within a web
page. Some popular client-side scripting languages are VBScript, JavaScript,
PHP(Hyper Text Preprocessor).
2. Server-Side Scripts: Server-side scripting enables the completion or carrying
out a task at the server-end and then sending the result to the client –end.
Some popular server-side Scripting Languages are PHP, Perl, ASP(Active
Server Pages), JSP(Java Server Pages) etc.
200
A complete energized Study material of Computer Science for Class XII
Linux : Linux is a famous computer operating system . popular Linux server set of
program –LAMP(Linux, Apache, MySQL, PHP)
201
A complete energized Study material of Computer Science for Class XII
Apache server: Apache web server is an open source web server available for
many platforms such as BSD, Linux, and Microsoft Windows etc. Apache Web
server is maintained by open community of developers of Apache software
foundation.
MYSQL : MYSQL is one of the most popular open source database system.
Features of MYSQL:
o Multithreading
o Multi –User
o SQL Relational Database Server
o Works in many different platform
Postgres SQL: Postgres SQL is a free software object relational database server .
Postgres SQL can be downloaded from www.postgressql org.
Pango: Pango project is to provide an open source framework for the layout and
rendering of internationalized text into GTK + GNOME environment. Pango using
Unicode for all of its encoding ,and will eventually support output in all the
world‘s major languages.
202
A complete energized Study material of Computer Science for Class XII
Web 2.0 services : Web 2.0 is the term given to describe a second generation of
the World Wide Web that is focused on the ability for people to collaborate and
share information online. Web 2.0 basically refers to the transition from static
HTML Web pages to a more dynamic Web that is more organized and is based on
serving Web applications to users. Other improved functionality of Web 2.0
includes open communication with an emphasis on Web-based communities of
users, and more open sharing of information. Over time Web 2.0 has been used
more as a marketing term than a computer-science-based term. Blogs, wikis, and
Web services are all seen as components of Web 2.0. Web 2.0 was previously used
as a synonym for Semantic Web, but while the two are similar, they do not share
precisely the same meaning.
*****************************
203
A complete energized Study material of Computer Science for Class XII
Book References
1. C++ By E Balagurusamy
QR Code References
1. E- Content developed by Sajad Akbar Rather (I/C ICT DIET SOPORE)
3. www. easytuts4you.com
4. SuccessCDs (http://youtu.be/Kelm63Q-LO8)
6. http://youtu.be/SJXTjSqjcLg
***************************************
204