1675185953cs Supportmaterial Xii PDF
1675185953cs Supportmaterial Xii PDF
1675185953cs Supportmaterial Xii PDF
ernakulam REGION
-
SUPPORT MATERIAL 2013-14
-
CLASS: 12
COMPUTER SCIENCE
1
STUDY MATERIAL
FOR CLASS XII COMPUTER SCIENCE
(2013-14)
PATRON
GUIDANCE
Smt. V. MEENAKSHI
Asstt. Commissioner
KVS Ernakulam Region
COORDINATOR
SH. K. B. K. UNNITHAN
Principal
KV Pangode
KVS Ernakulam Region
RESOURCE PERSONS
PREFACE
It gives me immense pleasure to present the Study Material of Class XII
Computer Science for session 2013-14 by KVS Ernakulam Region.
This study material is written according to CBSE Syllabus of Computer
Science for Class XII.
I am confident that the Study Material for Class XII Computer Science will
help the students immensely to understand the concepts and will improve
the quality performance of the students.
(Ranvir Singh)
Deputy Commissioner
KVS RO, Ernakulam
Unit Name
Marks
30
UNIT 1 Programming in C++
14
UNIT 2 Data Structures
10
UNIT 3 Database and SQL
08
UNIT 4 Boolean Logic
08
UNIT 5 Communication and Open source concepts
Total Marks 70
S. N.
1
2
3
Marks
12
12
14
06
10
08
08
70
Total
Marks
09
26
15
20
70
SUPPORT MATERIAL
INDEX
Topics
S.No.
PAGE
NO.
Overview of C++
06
16
27
Inheritance
31
39
Pointers
49
Data Structures
Arrays
59
Stacks
Queues
90
Boolean Algebra
101
10
114
11
129
Data type conversion- Conversion of one data type into another data type. Two type of
conversion i.e
Implicit Conversion It is automatically taken care by complier in the case of lower range to
higher range e.g. int x, char c=A then x=c is valid i.e character value in c is automatically
converted to integer.
Explicit Conversion- It is user-defined that forces an expression to be of specific type.
e.g. double x1,x2 and int res then res=int(x1+x2)
Variable- Memory block of certain size where value can be stored and changed during program
execution. e.g. int x, float y, float amount, char c;
Constant- Memory block where value can be stored once but cant changed later on during
program execution.e.g. const int pi =3.14;
cout It is an object of ostream_withassign class defined in iostream.h header file and used to
display value on monitor.
cin It is an object of istream_withassign class defined in iostream.h header file and used to
read value from keyboard for specific variable.
comment- Used for better understanding of program statements and escaped by the compiler to
compile . e.g. single line (//) and multi- line(/*.*/)
Cascading Repeatedly use of input or output operators( >> or <<) in one statement with cin
or cout.
Control structure:
Sequence
conditional Multiple
Switch Statement
loop control statement
control
statement
Choice
(Alternate for if(while ,do while, for)
statement(if (if else)
Statement
else- if) works for
)
If else-if
only exact match
Syntax
Syntax
Syntax
Syntax
Syntax
if(expressio If(expressio If (expression)
switch(int / char
while(expression)
n)
n)
{
variable)
{
{
{
statements
{
statements;
statements;
}
case literal1:
}
}
statements;
else
[statements
Entry
control
loop
}
if(expression)
break;] case
works for true condition.
else
{
literal2:
{
statement
[statements,
do
}
break;]
{
statements;
else
default:statements; statements;
}
{
}
} while(expression);
statement
Exit
Control
Loop
}
Break
is execute at least once if
compulsory
the condition is false at
statement
with beginning.
every case because
if it is not included for loop
then the controls for(expression1;expressio
executes next case n2;expression3)
statement until next {
break encountered statement;}
or end of swtich Entry control loop works
reached.
for true condition and
Default is optional, preferred for fixed no.of
it gets executed times.
when no match is
found
7
Note: any non-zero value of an expression is treated as true and exactly 0 (i.e. all bits contain
is treated as false.
Nested loop -loop within loop.
exit()- defined in process.h and used to terminate the program depending upon certain condition.
break- exit from the current loop depending upon certain condition.
continue- to skip the remaining statements of the current loop and passes control to the next loop
control statement.
goto- control is unconditionally transferred to the location of local label specified by
<identifier>.
For example
A1:
cout<<test;
goto A1;
Some Standard C++ libraries
Header
Nome Purpose
iostream.h Defines stream classes for input/output streams
stdio.h
Standard input and output
ctype.h
Character tests
string.h
String operations
math.h
Mathematical functions such as sin() and cos()
stdlib.h
Utility functions such as malloc() and rand()
Some functions
isalpha(c)-check whether the argument is alphabetic or not.
islower(c)- check whether the argument is lowecase or not.
isupper(c) - check whether the argument is upercase or not.
isdigit(c)- check whether the argument is digit or not.
isalnum(c)- check whether the argument is alphanumeric or not.
tolower()-converts argument in lowercase if its argument is a letter.
toupper(c)- converts argument in uppercase if its argument is a letter.
strcat()- concatenates two string.
strcmp-compare two string.
pow(x,y)-return x raised to power y.
sqrt(x)-return square root of x.
random(num)-return a random number between 0 and (num-1)
randomize- initializes the random number generator with a random value.
Array- Collection of element of same type that are referred by a common name.
One Dimensional array
An array is a continuous memory location holding similar type of data in single row or single
column. Declaration in c++ is as under:
const int size =20;
int a[size] or int a[20]. The elements of array accessed with the help of an index. For
example : for(i=0;i<20;i++) cout<<a[i];
String (Array of characters) Defined in c++ as one dimensional array of characters as
char s[80]= Object oriented programming;
Two dimensional array
A two diamensional array is a continuous memory location holding similar type of data
arranged in row and column format (like a matrix structure).
Declaration int a[3][4], means a is an array of integers are arranged in 3 rows & 4
columns.
8
Function -Name given to group of statements that does some specific task and may return a
value. Function can be invoked(called) any no. of time and anywhere in the program.
Function prototypes-Function declaration that specifies the function name, return type and
parameter list of the function.
syntax: return_type function_name(type var1,type var2,.,type varn );
Actual Parameters
Variables associated with function name during function call statement.
Formal Parameters
Variables which contains copy of actual parameters inside the function definition.
Local variables
Declared inside the function only and its scope and lifetime is function only and hence
accessible only inside function.
Global variables
Declared outside the function and its scope and lifetime is whole program and hence
accessible to all function in the program from point declaration.
Example :
#include <iostream.h>
int a=20; // global
void main()
{
int b=10; // local
cout<<a<<b;
}
Passing value to functionPassing by value- In this method separate memory created for formal arguments and if any
changes done on formal variables , it will not affect the actual variables.So actual
variables are preserved in this case
Passing by address/reference- In this method no separate memory created for formal
variables i.e formal variables share the same location of actual variables and hence any change
on formal variables automatically reflected back to actual variables.
Example :
void sample( int a, int &b)
{
a=a+100; b=b+200;
cout<<a<<b;
}
void main()
{
int a=50, b=40;
cout<<a<<b; // output 50 40
sample(a,b) // output 150 240
cout<<a<<b; // output 50 240
}
Function overloading
Processing of two or more functions having same name but different list of parameters
Function recursion
Function that call itself either directly or indirectly.
Structure-Collection of logically related different data types (Primitive and Derived) referenced
under one name.
9
struct employee
{
int empno; char name[30];
char design[20]; char
department[20];
}
Declaration:
employee e;
Input /Output : cin>>e.empno; // members are accessed using dot(.) operator. cout<<e.empno;
Nested structure
A Structure definition within another structure.
A structure containing object of another structure.
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 : cin>>e.ad.houseno; // members are accessed using dot(.) operator.
cout<<e.ad.houseno;
typedef
Used to define new data type name.
typedef char Str80[80]; Str80 str;
#define Directives
Use to define a constant number or macro or to replace an instruction.
Marks questions
Which C++ header file(s) will be essentially required to be included to run /execute the
following C++ code:
void main()
{
char Msg[ ]="Sunset Gardens"; for (int
I=5;I<strlen(Msg);I++) puts(Msg);
}
Ans : stdio.h, string.h
Name the header files that shall be need for the following code:
void main()
{
char text[] =Something
cout<<Remaining SMS chars: <<160-strlen(text)<<endl;
}
Ans: iostream.h/iomanip.h , string.h
(CBSE 2012)
10
Marks questions:
Rewrite the following program after removing the syntactical error(s) if any.
Underline each correction.
CBSE 2012
#include<iostream.h>
Class Item
{
long IId, Qty; public:
void Purchase { cin>>IId>>Qty;} void
Sale()
{
cout<<setw(5)<<IId<<Old:<< Qty<<endl; cout<<
New :<<Qty<<endl;
}};
void main()
{
Item I; Purchase();
I.Sale()
}
Ans : #include<iostream.h>
class Item
// C capital
{
long IId, Qty; public:
Either the statement is removed or
header file included as
#include<iomanip.h>
void Purchase ( ) { cin>>IId>>Qty;} // ( ) after function name
void Sale( )
{
cout<<setw(5)<<IId<<Old:<< Qty<<endl; cout<<
New :<<Qty<<endl;
}};
void main()
{
Item I;
Purchase(); // object missing I.Sale()
;
// ; is missing
}
2) Find the output of the following program:
CBSE 2012
#include<iostream.h>
#include<ctype.h> typedef
char Str80[80]; void main()
{char *Notes;
Str80 str= vR2GooD;
int L=6; Notes =Str;
while(L>=3)
{
Str[L]=(isupper(Str[L])? tolower(Str[L]) : toupper(Str[L]));
cout<<Notes<<endl;
L--;
Notes++;
}}
11
Ans : vR2Good
R2GoOd 2GOOd
gOOd
Observe the following program and find out, which output(s) out id (i) to (iv) will not be
expected from program? What will be the minimum and maximum value assigned to the
variables Chance?
#include<iostream.h>
CBSE 2012
#include<stdlib.h> void
main()
{
randomize();
int Arr[] = {9,6};, N;
int Chance = random(2)+10; for(int
c=0;c<2;c++)
{
N= random(2); cout<<Arr[N];
}}
9#6#
19#17#
19#16#
20#16#
Ans: The output not expected from program are (i),(ii) and (iv) Minimum
value of Chance =10
Maximum value of Chance = 11
Marks questions:
4) Find the output of the following program:
CBSE 2012
#include<iostream.h>
class METRO
{
int Mno, TripNo, PassengerCount; public:
METRO(int Tmno=1) { Mno =Tmno; PassengerCount=0;} void
Trip(int PC=20) { TripNo++, PassengerCount+=PC};
void StatusShow()
{
cout<<Mno<< :<<TripNo<< :<<PassengerCount<<endl;}
};
void main()
{
METRO M(5), T;
M.Trip(); M.StatusShow();
T.StatusShow(); M.StatusShow();
}
Ans : 5: 1: 20
1: 1: 50
5: 2: 50
12
13
9) Rewrite the following C++ program after removing the syntax error(s) if any.
Underline each correction.
[CBSE 2010]
include<iostream.h>
class FLIGHT
{
Long FlightCode;
Char Description[25];
public
void addInfo()
{
cin>>FlightCode; gets(Description);}
void showInfo()
{
cout<<FlightCode<<:<<Description<<endl;}
};
void main( )
{
FLIGHT F;
addInfo.F(); showInfo.F;
}
In the following program, find the correct possible output(s)from the options:
#include<stdlib.h>
#include<iostream.h> void main( )
{ randomize( );
char City[ ][10]={DEL, CHN, KOL, BOM, BNG};
int Fly;
for(int I=0; I<3;I++)
{Fly=random(2) + 1;
cout<<City[Fly]<< :;
}}
Outputs:
DEL : CHN : KOL:
(ii) CHN: KOL : CHN:
(iii) KOL : BOM : BNG:
(iv) KOL : CHN : KOL:
In the following C++ program what is the expected value of Myscore from options (i) to
(iv) given below. Justify your answer.
#include<stdlib.h>
#include<iostream.h> void main( )
{
randomize( );
int Score[ ] = {25,20,34,56,72,63},Myscore;
cout<<Myscore<<endl;
}
i)
25 (ii) 34 (iii) 20 (iv) Garbage Value.
14
int main(void)
{
printData pd;
// Call print to print integer pd.print(5);
// Call print to print float pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
return 0;
}
When the above code is compiled and executed, it produces following result:
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
15
Data Abstraction:
It refers to the act of representing essential features without including the background details
.Example : For driving , only accelerator, clutch and brake controls need to be learnt rather
than working of engine and other details.
Data Encapsulation:
It means wrapping up data and associated functions into one single unit called class..
A class groups its members into three sections :public, private and protected, where private
and protected members remain hidden from outside world and thereby helps in implementing
data hiding.
Modularity :
The act of partitioning a complex program into simpler fragments called modules is called as
modularity.
It reduces the complexity to some degree and
It creates a number of well defined boundaries within the program .
Polymorphism:
Poly means many and morphs mean form, so polymorphism means one name multiple forms.
It is the ability for a message or data to be processed in more than one form.
C++ implements Polymorhism through Function Overloading , Operator overloading and Virtual
functions .
.
SHAPE
area()
RECTANGLE()
TRIANGLE()
CIRCLE()
area(rectangle)
Area(triangle)
Area(circle)
16
Classes in Programming :
It is a collection of variables, often of different types and its associated functions.
Class just binds data and its associated functions under one unit there by enforcing
encapsulation.
Classes define types of data structures and the functions that operate on those data
structures.
A class defines a blueprint for a data type.
Declaration/Definition :
A class definition starts with the keyword class followed by the class name; and the class body,
enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a
list of declarations.
class class_name {
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
Where class_name is a valid identifier for the class, object_names is an optional list of names for
objects of this class. The body of the declaration can contain members that can either be data or
function declarations, and optionally access specifiers.
[Note: the default access specifier is private.
Example : class Box { int a;
public:
double length; // Length of a box double breadth; //
Breadth of a box double height; // Height of a box
};
17
Member-Access Control
Type of Access
Meaning
Private
Protected
Public
OBJECTS in C++:
Objects represent instances of a class. Objects are basic run time entities in an object oriented
system.
Creating object / defining the object of a class:
The general syntax of defining the object of a class is:Class_name object_name;
In C++, a class variable is known as an object. The declaration of an object is similar to that of a
variable of any data type. The members of a class are accessed or referenced using object of a
class.
Box Box1;
Box Box2;
Both of the objects Box1 and Box2 will have their own copy of data members.
19
INLINE FUNCTIONS
Inline functions definition starts with keyword inline
The compiler replaces the function call statement with the function code
itself(expansion) and then compiles the entire code.
They run little faster than normal functions as function calling overheads are saved.
A function can be declared inline by placing the keyword inline before it.
Example
inline void Square (int a)
{ cout<<a*a;} void main()
{.
Square(4);
{ cout <<4*4;}
Square(8) ;
{ cout <<8*8; }
In place of function
call , function body is
substituted because Square ()
is inline function
20
/**********OUTPUT***********
Height is:6feet 5inches
Height is:2feet 7inches Height
is 9 feet and 0
21
22
23
Public Members
A function Enter( ) to allow user to enter values for ANo, Name, Agg & call function
GradeMe( ) to find the Grade
A function Result ( ) to allow user to view the content of all the data members.
Ans:class Applicant
{long ANo; char
Name[25]; float Agg;
char Grade;
void GradeMe( )
{
if (Agg > = 80)
Grade = A;
else if (Agg >= 65 && Agg < 80 )
Grade = B;
else if (Agg >= 50 && Agg < 65 )
Grade = C;
else
Grade = D;
}
public:
void Enter ( )
{
cout <<\n Enter Admission No.
; cin>>ANo;
cout <<\n Enter Name of the Applicant
; cin.getline(Name,25);
cout <<\n Enter Aggregate Marks obtained by the Candidate :; cin>>Agg;
GradeMe( );
}
void Result( )
{
cout <<\n Admission No. <<ANo;
cout <<\n Name of the Applicant ;<<Name;
cout<<\n Aggregate Marks obtained by the Candidate.
<< Agg;
cout<<\n
Grade Obtained is << Grade ;
}
};
24
25
Calculate() a function that calculates overall percentage of marks and return the
percentage of marks.
public members :
Readmarks() a function that reads marks and invoke the Calculate function.
Displaymarks() a function that prints the marks.
Q3 : Define a class report with the following specification :
Private members :
4 digit admission number
adno
20 characters
name
an array of 5 floating point values
marks
average
average marks obtained
getavg() to compute the average obtained in five subjects
Public members :
readinfo() function to accept values for adno, name, marks, and invoke the function
getavg().
displayinfo() function to display all data members on the screen you should give function
definitions.
26
TYPES OF CONSRUCTORS:
Default Constructor:
A constructor that accepts no parameter is called the Default Constructor. If you don't declare a
constructor or a destructor, the compiler makes one for you. The default constructor and
destructor take no arguments and do nothing.
Parameterized Constructors:
A constructor that accepts parameters for its invocation is known as parameterized Constructors ,
also called as Regular Constructors.
Copy Constructor
A copy constructor is a special constructor in the C++ programming language used to
create a new object as a copy of an existing object.
A copy constructor is a constructor of the form classname(classname &).The compiler
will use the copy constructors whenever you initialize an instance using values of another instance
of the same type.
Copying of objects is achieved by the use of a copy constructor and a assignment operator.
Example :
class Sample{ int i, j;}
public:
Sample(int a, int b)
// constructor
{ i=a;j=b;}
Sample (Sample & s)
//copy constructor
{ j=s.j ; i=s.i;
cout <<\n Copy constructor working \n;
}
void print (void)
{cout <<i<< j<< \n;}
};
Note : The argument to a copy constructor is passed by reference, the reason being that when
an argument is passed by value, a copy of it is constructed. But the copy constructor is creating
a copy of the object for itself, thus ,it calls itself. Again the called copy constructor requires
another copy so again it is called. In fact it calls itself again and again until the compiler runs
out of the memory .So, in the copy constructor, the argument must be passed by reference.
**
Derived classes do not inherit constructors or destructors from their base classes, but they do call
the constructor and destructor of base classes.
The default destructor calls the destructors of the base class and members of the derived class.
The destructors of base classes and members are called in the reverse order of the
completion of their constructor:
The destructor for a class object is called before destructors for members and bases are called.
*****************
Ans.
valid
valid
invalid
valid
invalid
Q3 Given the following C++ code, answer the questions (i) & (ii).
class TestMeOut
{
public :
~TestMeOut() // Function 1
{ cout << "Leaving the examination hall " << endl; } TestMeOut()
// Function 2
{ cout << "Appearing for examination " << endl; } void
MyWork() // Function 3
{ cout << "Attempting Questions " << endl; }
};
In Object Oriented Programming, what is Function 1 referred as and when does it get invoked
/ called ?
In Object Oriented Programming, what is Function 2 referred as and when does it get invoked
/ called ?
30
INHERITANCE
Inheritance is the process by which new classes called derived classes are created from
existing classes called base classes.
The derived classes have all the features of the base class and the programmer can choose to add
new features specific to the newly created derived class.
The idea of inheritance implements the is a relationship. For example, mammal IS-A animal,
dog IS-A mammal hence dog IS-A animal as well and so on.
which
31
// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
When the above code is compiled and executed, it produces following result: Total
area: 35
public
protected
private
Same class
yes
yes
yes
Derived classes
yes
yes
no
Outside classes
yes
no
no
A derived class inherits all base class methods with the following exceptions:
Constructors, destructors and copy constructors of the base class.
Overloaded operators of the base class.
The friend functions of the base class.
When deriving a class from a base class, the base class may be inherited through public, protected
or private inheritance. We hardly use protected or private inheritance but public inheritance
is commonly used. While using different type of inheritance, following rules are applied:
32
Public Inheritance: When deriving a class from a public base class, public members of the base
class become public members of the derived class and protected members of the base class
become protected members of the derived class. A base class's private members are never
accessible directly from a derived class, but can be accessed through calls to the public and
protected members of the base class.
Protected Inheritance: When deriving from a protected base class, public and
protected members of the base class become protected members of the derived class.
Private Inheritance: When deriving from a private base class, public and protected
members of the base class become private members of the derived Class.
TYPES OF INHERITANCE
Single class Inheritance:
Single inheritance is the one where you have a single base class and a single derived class.
it is class (super)
Class A a Base
Multilevel Inheritance:
In Multi level inheritance, a subclass inherits from a class that itself inherits from another class.
Class A
Multiple Inheritance:
In Multiple inheritances, a derived class inherits from multiple base classes. It has
properties of both the base classes.
Class A
Class B
Base class
33
Hierarchical Inheritance:
In hierarchial Inheritance, it's like an inverted tree. So multiple classes inherit from a
single base class.
Base Class
Class A
Class B
Class C
Sub Class( derived)
Class D
Hybrid Inheritance:
It combines two or more forms of inheritance .In this type of inheritance, we can have mixture
of number of inheritances but this can generate an error of using same name function from no of
classes, which will bother the compiler to how to use the functions.
Therefore, it will generate errors in the program. This has known as ambiguity or
duplicity.
Ambiguity problem can be solved by using virtual base classes
Class A
Class B Class C
Class D
Name the base class and derived class of the class COUNTRY.
Name the data member(s) that can be accessed from function DISPLAY().
Name the member function(s), which can be accessed from the objects of class STATE.
Is the member function OUTPUT() accessible by the objects of the class COUNTRY ?
Ans (i) Base class : WORLD
Derived class : STATE
M.
DISPLAY(), INDATA() and OUTDATA()
No
Q2. Consider the following declarations and answer the questions given below : class
living_being {
char name[20]; protected:
int jaws;
public:
void inputdata(char, int); void
outputdata();
}
class animal : protected living_being { int
tail;
protected: int
legs; public:
void readdata(int, int); void
writedata();
};
class cow : private animal { char
horn_size;
public:
void fetchdata(char); void
displaydata();
};
Name the base class and derived class of the class animal.
Name the data member(s) that can be accessed from function displaydata.
Name the data member(s) that can be accessed by an object of cow class.
the member function outputdata accessible to the objects of animal class.
Ans (i) Base class : living_being
Derived class : cow
rn_size, legs, jaws
fetchdata() and displaydata()
No
Q3. Consider the following and answer the questions given below : class
MNC
{
char Cname[25]; // Company name protected
:
char Hoffice[25]; // Head office public
:
MNC( );
char Country[25]; void
EnterDate( ); void
DisplayData( );
};
35
36
Which constructor will be called first at the time of declaration of an object of class
Manager?
w many bytes will an object belonging to class Manager require ?
Name the member function(s), which are directly accessible from the object(s) of class
Manager.
the member function OUTPUT() accessible by the objects of the class Director ?
Ans (i) CEO()
(ii) 16
DISPLAY(), INDATA(), OUTDATA(), INPUT(), OUTPUT()
Yes
37
public:
void readphysicsbook(); void
showphysicsbook();}
Name the members, which can be accessed from the member functions of class
physicsbook.
Name the members, which can be accessed by an object of Class textbook.
Name the members, which can be accessed by an object of Class physicsbook.
What will be the size of an object (in bytes) of class physicsbook.
Q3 : Answer the questions (i) to (iv) based on the following: class
CUSTOMER
{
int Cust_no;
char Cust_Name[20]; protected:
void Register();
public:
CUSTOMER( );
void Status( );};
class SALESMAN
{
int Salesman_no;
char Salesman_Name[20]; protected:
float Salary; public: SALESMAN( );
void Enter( ); void Show( );};
class SHOP :
private CUSTOMER, public SALESMAN
{
char Voucher_No[10];
char Sales_Date[8;
public :
SHOP( );
void Sales_Entry( ); void Sales_Detail( );};
Write the names of data members, which are accessible from object belonging to class
CUSTOMER.
Write the names of all the member functions which are accessible from object belonging to
class SALESMAN.
Write the names of all the members which are accessible from member functions of class
SHOP.
How many bytes will be required by an object belonging to class SHOP?
39
We can also use file>>ch for reading and file<<ch writing i n text file. But >> operator does not
accept white spaces.
Binary file functions:
read()- read a block of binary data or reads a fixed number of bytes from the specified stream
and store in a buffer.
Syntax : Stream_object.read((char *)& Object, sizeof(Object));
e.g file.read((char *)&s, sizeof(s));
write() write a block of binary data or writes fixed number of bytes from a specific
memory location to the specified stream.
Syntax : Stream_object.write((char *)& Object, sizeof(Object));
e.g file.write((char *)&s, sizeof(s));
Note:
Both functions take two arguments.
The first is the address of variable, and the second is the length of that variable in bytes. The
address of variable must be type cast to type char*(pointer to character type)
The data written to a file using write( ) can only be read accurately using read( ).
File Pointer: The file pointer indicates the position in the file at which the next input/output is to
occur.
Moving the file pointer in a file for various operations viz modification, deletion , searching
etc. Following functions are used:
seekg(): It places the file pointer to the specified position in input mode of file.
e.g file.seekg(p,ios::beg); or file.seekg(-p,ios::end), or file.seekg(p,ios::cur)
i.e to move to p byte position from beginning, end or current position.
seekp(): It places the file pointer to the specified position in output mode of file.
e.g file.seekp(p,ios::beg); or file.seekp(-p,ios::end), or file.seekp(p,ios::cur)
i.e to move to p byte position from beginning, end or current position.
tellg(): This function returns the current working position of the file pointer in the input mode.
e.g int p=file.tellg();
tellp(): This function returns the current working position of the file pointer in the output mode.
e.f int p=file.tellp(); Steps To
Create A File
Declare an object of the desired file stream class(ifstream, ofstream, or fstream)
Open the required file to be processed using constructor or open function.
Process the file.
Close the file stream using the object of file stream.
General program structure used for creating a Text File
To create a text file using strings I/O
#include<fstream.h> //header file for file operations
void main()
{
char s[80], ch;
ofstream file(myfile.txt); //open myfile.txt in default output mode
do
{
cout<<\n enter line of text;
gets(s); //standard input
file<<s; // write in a file myfile.txt
cout<<\n more input y/n;
40
cin>>ch;
}while(ch!=n||ch!=N);
file.close();
} //end of main
To create a text file using characters I/O
#include<fstream.h> //header file for file operations
void main()
{
char ch;
ofstream file(myfile.txt); //open myfile.txt in default output mode
do{ ch=getche();
if (ch==13) //check if character is enter key
cout<<\n;
else
file<<ch; // write a character in text file myfile.txt
} while(ch!=27); // check for escape key file.close();
} //end of main
Text files in input mode:
To read content of myfile.txt and display it on monitor.
2 Marks Questions:
Write a function in a C++ to read the content of a text file DELHI.TXT and display all
those lines on screen, which are either starting with D or starting with M. [CBSE 2012]
void DispDorM()
{
ifstream File(DELHI.TXT) char str[80];
while(File.getline(str,80))
{
if(str[0] = =D || str[0] = =M)
cout<<str<<endl;
}
File.close(); //Ignore
}
Write a function in a C++ to count the number of lowercase alphabets present in a text file
BOOK.txt.
int countalpha()
{
ifstream Fin(BOOK.txt);
char ch;
int count=0;
while(!Fin.eof())
{Fin.get(ch);
41
if (islower(ch))
count++;
}
Fin.close(); return count;
}
Function to count number of lines from a text files (a line can have maximum 70 characters
or ends at .)
int countword()
{
ifstream Fin(BOOK.txt);
char ch[70]; int
count=0; if (!Fin)
{
cout<<Error opening file! ;
exit(0);
}
42
while(1)
{Fin.getline(ch,70,.);
if (Fin.eof())
break; count++;
}
Fin.close(); return count;
}
clrscr(); student s;
if(!fout)
{cout<<File cant be opened;
break;
}
do
{
s.input();
cout<<\n more record y/n;
cin>>ch;
}while(ch!=n || ch!=N);
fout.close();
}
void read_file()
{
ifstream fin; student s;
fin.open(student.dat,ios::in | ios:: binary);
fin.read((char *) &s,sizeof(student)); while(file)
{
s.output();
cout<< \n;
fin.read((char *) & s,sizeof(student));
}
fin.close();
}
void modify_record()
{
student s;
fstream file;
file.open(student.dat,ios::in|ios::out|ios::ate|ios::binary);
int r,pos=-1;
cout<<\n enter the rollo no of student whom data to be modified;
cin>>r;
file.read((char *)&s,sizeof(s)); while(file)
{
if (r==s.getrno())
{
cout<<\n record is ;
s.output();
pos =file.tellg()-size(s); break;
}
file.read((char *)&s,sizeof(s));
}
if(pos>-1)
{
cout<< \n enter new
record;
s.input(); file.seekp(pos,ios::beg);
file.write((char *)&s,sizeof(s));
cout<< \n record modified successfully;
}
else
cout<< \n record not exist;
}
45
void delete_record()
{
fstream file(student.dat, ios::in|ios::binary); fstream
newfile(newstu.dat,ios::out|ios::binary);
student s;
cout<<\n enter the rollno no of student whom record to be deleted;
cin>>r;
file.read((char *)&s,sizeof(s)); while(file)
{
if (r!=s.getrno())
{
newfile.write((char *)&s,sizeof(s));
}
file.read((char *)&s,sizeof(s));
}
file.close(); newfile.close();
}
void search_record()
{
student s;
fstream file;
file.open(student.dat,ios::in|os::binary); int r,flag=1;
cout<<\n enter the rollo no of student whom record to be searched;
cin>>r;
file.read((char *)&s,sizeof(s)); while(file)
{
if (r==s.getrno())
{
cout<<\n record is ;
s.output(); flag=1;
break;
}
file.read((char *)&s,sizeof(s));
}
if(flag==1)
cout<< \n search successfull;
else
cout<< \n search unsuccessfull;
file.close();
}
1 Mark Questions
Observe the program segment carefully and answer the question that follows:
class stock
{
int Ino, Qty; Char Item[20];
public:
void Enter() { cin>>Ino; gets(Item); cin>>Qty;}
void issue(int Q) { Qty+=0;}
void Purchase(int Q) {Qty-=Q;}
int GetIno() { return Ino;}
};
void PurchaseItem(int Pino, int PQty)
{
fstream File;
46
File.open(stock.dat, ios::binary|ios::in|ios::out);
Stock s;
int success=0;
while(success= = 0 && File.read((char *)&s,sizeof(s)))
{
If(Pino= = ss.GetIno())
{
s.Purchase(PQty);
// statement 1
// statement 2
Success++;
}
}
if (success = =1)
cout<< Purchase Updated<<endl;
else
cout<< Wrong Item No<<endl;
File.close() ;
}
Ans.1. i) Statement 1 to position the file pointer to the appropriate place so that the data
updation is done for the required item.
File.seekp(File.tellg()-sizeof(stock); OR
File.seekp(-sizeof(stock),ios::cur);
ii) Staement 2 to perform write operation so that the updation is done in the binary file.
File.write((char *)&s, sizeof(s)); OR File.write((char *)&s, sizeof(stock));
3 Marks Question
Write a function in c++ to search for details (Phoneno and Calls) of those Phones which
have more than 800 calls from binary file phones.dat. Assuming that this binary file
contains records/ objects of class Phone, which is defined below.
class Phone
CBSE 2012
{
Char Phoneno[10]; int Calls;
public:
void Get() {gets(Phoneno); cin>>Calls;}
void Billing() { cout<<Phoneno<< #<<Calls<<endl;}
int GetCalls() {return Calls;}
};
Ans 2 : void Search()
{
Phone P; fstream fin;
fin.open( Phone.dat, ios::binary| ios::in);
while(fin.read((char *)&P, sizeof(P)))
{
if(p.GetCalls() >800)
p.Billing();
}
Fin.close(); //ignore
}};
47
Write a function in C++ to add 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;}
};
Ans.3. void searchbook(int bookno)
{ifstream ifile(BOOK.DAT,ios::in|ios::binary);
if(!ifile)
{cout<<could not open BOOK.DAT file; exit(-1);}
else
{BOOK b; int found=0;
while(ifile.read((char *)&b, sizeof(b)))
{if(b.RBno()==bookno)
{b.Display(); found=1; break;}
}
if(! found)
cout<<record is not found ;
ifile.close();
}
}
4. Given a binary file PHONE.DAT, containing records of the following class type
class Phonlist
{
char name[20]; char
address[30]; char
areacode[5]; char
Phoneno[15]; public:
void Register() void
Show();
void CheckCode(char AC[])
{return(strcmp(areacode,AC);
}};
Write a function TRANSFER( ) in C++, that would copy all those records which are having
areacode as DEL from PHONE.DAT to PHONBACK.DAT.
Ans 4. void TRANSFER()
{
fstream File1,File2; Phonelist P;
File1.open(PHONE.DAT, ios::binary|ios::in); File2.open(PHONEBACK.DAT,
ios::binary|ios::OUT) while(File1.read((char *)&P, sizeof(P)))
{
if( p.CheckCode( DEL))
File2.write((char *)&P,sizeof(P));
}
File1.close(); File2.close();
}
48
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.
*variable_name;
float *p1;
char *c;
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.
e.g.
i nt *p;
P++;
If current address of p is 1000, then p++ statement will increase p to 1002, not 1001. If
*c is char pointer and *p is integer pointer then
Char pointer
Address
Int pointer
C
100
c+1
c+2
c+3
c+4
c+5
c+6
c+7
101
102
103
104
105
106
107
p
p+1
p+2
p+3
Adding 1 to a pointer actually adds the size of pointers 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.
49
For array :
delete [size] pointer variable;
Eg. delete [ ] arr;
50
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
address
0
1000
1
1002
3
1006
4
1008
c
34
d
45
2450
e
56
2725
1004
a
12
1050
b
23
1065
Index
Array ip
value
address
2001
ip[4] = &e;
ip[0]
ip[1]
ip[2]
ip[3]
ip[4]
1050
1065
2001
2450
2725
1000
1002
1004
1006
ip is now a pointer pointing to its first element of ip. Thus ip is equal
to address of ip[0], i.e. 1000
*ip (the value of ip[0]) = 1050
(* ip) = the value of *ip = 12
* * (ip+3) = * * (1006) = * (2450) = 45
1008
51
An array of char pointers is very useful for storing strings in memory. Char
*subject[] = { Chemistry, Phycics, Maths, CS, English };
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.
// integer m declaration
// pointer p to an integer m
// ok : increments int pointer p
// a const pointer c to an intger n
// ok : increments int pointer c i.e. its contents
// wrong : pointer c is const address cant be modified
// a const integer cn
// a pointer to a const int
// wrong : int * pc is const contents cant be modified
// ok : increments pointer pc
// a const pointer to a const integer
// wrong : int *cc is const
// wrong : pointer cc is const
52
{
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();
cout << \n Set point at 6,7 with object pointer; p2>getPoint(6,7);
cout<< \n The point is :; p2>putPoint();
cout << \n Print point using object :; p1.getPoint();}
If you make an object pointer point to the first object in an array of objects, incrementing the pointer
would make it point to the next object in sequence.
student stud[5], *sp;
--sp = stud;
// sp points to the first element (stud[0])of stud
sp++;
// sp points to the second element (stud[1]) of stud sp + = 2;
// sp points to the fourth element (stud[3]) of stud sp--;
// sp
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 objects data
member is to be manipulated?
55
Member Function1
Object 1
Data Member1
Data Member 2
Member Function2
Object 2
Data Member1
Data Member 2
Member Function3
Object 3
Data Member1
Data Member 2
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 Objects Data Member3 is to be changed?
To overcome this problem this pointer is used.
When a member function is called, it is automatically passed an implicit argument that is a pointer to
the object that invoked the function. This pointer is called This.
That is if ojbect3 is invoking member function2, then an implicit argument is passed to member
function2 that points to object3 i.e. this pointer now points to object3.
The friend functions are not members of a class and, therefore, are not passed a this pointer. The static
member functions do not have a this pointer.
Solved Questions
Q. 1
How is *p different from **p ?
Ans :
*p means, it is a pointer pointing to a memory location storing a value in it. But **p means, it
is a pointer pointing to another pointer which in turn points to a memory
location storing a value in it.
Q. 2
How is &p different from *p ?
Ans :
&p gives us the address of variable p and *p. dereferences p and gives us the value
stored in memory location pointed to by p.
Q. 3
Find the error in following code segment :
Float **p1, p2;
P2 = &p1;
Ans : In code segment, p1 is pointer to pointer, it means it can store the address of another pointer
variable, whereas p2 is a simple pointer that can store the address of a normal variable. So here the
statement p2 = &p1 has error.
Q. 4
What will be the output of the following code segment ?
char C1 = A; char C2 = D;
char *i, *j; i = &C1;
j = &C2;
*i = j;
cout << C1; Ans :
It will
print A.
5
How does C++ organize memory when a program is run ?
Ans :
Once a program is compiled, C++ creates four logically distinct regions of memory :
area to hold the compiled program code
area to hold global variables
the stack area to hold the return addresses of function calls, arguments passed to the functions, local
variables for functions, and the current state of the CPU.
The heap area from which the memory is dynamically allocated to the program.
56
Q. 6
Identify and explain the error(s) in the following code segment :
float a[] = { 11.02, 12.13, 19.11, 17.41};
float *j, *k; j = a;
k = a + 4; j = j *
2; k = k / 2;
cout << *j = << *j << , *k = << *k << \n; Ans :
The erroneous statements in the code are :
j = j * 2; k = k / 2;
Because multiplication and division operations cannot be performed on pointer and j and k are
pointers.
13 How does the functioning of a function differ when
an object is passed by value ?
(ii)
an object is passed by reference ?
Ans : (i) When an object is passed by value, the called function creates its own copy of theobject
by just copying the contents of the passed object. It invokes the objects copy constructor to
create its copy of the object. However, the called function destroys its copy of the object by
calling the destructor function of the object upon its termination.
(i)
When an object is passed by reference, the called function does not create its own copy
of the passed object. Rather it refers to the original object using its
reference or alias name. Therefore, neither constructor nor destructor function of the object is invoked in
such a case.
2 MARKS PRACTICE QUESTIONS
Differentiate between static and dynamic allocation of memory.
Identify and explain the error in the following program :
#include<iostream.h> int main()
{int x[] = { 1, 2, 3, 4, 5 };
for (int i = 0; i < 5; i++)
{
cout << *x;
x++;
}
return 0;
}
Give the output of the following : char *s =
computer;
for (int x = strlen(s) 1; x >= 0; x--)
{
for(int y =0; y <= x; y++)
cout << endl;
}
57
Identify the syntax error(s), if any, in the following program. Also give reason for errors. void
main()
{const int i = 20;
const int * const ptr = &i;
(*ptr++; int j= 15; ptr
= &j; }
What is this pointer ? What is its significance ?
What will be the output of following program ?
#include<iostream.h> void
main()
{
char
name1[] = ankur; char
name2[] = ankur; if (name1 != name2)
cout << \n both the strings are not equal;
else
cout << \n the strings are equal;
}
Give and explain the output of the following code :
void junk (int, int *);
int main()
{
int i = 6, j = -4;
junk (i, &j);
cout << i = << i << , j = << j << \n;
return 0;
}
void junk(int a, int *b)
{
a = a* a;
*b = *b * *b;
}
58
59
60
if(item==a[middle])
return middle; // item is found else if(item<
a[middle])
last=middle-1; //item is present in left side of the middle element
else
first=middle+1; // item is present in right side of the middle element
}
return -1; //given item is not present in the array, here, -1 indicates unsuccessful search
}
void main()
{
int b[8]={2,4,5,7,8,9,12,15},size=8;
int item;
cout<<enter a number to be searched for;
cin>>item;
int p=binary_search(b, size, item); //search item in the array b if(p==-1)
cout<<item<< is not present in the array<<endl;
else
cout<<item << is present in the array at index no <<p;
}
Let us see how this algorithm work for item=12
Initializing first =0 ; last=size-1; where size=8 Iteration
1
A[0]
a[1] [2]
a[3]
a[4] a[5] a[6] a[7]
2
4
5
7
8
9
12
15
first
middle
last
First=0, last=7
middle=(first+last)/2=(0+7)/2=3 // note integer division 3.5 becomes 3 value of
a[middle] i.e. a[3] is 7
7<12 then first= middle+1 i.e. 3 + 1 =4
iteration 2
A[4]
a[5] a[6] a[7]
8
9
12
15
first
middle
last
first=4, last=7
middle=(first+last)/2=(4+7)/2=5 value of
a[middle] i.e. a[5] is 9 9<12 then
first=middle+1;5+1=6
iteration 3
a[6]
12
first
a[7]
15
middle
last
first=6,last=7
61
middle=(first+last)/2 = (6+7)/2=6
value of a[middle] i.e. a[6] is 12 which is equal to the value of item being search i.e.12
As a successful search the function binary_search() will return to the main function with value 6 as index of
12 in the given array. In main function p hold the return index number.
Note that each iteration of the algorithm divides the given array in to two equal segments and the only one
segment is compared for the search of the given item in the next iteration. For a given array of size N= 2 n
elements, maximum n number of iterations are required to make sure whether the given item is present in
the given array or not, where as the linear requires maximum 2n number of iteration. For example, the
number of iteration required to search an item in the given array of 1000 elements, binary search requires
maximum 10 (as 1000210) iterations where as linear search requires maximum 1000 iterations.
Inserting a new element in an array
We can insert a new element in an array in two ways
If the array is unordered, the new element is inserted at the end of the array
If the array is sorted then the new element is added at appropriate position without altering the order.
To achieve this, all elements greater than the new element are shifted. For example, to add 10 in the given
array below:
a[0] a[1] [2] a[3]
a[4] a[5] a[6] a[7] a[8]
2
a[0]
a[1] [2]
7
8
11
12
15
Original array
a[3]
a[4] a[5] a[6] a[7] a[8]
2
4
5
7
8
11
12
Elements greater than 10 shifted to create free place to insert 10 a[0]
a[3] a[4] a[5] a[6] a[7] a[8]
15
a[1] [2]
4
5
7
8 10
11
12
15
Array after insertion
Following program implement insertion operation for sorted array
#include<iostream.h>
void insert(int a[ ], int &n, int item) //n is the number of elements already present in the array
{
int i=n-1;
while (i>=0 && a[i]>item)
{
a[i+1]=a[i]; // shift the ith element one position towards right i--;
}
a[i+1]=item;
//insertion of item at appropriate place
n++; //after insertion, number of elements present in the array is increased by 1
}
void main()
{int a[10]={2,4,5,7,8,11,12,15},n=8;
int i=0;
cout<<Original array is:\n;
for(i=0;i<n;i++)
cout<<a[i]<<, ;
insert(a,n,10);
cout<<\nArray after inserting 10 is:\n;
62
a[0] a[1]
[2]
a[0] a[1]
[2]
7
8
11
12
15
Original array
a[3]
a[4] a[5] a[6] a[7]
7
8
12
15
Element removed
a[3]
a[4] a[5] a[6] a[7]
2
4
5
7
8
12
15
Array after shifting the rest element Following program implement
deletion operation for sorted array
#include<iostream.h>
void delete_item(int a[ ], int &n, int item) //n is the number of elements already present in the array
{int i=0;
while(i<n && a[i]<item) i++;
if (a[i]==item) // given item is found
{while (i<n)
{a[i]=a[i+1]; // shift the (i+1)th element one position towards left i++;
}
cout<<\n Given item is successfully deleted;
}
else
cout<<\n Given item is not found in the array;
n--;
}
void main()
{int a[10]={2,4,5,7,8,11,12,15},n=8;
int i=0;
cout<<Original array is :\n;
for(i=0;i<n;i++)
cout<<a[i]<<, ;
delete_item(a,n,11);
cout<<\nArray after deleting 11 is:\n;
63
Sorting
The process of arranging the array elements in increasing (ascending) or decreasing (descending) order is
known as sorting. There are several sorting techniques are available e.g. selection sort, insertion sort,
bubble sort, quick sort, heap short etc. But in CBSE syllabus only selection sort, insertion sort, bubble sort
are specified.
Selection Sort
The basic idea of a selection sort is to repeatedly select the smallest element in the remaining unsorted
array and exchange the selected smallest element with the first element of the unsorted array. For
example, consider the following unsorted array to be sorted using selection sort
64
Original array
0
8
1
5
2
9
3
3
4
16
5
4
6
7
iteration 1 : Select the smallest element from unsorted array which is 3 and exchange 3 with the first
element of the unsorted array i.e. exchange 3 with 8. After iteration 1 the element 3 is at its final position in
the array.
0
1
2
3
4
5
6
5
9
8 16
4
7
3
Iteration 2:
The second pass identify 4 as the smallest element and then exchange 4 with 5
0
Iteration 3:
0
Iteration 4:
0
Iteration 5:
0
Iteration 6:
no effect.
0
2
3
4
5
6
9
8
16
5
7
3
4
The third pass identify 5 as the smallest element and then exchange 5 with 9
1
2
3
4
5
6
8
16
9
7
3
4
5
The third pass identify 7 as the smallest element and then exchange 7 with 8
1
2
3
4
5
6
16
9
8
3
4
5
7
The third pass identify 8 as the smallest element and then exchange 8 with 16
1
2
3
4
5
6
9
16
3
4
5
7
8
The third pass identify 9 as the smallest element and then exchange 9 with 9 which makes
1
2
3
4
5
6
16
3
4
5
7
8
9
The unsorted array with only one element i.e. 16 is already at its appropriate position so no more iteration
is required. Hence to sort n numbers, the number of iterations required is n-1, where in each next iteration,
the number of comparison required to find the smallest element is decreases by 1 as in each pass one
element is selected from the unsorted part of the array and moved at the end of sorted part of the array .
For n=7 the total number of comparison required is calculated as
Pass1: 6 comparisons i.e. (n-1) Pass2: 5
comparisons i.e. (n-2) Pass3: 4 comparisons
i.e. (n-3) Pass4: 3 comparisons i.e. (n-4) Pass5:
2 comparisons i.e. (n-5)
Pass6: 1 comparison i.e. (n-6)=(n-(n-1))
Total comparison for n=(n-1)+(n-2)+(n-3)+ .+(n-(n-1))= n(n-1)/2
7=6+5+4+3+2+1=7*6/2=21;
Note: For given array of n elements, selection sort always executes n(n-1)/2 comparison statements
irrespective of whether the input array is already sorted(best case), partially sorted(average case) or
totally unsorted(i.e. in reverse order)(worst case).
#include<iostream.h>
void select_sort(int a[ ], int n) //n is the number of elements present in the array
{int i, j, p, small;
for(i=0;i<n-1;i++)
{small=a[i]; // initialize small with the first element of unsorted part of the array p=i;
// keep index of the smallest number of unsorted part of the array in p
65
for(j=i+1; j<n; j++) //loop for selecting the smallest element form unsorted array
{if(a[j]<small)
{small=a[j]; p=j;
}
}// end of inner loop---------//----------exchange the smallest element with ith element------------- a[p]=a[i];
a[i]=small;
//-----------end of exchange------------}
}//end of function void
main( )
{int a[7]={8,5,9,3,16,4,7},n=7,i;
cout<<\n Original array is :\n; for(i=0;i<n;i++)
cout<<a[i]<<, ;
select_sort(a,n);
cout<<\nThe sorted array is:\n;
for(i=0; i<n; i++)
cout<<a[i]<<, ;
}
Output is Original
array is 8, 5, 9, 3,
16, 4, 7
The sorted array is
3, 4, 5, 7, 8, 9, 16
Insertion Sort
Insertion sort algorithm divides the array of n elements in to two subparts, the first subpart contain a[0] to
a[k] elements in sorted order and the second subpart contain a[k+1] to a[n] which are to be sorted. The
algorithm starts with only first element in the sorted subpart because array of one element is itself in
sorted order. In each pass, the first element of the unsorted subpart is removed and is inserted at the
appropriate position in the sorted array so that the sorted array remain in sorted order and hence in each
pass the size of the sorted subpart is increased by 1 and size of unsorted subpart is decreased by 1. This
process continues until all n-1 elements of the unsorted arrays are inserted at their appropriate position in
the sorted array.
For example, consider the following unsorted array to be sorted using selection sort
Original array
0
1
2
3
4
5
6
5
9
3
16
4
7
8
Sorted
unsorted
Initially the sorted subpart contains only one element i.e. 8 and the unsorted subpart contains n-1 elements
where n is the number of elements in the given array.
Iteration1: To insert first element of the unsorted subpart i.e. 5 into the sorted subpart, 5 is compared with
all elements of the sorted subpart starting from rightmost element to the leftmost element whose value
is greater than 5, shift all elements of the sorted subpart whose value is greater than 5 one position
towards right to create an empty place at the appropriate
66
position in the sorted array, store 5 at the created empty place, here 8 will move from position a[0] to
a[1] and a[0] is filled by 5. After first pass the status of the array is:
0
1
2
3
4
5
6
9
3
16
4
7
5
8
Sorted
unsorted
Iteration2:
In second pass 9 is the first element of the unsorted subpart, 9 is compared with 8, since 8 is
less than 9 so no shifting takes place and the comparing loop terminates. So the element 9 is added at the
rightmost end of the sorted subpart. After second pass the status of the array is:
0
1
2
3
4
5
6
3
16
4
7
5
8
9
Sorted
unsorted
Iteration3:
in third pass 3 is compared with 9, 8 and 5 and shift them one position towards right and
insert 3 at position a[0]. After third pass the status of the array is:
0
1
2
3
4
5
6
16
4
7
3
5
8
9
Sorted
unsorted
Iteration4:
in forth pass 16 is greater than the largest number of the sorted subpart so it remains at the
same position in the array. After fourth pass the status of the array is:
0
1
2
3
4
5
6
4
7
3
5
8
9
16
Sorted
Iteration5:
0
unsorted
in fifth pass 4 is inserted after 3. After third pass the status of the array is:
1
2
3
4
5
6
7
3
4
5
8
9
16
Sorted
Iteration6:
0
unsorted
in sixth pass 7 is inserted after 5. After fifth pass the status of the array is:
1
2
3
4
5
6
3
4
5
7
8
9
16
Sorted
Insertion sort take advantage of sorted(best case) or partially sorted(average case) array because if all
elements are at their right place then in each pass only one comparison is required to make sure that the
element is at its right position. So for n=7 only 6 (i.e. n-1) iterations are required and in each iteration only
one comparison is required i.e. total number of comparisons required= (n-1)=6 which is better than the
selection sort (for sorted array selection sort required n(n-1)/2 comparisons). Therefore insertion sort is
best suited for sorted or partially sorted arrays.
#include<iostream.h>
void insert_sort(int a[ ],int n) //n is the no of elements present in the array
{int i, j,p;
for (i=1; i<n; i++)
{p=a[i]; j=i-1;
//inner loop to shift all elements of sorted subpart one position towards right
while(j>=0&&a[j]>p)
{
a[j+1]=a[j]; j- -;
67
}
//---------end of inner loop
a[j+1]=p;
//insert p in the sorted subpart
}
}
void main( )
{
int a[7]={8,5,9,3,16,4,7},n=7,i;
cout<<\n Original array is :\n; for(i=0;i<n;i++)
cout<<a[i]<<, ;
insert_sort(a,n);
cout<<\nThe sorted array is:\n;
for(i=0; i<n; i++)
cout<<a[i]<<, ;
}
Output is Original
array is 8, 5, 9, 3,
16, 4, 7
The sorted array is 3,
4, 5, 7, 8, 9, 16
Merging of two sorted arrays into third array in sorted order
Algorithm to merge arrays a[m](sorted in ascending order) and b[n](sorted in descending order) into third
array C[n+m] in ascending order.
#include<iostream.h>
Merge(int a[ ], int m, int b[n], int c[ ])// m is size of array a and n is the size of array b
{int i=0; // i points to the smallest element of the array a which is at index 0
int j=n-1;// j points to the smallest element of the array b which is at the index m-1 since b is
// sortet in descending order
int k=0; //k points to the first element of the array c while(i<m&&j>=0)
{if(a[i]<b[j])
c[k++]=a[i++]; // copy from array a into array c and then increment i and k
else
c[k++]=b[j--]; // copy from array b into array c and then decrement j and increment k
68
}
while(i<m)
//copy all remaining elements of array a
c[k++]=a[i++];
while(j>=0)
//copy all remaining elements of array b
c[k++]=b[j--];
}
void main()
{int a[5]={2,4,5,6,7},m=5; //a is in ascending order
int b[6]={15,12,4,3,2,1},n=6; //b is in descending order int
c[11];
merge(a, m, b, n, c);
cout<<The merged array is :\n;
for(int i=0; i<m+n; i++)
cout<<c[i]<, ;
}
Output is
The merged array is:
1, 2, 2, 3, 4, 4, 5, 6, 7, 12, 15
Two dimensional arrays
In computing, row-major order and column-major order describe methods for storing multidimensional
arrays in linear memory. Following standard matrix notation, rows are identified by the first index of a
two-dimensional array and columns by the second index. Array layout is critical for correctly passing
arrays between programs written in different languages. Row-major order is used in C, C++; columnmajor order is used in Fortran and MATLAB.
Row-major order
In row-major storage, a multidimensional array in linear memory is accessed such that rows are stored one
after the other. When using row-major order, the difference between addresses of array cells in increasing
rows is larger than addresses of cells in increasing columns. For example, consider this 23 array:
An array declared in C as
int A[2][3] = { {1, 2, 3}, {4, 5, 6} };
would be laid out contiguously in linear memory as:
1 2 3 4 5 6
To traverse this array in the order in which it is laid out in memory, one would use the following nested
loop:
for (i = 0; i < 2; i++) for
(j = 0; j < 3; j++)
cout<<A[i][j];
The difference in offset from one column to the next is 1*sizeof(type) and from one row to the next is
3*sizeof(type). The linear offset from the beginning of the array to any given element A[row][column]
can then be computed as:
offset = row*NUMCOLS + column
Address of element A[row][column] can be computed as:
Example 1.
For a given array A[10][20] is stored in the memory along the row with each of its elements occupying 4
bytes. Calculate address of A[3][5] if the base address of array A is 5000. Solution:
For given array A[M][N] where M=Number of rows, N =Number of Columns present in the array
address of A[I][J]= base address+(I * N + J)*sizeof(type)
here M=10, N=20, I=3, J=5, sizeof(type)=4 bytes
address of A[3][5]
= 5000 + (3 * 20 + 5) * 4
= 5000 + 65*4=5000+260=5260
Example 2.
An array A[50][20] is stored in the memory along the row with each of its elements occupying 8 bytes.
Find out the location of A[5][10], if A[4][5] is stored at 4000.
Solution:
Calculate base address of A i.e. address of A[0][0]
For given array A[M][N] where M=Number of rows, N =Number of Columns present in the array
address of A[I][J]= base address+(I * N + J)*sizeof(type)
here M=50, N=20, sizeof(type)=8, I=4, J=5 address
of A[4][5]
= base address + (4*20 +5)*8
4000 = base address + 85*8
Base address= 4000-85*8= 4000-680=3320 Now to find address
of A[5][10]
here M=50, N=20, sizeof(type)=8, I=5, J=10 Address
of A[5][10]
= base address +(5*20 + 10)*8
=3320 + 110*8 = 3320+880 = 4200
As C, C++ supports n dimensional arrays along the row, the address calculation formula can be
generalized for n dimensional array as:
For 3 dimentional array A[m][n][p], find address of a[i][j][k]:
Address of a[i][j][k] = base address + ( (I * n + j ) * p + k ) * sizeof(type)
For 4 dimentional array A[m][n][p][q], find address of a[i][j][k][l]:
Address of a[i][j][k][l] = base address + ( ( (I * n + j ) * p + k ) * p + l ) * sizeof(type)
Column-major order is a similar method of flattening arrays onto linear memory, but the columns are
listed in sequence. The programming languages Fortran, MATLAB, use column-major ordering.
The array
if stored contiguously in linear memory with column-major order would look like the following: 1
4 2 5 3 6
The memory offset could then be computed as:
offset = row + column*NUMROWS
Address of element A[row][column] can be computed as:
Address of A[row][column]=base address of A + (column*NUMROWS +rows)* sizeof (type)
Where NUMROWS represents the number of rows in the array in this case, 2.
Treating a row-major array as a column-major array is the same as transposing it. Because performing a
transpose requires data movement, and is quite difficult to do in-place for non-square matrices, such
transpositions are rarely performed explicitly. For example, software libraries for linear algebra, such as
the BLAS, typically provide options to specify that certain matrices are to be interpreted in transposed
order to avoid the necessity of data movement
Example1.
For a given array A[10][20] is stored in the memory along the column with each of its elements occupying
4 bytes. Calculate address of A[3][5] if the base address of array A is 5000. Solution:
For given array A[M][N] where M=Number of rows, N =Number of Columns present in the array
Address of A[I][J]= base address + (J * M + I)*sizeof(type)
here M=10, N=20, I=3, J=5, sizeof(type)=4 bytes
Address of A[3][5] = 5000 + (5 * 10 + 3) * 4
= 5000 + 53*4 = 5000+215 =5215
Example2.
An array A[50][20] is stored in the memory along the column with each of its elements occupying 8 bytes.
Find out the location of A[5][10], if A[4][5] is stored at 4000.
Solution:
Calculate base address of A i.e. address of A[0][0]
For given array A[M][N] where M=Number of rows, N =Number of Columns present in the array address
of A[I][J]= base address+(J * M + I)*sizeof(type)
here M=50, N=20, sizeof(type)=8, I=4, J=5
address of A[4][5]
= base address + (5 * 50 +4)*8
4000
= base address + 254*8
Base address= 4000-55*8= 4000-2032=1968 Now to find address
of A[5][10]
here M=50, N=20, sizeof(type)=8, I =5, J=10 Address
of A[5][10]
= base address +(10*50 + 10)*8
=1968 + 510*8 = 1968+4080 = 6048
4 Marks Questions
Write a function in C++ which accepts an integer array and its size as arguments and replaces elements
having even values with its half and elements having odd values with twice its value
Write a function in C++ which accepts an integer array and its size as argument and exchanges the
value of first half side elements with the second half side elements of the array.
Example: If an array of eight elements has initial content as 2,4,1,6,7,9,23,10. The function should
rearrange the array as 7,9,23,10,2,4,1,6.
Write a function in c++ to find and display the sum of each row and each column of 2 dimensional
array. Use the array and its size as parameters with int as the data type of the array.
Write a function in C++, which accepts an integer array and its size as parameters and rearrange the
array in reverse. Example if an array of five members initially contains the elements as 6,7,8,13,9,19
Then the function should rearrange the array as 19,9,13,8,7,6
Write a function in C++, which accept an integer array and its size as arguments and swap the elements of
every even location with its following odd location. Example : if an array of nine elements initially
contains the elements as 2,4,1,6,5,7,9,23,10 Then the function should rearrange the array as
4,2,6,1,7,5,23,9,10
Write a function in C++ which accepts an integer array and its size as arguments and replaces elements
having odd values with thrice and elements having even values with twice its value. Example: If an array
of five elements initially contains the elements 3,4,5,16,9
Then the function should rearrange the content of the array as 9,8,15,32,27
74
Output is 5
3
Stack is empty -1
In the above program the statement stack s1 creates s1 as an empty stack and the constructor initialize top by
-1.
Initially stack is empty
stack after s1.push(3)
stack after s1.push(5)
4
4
4
3
3
3
2
2
2
1
1
5
top
1
0
3
top
0
3
0
top -1
After first s1.pop() statement, the item 5 is removed from the stack and top moves from 1 to 0
top
4
3
2
1
0
After second s1.pop() statement, the item 3 is removed from stack and top moves from 0 to -1 which
indicates that now stack is empty.
4
3
2
1
0
top
-1
After third s1.pop() statement the pop function display error message stack is empty and returns -1 to
indicating that stack is empty and do not change the position of top of the stack.
Linked list
In Computer Science, a linked list (or more clearly, "singly-linked list") is a data structure that consists of
a sequence of nodes each of which contains data and a pointer which points (i.e., a link) to the next node
in the sequence.
A linked list whose nodes contain two fields: an integer value and a link to the next node
The main benefit of a linked list over a conventional array is that the list elements can easily be added or
removed without reallocation or reorganization of the entire structure because the data items need not be
stored contiguously in memory or on disk .Stack using linked lists allow insertion and removal of nodes
only at the position where the pointer top is pointing to.
Stack implementation using linked list
#include<iostream.h>
struct node
75
{
int item; //data that will be stored in each node
node * next; //pointer which contains address of another node
}; //node is a self referential structure which contains reference of another object type node
class stack
{node *top; public:
stack() //constructor to create an empty stack by initializing top with NULL
{ top=NULL; }
void push(int item); int
pop();
~stack();
};
void stack::push(int item) //to insert a new node at the top of the stack
{node *t=new node; //dynamic memory allocation for a new object of node type if(t==NULL)
cout<<Memory not available, stack is full;
else
{t->item=item;
t->next=top; //newly created node will point to the last inserted node or NULL if
//stack is empty
top=t;
//top will point to the newly created node
}
}
int stack::pop()//to delete the last inserted node(which is currently pointed by the top)
{if(top==NULL)
{cout<<Stack is empty \n;
return 0; // 0 indicating that stack is empty
}
else
{node *t=top; //save the address of top in t
int r=top->item; //store item of the node currently pointed by top
top=top->next; // move top from last node to the second last node
delete t; //remove last node of the stack from memory
return r;
}
}
stack::~stack() //de-allocated all undeleted nodes of the stack when stack goes out of scope
{node *t; while(top!=NULL)
{t=top; top=top->next; delete
t;
}
};
void main()
{
76
NULL
NULL
NULL
After the first s1.pop() statement the node currently pointed by top (i.e. node containing 7) is deleted from
the stack, after deletion the status of stack is
top
NULL
After the second s1.pop() statement the node currently pointed by top (i.e. node containing 5) is deleted
from the stack, after deletion the status of stack is
top 3
NULL
After the third s1.pop() statement the node currently pointed by top (i.e. node containing 3) is deleted from
the stack, after deletion the stack become empty i.e.
Top
NULL
After the fourth s1.pop() statement, the error message stack is empty displayed and the pop() function
return 0 to indicate that stack is empty.
77
78
(
A
+
B
)
*
(
C
D
)
/
E
)
Postfix expression
A
A
AB
AB+
AB+
AB+
AB+C
AB+C
AB+CD
AB+CDAB+CD-*
AB+CD-*E
AB+CD-*E/
79
token
scanned
postfix expression
8
2
+
5
3
-
10, 5
10, 5, 3
10, 2
20
4
/
20, 4
5
NULL
Final result 5
Operation performed
Push 8
Push 2
Op2=pop() i.e 2
Op1=pop() i.e 8
Push(op1+op2) i.e. 8+2
Push(5)
Push(3)
Op2=pop() i.e. 3
Op1=pop() i.e. 5
Push(op1-op2) i.e. 5-3
Op2=pop() i.e. 2
Op1=pop() i.e. 10
Push(op1-op2) i.e. 10*2
Push 4
Op2=pop() i.e. 4
Op1=pop() i.e. 20
Push(op1/op2) i.e. 20/4
Pop 5 and return 5
Evaluate the following Boolean postfix expression showing stack status after every step
True, False, True, AND, OR, False, NOT, AND
token scanned Stack status ( bold letter
from
postfix shows the top of the
expression
stack) after processing the
scanned token
True
True
False
True, False
True
True, False, True
AND
True, False
OR
True
False
NOT
True, False
True, True
AND
True
NULL
Operation performed
Push True
Push False
Push True
Op2=pop() i.e. True
Op1=pop() i.e. False
Push(Op2
AND Op1) i.e. False AND
True=False
Op2=pop() i.e. False
Op1=pop() i.e. True
Push(Op2 OR Op1) i.e. True OR False=True
Push False
Op1=pop() i.e. False
Push(NOT False) i.e. NOT False=True
Op2=pop() i.e. True
Op1=pop() i.e. True
Push(Op2
AND Op1) i.e. True AND
True=True
Pop True and Return True
QUEUE
Queue is a linear data structure which follows First In First Out (FIFO) rule in which a new item is added
at the rear end and deletion of item is from the front end of the queue. In a FIFO data structure, the first
element added to the queue will be the first one to be removed.
Linear Queue implementation using Array
#include<iostream.h>
const int size=5;
class queue
{int front , rear;
int a[size]; public:
queue(){front=0;rear=0;} //Constructor to create an empty queue void
addQ()
{ if(rear==size)
cout<<queue is full<<endl;
else
a[rear++]=item;
}
int delQ()
{if(front==rear)
{cout<<queue is empty<<endl; return 0;}
else
return a[front++];
}}
void main()
{queue q1; q1.addQ(3);
q1.addQ(5) ;
q1.addQ(7) ;
cout<<q1.delQ()<<endl ;
cout<<q1.delQ()<<endl ;
cout<<q1.delQ()<<endl;
cout<<q1.delQ()<<endl;
}
Output is 3
5
7
Queue is empty
0
In the above program the statement queue q1 creates an empty queue q1.
Front
a[0]
Rear
Rear
After execution of the statement q1.addQ(7), status of queue is Front
a[0] a[1] a[2] a[3] a[4]
3
5
7
Rear
After execution of the first cout<<q1.delQ() statement, 3 is deleted from queue status of queue is
Front
a[0]
Rear
After execution of the second cout<<q1.delQ() statement, 5 is deleted from the queue status of queue is
Front
a[0]
3
Rear
After execution of the third cout<<q1.delQ() statement, 7 is deleted from the queue. The status of queue is
empty
Front
a[0]
3
Rear
After execution of the fourth cout<<q1.delQ() statement, the message queue is empty displayed and
status of queue is
Front
a[0]
83
Output is 3
5
7
Queue is empty
0
In the above program the statement queue q1; invokes the constructor queue() which create an empty
queue object q1 and initialize front and rear with NULL.
front
NULL
rear
After statement q1.addQ(3) the stack become
front
NULL
3
rear
After statement q1.addQ(5) the stack become
front 3
5
rear
NULL
7 NULL
rear
After the first q1.delQ() statement the node currently pointed by front (i.e. node containing 3) is deleted
from the queue, after deletion the status of queue is
front
5
NULL
rear
After the second q1.delQ() statement the node currently pointed by front (i.e. node containing 5) is deleted
from the queue, after deletion the status of queue is
front 7
NULL
rear
After the third q1.delQ() statement the node currently pointed by front (i.e. node containing 7) is deleted
from the queue, after deletion the queue become empty therefore NULL is a assigned to both rear and
front
Front=rear= NULL ;
After the fourth q1.delQ() statement, the error message queue is empty displayed and the pop() function
return 0 to indicate that queue is empty.
Evaluate the following postfix expression E given below; show the contents of the stack during the
evaluation
1. E= 5,9,+2,/,4,1,1,3,_,*,+
2
2. E= 80,35,20,-,25,5,+,-,*
3. E= 30,5,2,^,12,6,/,+,4. E=15, 3, 2, +, /, 7, + 2, *
An array A[40][10] is stored in the memory along the column with each element occupying 4 bytes.
Find out the address of the location A[3][6] if the location A[30][10] is stored at the address 9000. 3
4 Define functions in C++ to perform a PUSH and POP operation in a dynamically allocated stack
considering the following :
4
struct Node
{ int X,Y; Node *Link;
}; class STACK
{ Node * Top; public:
STACK( ) { TOP=NULL;}
void PUSH( ); void POP( );
~STACK( );
};
Write a function in C++ to perform a Add and Delete operation in a dynamically allocated Queue
considering the following:
4
struct node
{ int empno ;char name[20] ;float sal ; Node *Link;
};
as
e.g.rollno,name (student)
Union Operation : Two relation are said to be union compatible if their degree and column are same.
e.g Relation A
Relation B
Resultant Relation A U B =
90
Cartesian product: Cartesian Product of two relation A and B gives resultant relation whose no. of column
are sum of degrees of two relation and no. of rows are product of cardinality of two relations.
e.g Relation A
Relation A
Resultant Relation
Relation B
AB
NUMBER
Used to store a numeric value in a field/column. It may be decimal, integer or a real value. General syntax
is
Number(n,d)
Where n specifies the number of digits and d specifies the number of digits to the right of the decimal
point.
e.g
marks number(3)
declares marks to be of type number with maximum value 999.
pct number(5,2)
declares pct to be of type number of 5 digits with two digits to the right of
decimal point.
CHAR
Used to store character type data in a column. General syntax is
Char (size)
where size represents the maximum number of characters in a column. The CHAR type data can hold at most
255 characters.
e.g
name char(25)
declares a data item name of type character of upto 25 size long.
VARCHAR/VARCHAR2
This data type is used to store variable length alphanumeric data. General syntax is
varchar(size) / varchar2(size)
where size represents the maximum number of characters in a column. The maximum allowed size in this
data type is 2000 characters.
e.g
address varchar(50); address is of type varchar of upto 50 characters long.
4.
DATE
Date data type is used to store dates in columns. SQL supports the various date formats other that the
standard DD-MON-YY.
e.g
dob date;
declares dob to be of type date.
SQL Commands
CREATE TABLE Command
Create table command is used to create a table in SQL. It is a DDL type of command.
Syntax :
CREATE TABLE <table name>
( <column name> <data types>[(size)] [,<column name> <data types>[(size)].);
e.g.
Create table student (rollno
number(2), name varchar2(20), dob
date);
Constraints:
Constraints are the conditions that can be enforced on the attributes of a relation. The constraints come in
play when ever we try to insert, delete or update a record in a relation.They are used to ensure integrity of a
relation, hence named as integrity constraints.
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
Not Null constraint : It ensures that the column cannot contain a NULL value.
Unique constraint : A candidate key is a combination of one or more columns, the value of which
uniquely identifies each row of a table.
Primary Key : It ensures two things : (i) Unique identification of each row in the table. (ii) No column
that is part of the Primary Key constraint can contain a NULL value.
Foreign Key : The foreign key designates a column or combination of columns as a foreign key and
establishes its relationship with a primary key in different table.
Create table Fee
(RollNo number(2) Foreign key (Rollno) references Student (Rollno),
Name varchar2(20) Not null, Amount
number(4), Fee_Date date);
Check Constraint : Sometimes we may require that values in some of the columns of
our table are to be within a certain range or they must satisfy
conditions. Example:
Create table Employee
(EmpNo number(4) Primary Key,
Name varchar2(20) Not Null,
Salary number(6,2) check (salary > 0),
DeptNo number(3)
);
NOTE:- In SQL we can repeat or re-execute the last command typed at SQL prompt by typing / key
and pressing enter.
Roll_no Name
Class Marks City
101
Rohan
XI
400
Jammu
102
Aneeta Chopra
XII
390
Udhampur
103
Pawan Kumar
IX
298
Amritsar
104
Rohan
IX
376
Jammu
105
Sanjay
VII
240
Gurdaspur
113
Anju Mahajan
VIII
432
Pathankot
Operators in SQL:
The following are the commonly used operators in SQL
1. Arithmetic Operators
+, -, *, /
2. Relational Operators
=, <, >, <=, >=, <>
3. Logical Operators
OR, AND, NOT
Arithmetic operators are used to perform simple arithmetic operations. Relational
Operators are used when two values are to be compared and
Logical operators are used to connect search conditions in the WHERE Clause in SQL. Other
operators :
Range check between low and high
List check in
Pattern check like , not like ( % and _ under score is used)
Queries:
To retrieve information from a database we can query the databases. SQL SELECT statement is used to
select rows and columns from a database/relation.
SELECT Command
This command can perform selection as well as projection.
Selection:
This capability of SQL can return you the tuples form a relation with all the attributes.
e.g. SELECT name, class FROM student;
The above command displays only name and class attributes from student table.
Projection:
This is the capability of SQL to return only specific attributes in the relation. Use of where
clause is required when specific tuples are to be fetched or manipulated.
e.g
SELECT * FROM student; command will display all the tuples in the relation student SELECT
FROM student WHERE Roll_no <=102;
The above command display only those records whose Roll_no less than or equal to 102. Select
command can also display specific attributes from a relation.
SELECT count(*) AS Total Number of Records FROM student;
Display the total number of records with title as Total Number of Records i.e an alias
We can also use arithmetic operators in select statement, like
SELECT Roll_no, name, marks+20 FROM student;
SELECT name, (marks/500)*100 FROM student WHERE Roll_no > 103;
Eliminating Duplicate/Redundant data
DISTINCT keyword is used to restrict the duplicate rows from the results of a SELECT statement.
e.g.
SELECT DISTINCT name FROM student;
91
SQL Functions :
SQL supports functions which can be used to compute and select numeric, character and date
columns of a relations. These functions can be applied on a group of rows. The rows are grouped on a
common value of a column in the table. These functions return only one value for a group and
therefore, they are called aggregate or group functions.
SUM() :
It returns the sum of values of numeric type of a column.
Eg.
Select sum(salary) from employee;
AVG() :
It returns the average of values of numeric type of a column.
92
Eg.
Select avg(salary) from employee;
MIN() :
It returns the minimum of the values of a column of a given relation.
Eg.
Select min(salary) from employee;
MAX() :
It returns the maximum of the values of a column of a given relation.
Eg.
Select max(salary) from employee;
COUNT():
It returns the number of rows in a relation.
Eg.
Group By Clause :
The rows of a table can be grouped together based on a common value by using the Group By clause of
SQL in a select statement.
Syntax :
SELECT <attribute name>, <attribute name> ---- [functions] FROM
<relation name>
GROUP BY <group by column>; Eg.
Select age, count (rollno)
From
students
Group
by
age;
Output :Age
Count(rollno)
15
2
14.5
2
14
5
Group-By-Having Clause :
It is used to apply some condition to the Group By clause. Eg.
Select class
From students Group by class
Having count(*) > 5;
DELETE Command
To delete the record from a table SQL provides a delete statement. General syntax is:DELETE FROM <table_name> [WHERE <condition>];
e.g. DELETE FROM student WHERE city = Jammu;
This command deletes all those records whose city is Jammu.
NOTE: It should be kept in mind that while comparing with the string type values lowercase
and uppercase letters are treated as different. That is Jammu and jammu is different while
comparing.
UPDATE Command
To update the data stored in the data base, UPDATE command is used.
e. g.
UPDATE student SET marks = marks + 100;
Increase marks of all the students by 100.
93
e. g.
UPDATE student SET City = Udhampur WHERE city = Jammu;
changes the city of those students to Udhampur whose city is Jammu.
We can also update multiple columns with update command, like
e. g.
UPDATE student set marks = marks + 20, city =
Jalandhar WHERE city NOT IN (Jammu,Udhampur);
CREATE VIEW Command
In SQL we can create a view of the already existing table that contains specific attributes of the table.
e. g. the table student that we created contains following fields: Student
(Roll_no, Name, Marks, Class, City)
Suppose we need to create a view v_student that contains Roll_no,name and class of student table, then
Create View command can be used:
CREATE VIEW v_student AS SELECT Roll_no, Name, Class FROM student;
The above command create a virtual table (view) named v_student that has three attributes as mentioned
and all the rows under those attributes as in student table.
We can also create a view from an existing table based on some specific conditions, like
CREATE VIEW v_student AS SELECT Roll_no, Name, Class FROM student WHERE City <>Jammu;
The main difference between a Table and view is that
A Table is a repository of data. The table resides physically in the database.
A View is not a part of the database's physical representation. It is created on a table or another view. It is
precompiled, so that data retrieval behaves faster, and also provides a secure accessibility mechanism.
ALTER TABLE Command
In SQL if we ever need to change the structure of the database then ALTER TABLE command is used. By
using this command we can add a column in the existing table, delete a column from a table or modify
columns in a table.
Adding a column : The syntax to add a column is:ALTER TABLE table_name
ADD column_name datatype;
e.g
ALTER TABLE student ADD(Address varchar(30));
The above command add a column Address to the table student.
If we give command
SELECT * FROM student;
The following data gets displayed on screen:
Roll_no
Name
Class
Marks
City
101
Rohan
XI
400
Jammu
102
Aneeta Chopra
XII
390
Udhampur
103
Pawan Kumar
IX
298
Amritsar
104
Rohan
IX
376
Jammu
105
Sanjay
VII
240
Gurdaspur
113
Anju MAhajan
VIII
432
Pathankot
Address
94
Note that we have just added a column and there will be no data under this attribute. UPDATE
command can be used to supply values / data to this column.
Removing a column
ALTER TABLE table_name DROP
COLUMN column_name;
e.g
ALTER TABLE Student
DROP COLUMN Address;
The column Address will be removed from the table student.
Modifying Table Structure
ALTER TABLE table_name
MODIFY (column_name new datatype new size)
e.g
ALTER TABLE Student MODIFY Address varchar(50);
The size of column Address will be modified to new size 50
DROP TABLE Command
Sometimes you may need to drop a table which is not in use. DROP TABLE command is used to
Delete / drop a table permanently. It should be kept in mind that we cannot drop a table if it contains
records. That is first all the rows of the table have to be deleted and only then the table can be dropped.
The general syntax of this command is:DROP TABLE <table_name>;
DROP TABLE student;
This command will remove the table student
relationships existing among data. At this level the database is described logically in terms of
simple data-structures.
Primary Key
Ans : It is a key/attribute or a set of attributes that can uniquely identify tuples within the relation.
Candidate Key
Ans : All attributes combinations inside a relation that can serve as primary key are candidate key
as they are candidates for being as a primary key or a part of it.
Relational Algebra
Ans : It is the collections of rules and operations on relations(tables). The various operations are
selection, projection, Cartesian product, union, set difference and intersection, and joining of
relations.
Domain
Ans : it is the pool or collection of data from which the actual values appearing in a given column
are drawn.
Sol :
SELECT NAME from GRADUATE where DIV = I order by NAME;
SELECT NAME,STIPEND,SUBJECT, STIPEND*12 from GRADUATE;
SELECT SUBJECT,COUNT(*) from GRADUATE group by SUBJECT
having SUBJECT=PHYISCS or SUBJECT=COMPUTER SC;
INSERT INTO GRADUATE values(11,KAJOL,300,COMPUTER SC,75,1);
i) 63
800
475
4
Consider the following tables Sender and Recipient. Write SQL commands for the statements (i) to
and give the outputs for SQL queries (v) to (viii).
RecAddress
116, A Vihar
13, BID, Mayur Vihar
RecID
RecName ND08 S Mahajan ND48
Tripathi
Write SQL command for (i) to (vii) on the basis of the table SPORTS
Table: SPORTS
Student
NO
10
11
12
13
14
15
Class
Name
Game1
Grade Game2
Grade2
7
8
7
7
9
10
Sammer
Sujit
Kamal
Venna
Archana
Arpit
Cricket
Tennis
Swimming
Tennis
Basketball
Cricket
B
A
B
C
A
A
A
C
B
A
A
C
Swimming
Skating
Football
Tennis
Cricket
Atheletics
Display the names of the students who have grade C in either Game1 or Game2 or both.
Display the number of students getting grade A in Cricket.
Display the names of the students who have same game for both Game1 and Game2.
Display the games taken up by the students, whose name starts with A.
Add a new column named Marks.
Assign a value 200 for Marks for all those who are getting grade B or grade A in both Game1
and Game2.
Ans : a)
SELECT Name from SPORTS where grade=C or Grade2=C;
SELECT Count(*) from SPORTS where grade=A;
SELECT name from SPORTS where game1 = game2;
SELECT game,game2 from SPORTS where name like A%;
ALTER TABLE SPORTS add (marks int(4));
UPDATE SPORTS set marks=200 where grade=A;
4. Consider the following tables Stationary and Consumer. Write SQL commands for the statement (i) to
(iv) and output for SQL queries (v) to (viii):
S_ID
Table: Stationary
StationaryName
Compan
y
Price
100
DP01
PL02
ER05
PL01
GP02
Dot Pen
Pencil
Eraser
Pencil
Gel Pen
Table: Consumer
C_I
ConsumerName
D
01
Good Learner
06
Write Well
12
Topper
15
Write & Draw
16
Motivation
ABC
XYZ
XYZ
CAM
ABC
10
6
7
5
15
Addres
s
Delhi
Mumbai
Delhi
Delhi
Banglore
S_ID
PL01
GP02
DP01
PL02
PL01
GCODE
10023
10001
10012
10024
10090
10019
10009
10007
10020
10089
FCODE
F04
F02
F03
F01
Table : GARMENT
DESCRIPTION
PRICE
PENCIL
SKIRT
1150
FORMAL
SHIRT
1250
INFORMAL SHIRT
1550
BABY
TOP
750
TULIP
SKIRT
850
EVENING
GOWN
850
INFORMAL PANT
1500
FORMAL
PANT
1350
FROCK
850
SLACKS
750
FCODE
F03
F01
F02
F03
F02
F03
F02
F01
F04
F03
READYDATE
19DEC08
12JAN08
06JUN08
07APR07
31MAR07
06JUN08
20OCT08
09MAR08
09SEP07
20OCT08
Table : FABRIC
TYPE
POLYSTER
COTTON
SILK
TERELENE
To display the average PRICE of all the GARMENTs, which are made up of FABRIC with
FCODE as F03.
To display FABRIC wise highest and lowest price of GARMENTs from DRESS table.
(Display FCODE of each GARMENT along with highest and lowest price)
(v) SELECT SUM (PRICE) FROM GARMENT WHERE FCODE= F01;
SELECT DESCRIPTION, TYPE FROM GARMENT, FABRIC WHERE
GARMENT.FCODE = FABRIC. FCODE AND GARMENT. PRICE>=1260;
SELECT MAX (FCODE) FROM FABRIC;
SELECT COUNT (DISTINCT PRICE) FROM FABRIC;
Consider the following WORKERS and DESIG. Write SQL commands for the statements (i) to (iv) and
give outputs for SQL queries (v) to (vi)
WORKERS
W_ID FIRSTNAME LASTNAME ADDRESS
CITY
102
Sam
Tones
33 Elm St.
Paris
105
Sarah
Ackerman
440 U.S. 110
New York
144
Manila
Sengupta
24 Friends Street New Delhi
210
George
Smith
83 First Street
Howard
255
Mary
Jones
842 Vine Ave.
Losantiville
300
Robert
Samuel
9 Fifth Cross
Washington
335
Henry
Williams
12Moore Street
Boston
403
Ronny
Lee
121 Harrison St.
New York
451
Pat
Thompson
11 Red Road
Paris
DESIG
W_ID SALARY
BENEFITS
102
105
144
210
255
300
335
403
451
15000
25000
15000
12500
12000
10000
10000
7500
7500
75000
85000
70000
75000
50000
45000
40000
32000
28000
DESIGNATI
ON
Manager
Director
Manager
Manager
Clerk
Clerk
Clerk
Salesman
Salesman
100
101
Truth table:
X
0
0
1
1
Y
0
1
0
1
X.Y
0
0
0
1
gate
AND gate
The output Q is true if input A AND input B are both
true: Q = A AND B An AND gate can have two or more
inputs, its output is true if all inputs are true.
OR gate
The output Q is true if input A OR input B is true (or
both of them are true): Q = A OR B
An OR gate can have two or more inputs, its output is true
if at least one input is true.
0
0
1
1
+
+
+
+
0
1
0
1
=
=
=
=
0
1
1
1
102
0.0 = 0
0.1 = 0
1.0 = 0
1.1 = 1
Complement Rules
0 1, 1 0
Principal of Duality
This principal states that we can derive a Boolean relation from another Boolean relation by
performing simple steps. The steps are:Change each AND(.) with an OR(+) sign
Change each OR(+) with an AND(.) sign
Replace each 0 with 1 and each 1 with 0
e.g
0+0=0
1+0=1
then dual is
then dual is
1.1=1
0.1=0
103
104
Minimization of Boolean expressions:After obtaining SOP and POS expressions, the next step is to simplify the Boolean expression.
There are two methods of simplification of Boolean expressions.
Algebraic Method
Karnaugh Map :
Algebraic method:This method makes use of Boolean postulates, rules and theorems to simplify the
expression.
Example No. 1: Reduce the expression XY X XY.
105
106
Remember, group together adjacent cells of 1s, to form largest possible rectangles of sizes that are
powers of 2. Notice that you can overlap the blocks if necessary.
Sum Of Products Reduction using K- Map
For reducing the expression first mark Octet, Quad, Pair then single.
Pair: Two adjacent 1s makes a pair.
Quad: Four adjacent 1s makes a quad.
Octet: Eight adjacent 1s makes an Octet.
Pair removes one variable.
Quad removes two variables.
Octet removes three variables.
Reduction of expression: When moving vertically or horizontally in pair or a quad or an octet it can be
observed that only one variable gets changed that can be eliminated directly in the expression.
For Example
In the above Ex
Step 1 : In K Map while moving from m7 to m15 the variable A is changing its state Hence it can be
removed directly, the solution becomes B.CD = BCD. This can be continued for all the pairs, Quads, and
Octets.
107
Step 2 : In K map while moving from m0 to m8 and m2 to m10 the variable A is changing its state. Hence B
can be taken similarly while moving from m0 to m2 and m8 to m10 the variable C is changing its state. Hence
D can be taken; the solution becomes B.D
The solution for above expression using K map is BCD + BD. Example1:
Reduce the following Boolean expression using K-Map:
F(P,Q,R,S)=(0,3,5,6,7,11,12,15)
Soln:
This is 1 quad, 2pairs & 2 lock
Quad(m3+m7+m15+m11) reduces to RS Pair(m5+m7)
reduces to PQS
Pair (m7+m6) reduces to PQR
Block m0=PQRS M12=PQRS
hence the final expressions is F=RS + PQS + PQR + PQRS + PQRS Example2:
Reduce the following Boolean expression using K-Map:
F(A,B,C,D)=(0,1,3,5,6,7,10,14,15)
Soln:
Reduced expressions are as follows: For
pair 1, (A+B+C)
For pair 2, (A+C+D)
For Quad 1, (A+D) For
Quad 2, (B+C)
Hence final POS expression will be
More about Gates:
NAND gate (NAND = Not AND)
This is an AND gate with the output inverted, as shown
by the 'o' on the output. The output is true if input A AND
input B are NOT both true: Q = NOT (A AND
A NAND gate can have two or more inputs, its
output is true if NOT all inputs are true.
NOR gate (NOR = Not OR)
This is an OR gate with the output inverted, as shown by
the 'o' on the output. The output Q is true if NOT inputs A
OR B are true: Q = NOT (A OR B) A NOR gate can have
two or more inputs, its output is true if no inputs are true.
Q = (A AND B) OR (NOT A AND NOT B) EX-NOR gates can only have 2 inputs.
Summary truth tables
The summary truth tables below show the output states for all types of 2-input and 3-input gates.
109
Ans.: AB+AB+BC
If F(P,Q,R,S) = (3,4,5,6,7,13,15) , obtain the simplified form using K-Map.
Ans.:
.
Reduction of groups following the reduction rule : Quad1
= M4.M5.M6.M7
= P+Q
Quad2 = M5.M7.M13.M15
= Q+S
Pair
= M3.M7
= P+R+S
Therefore POS of F(P,Q,R,S) = (P+Q)(Q+S)(P+R+S)
e) F(a,b,c,d)=(0,2,4,5,7,8,10,12,13,15)
F(a,b,c,d)=B1+B2+B3
B1=m0+m4+m12+m8==cd
B2=m5+m7+m13+m15=bd
B3=m0+m2+m8+m10=bd
F(a,b,c,d)=cd+bd+bd
Write the equivalent Boolean expression for the following logic circuit:
X
Y
Z
F
0 0
0
0
0 0
1
1
0 1
0
0
0 1
1
0
1 0
0
0
1 0
1
1
1 1
0
0
1 1
1
1
Express in the product of sums form, the Boolean function F(X,Y,Z), the truth table for which is
given below:
110
Write the equivalent Boolean Expression F for the following circuit diagram :
6 Write the equivalent Boolean Expression F for the following circuit diagram :
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)
Convert the following Boolean expression into its equivalent Canonical Product of Sum form (POS):
A.B.C + A.B.C +A.B.C
Write the equivalent Boolean Expression F for the following circuit diagram:
2
111
2
2
112
113
114
115
116
PAN (Personal Area Network): A Personal Area Network is computer network organized around an
individual person. It generally covers a range of less than 10 meters. Personal Area Networks can be
constructed with cables or wirelessly.
Network protocol
A protocol means the rules that are applicable for a network.
It defines the standardized format for data packets, techniques for detecting and correcting errors and so
on.
A protocol is a formal description of message formats and the rules that two or more machines must
follow to exchange those messages.
E.g. using library books.
Types of protocols are:
HTTP
FTP
TCP/IP
SLIP/PPP
Hypertext Transfer Protocol (HTTP) is a communications protocol for the transfer of information on
the intranet and the World Wide Web. HTTP is a request/response standard between a client and a
server. A client is the end-user; the server is the web site.
FTP (File Transfer Protocol) is the simplest and most secure way to exchange files over the Internet.
The objectives of FTP are:
To promote sharing of files (computer programs and/or data).
To encourage indirect or implicit use of remote computers.
To shield a user from variations in file storage systems among different hosts.
To transfer data reliably, and efficiently.
TCP/IP (Transmission Control Protocol / Internet Protocol)
TCP - is responsible for verifying the correct delivery of data from client to server. Data can be lost in
the intermediate network. TCP adds support to detect errors or lost data and to trigger retransmission until
the data is correctly and completely received.
IP - is responsible for moving packet of data from node to node. IP forwards each packet based on a four
byte destination address (the IP number). The Internet authorities assign ranges of numbers to different
organizations. The organizations assign groups of their numbers to departments. IP operates on gateway
machines that move data from department to organization to region and then around the world.
TelnetIt 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.
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.
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 any where the standard is supported. It uses
narrowband TDMA, which allows eight simultaneous calls on the same radio frequency.
CDMA(Code Division Multiple Access): it is a digital cellular technology that uses spreadspectrum techniques. CDMA does not assign a specific frequency to each user. Instead every channel uses
the full available spectrum.
120
General packet radio service (GPRS) is a packet oriented mobile data service on the 2G and 3G cellular
communication system's global system for mobile communications (GSM). GPRS usage is typically
charged based on volume of data transferred, contrasting with circuit switched data, which is usually billed
per minute of connection time.
1G n 2G: GPRS usage is typically charged based on volume of data transferred, contrasting with circuit
switched data, which is usually billed per minute of connection time.
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.
Email(Electronic Mail): Email is sending and receiving messages by computer.
Chat: Online textual talk in real time , is called Chatting. Internet Relay Chat (IRC) is a protocol for live
interactive Internet text.
Video Conferencing: a two way videophone conversation among multiple participants is called video
conferencing. The protocol used is Real-time Transport Protocol (RTP).
SMS(Short Message Service): SMS is the transmission of short text messages to and from a mobile
pone, fax machine and or IP address.
10.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.
EDGE(Enhanced Data rates for Global Evolution ) is a radio based high speed mobile data standard.
11.SMTP: Simple Mail Transfer Protocol (SMTP) is an Internet standard for electronic mail (e-mail)
transmission across Internet Protocol (IP) networks.
12. POP3: the Post Office Protocol (POP) is an application-layer Internet standard protocol used by
local e-mail clients to retrieve e-mail from a remote server over a TCP/IP connection.
13. Voice over IP (voice over Internet Protocol, VoIP) is a methodology and group of
technologies for the delivery of voice communications and multimedia sessions over Internet
Protocol (IP) networks, such as the Internet. Other terms commonly associated with VoIP are IP
telephony, Internet telephony, voice over broadband (VoBB), broadband telephony, IP
communications, and broadband phone service.
Network Security Concepts:
Viruses: Viruses are programs which replicate and attach to other programs in order to corrupt the
executable codes. Virus enters the computer system through an external source and become destructive.
Worms: Worms are also self- replicating programs that do not create multiple copies of itself on one
computer but propagate through the computer network. Worms log on to computer systems using the
username and passwords and exploit the system.
Trojan horse: - Though it is a useful program, however, a cracker can use it to intrude the computer
system in order to exploit the resources. Such a program can also enter into the computer through an email or free programs downloaded through the Internet.
Spams: Unwanted e-mail (usually of a commercial nature sent out in bulk)
Cookies: Cookies are the text messages sent by a web server to the web browser primarily for identifying
the user.
Firewall: A firewall is used to control the traffic between computer networks. It intercepts the packets
between the computer networks and allows only authorized packets to pass.
Cyber Law: Cyber law refers to all the legal and regulatory aspects of Internet and the World Wide Web.
Cyber Crimes: Cyber crime involves the usage of the computer system and the computer network for
criminal activity.
Hacking: Hacking is an unauthorized access to computer in order to exploit the resources.
Web Services:
WWW: The World Wide Web or W3 or simply the Web is a collection of linked documents or pages,
stored on millions of computers and distributed across the Internet.
121
HTML (Hyper Text Markup Language):- HTML is a computer language that describes the structure and
behavior of a web page. This language is used to create web pages.
XML (eXtensible Markup Language):- Extensible Markup Language (XML) is a meta language that helps
to describe the markup language.
HTTP (Hyper Text Transfer Protocol):- A protocol to transfer hypertext requests and information between
servers and browsers.
Domain Names: A domain name is a unique name that identifies a particular website and represents the
name of the server where the web pages reside.
URL:- The Uniform Resource Locator is a means to locate resources such as web pages on the Internet.
URL is also a method to address the web pages on the Internet. There are two types of URL, namely,
absolute URL and relative URL.
Website: A collection of related web pages stored on a web server is known as a website.
Web browser: A software application that enables to browse, search and collect information from the
Web is known as Web browser.
Web Servers: The web pages on the Internet are stored on the computers that are connected to the Internet.
These computers are known as web servers.
Web Hosting: - Web Hosting or website hosting is the service to host, store and maintain the websites on
the World Wide Web.
Web Scripting: - The process of creating and embedding scripts in a web page is known as Web
Scripting. Types of Scripts:Client Side Scripts: - Client side scripts supports interaction within a webpage. E.g. VB Script, Java
Script, PHP (PHPS Hypertext Preprocessor).
Server Side Scripts: - Server side scripting supports execution at server end. E.g. ASP, JSP, PHP
124
Knowledge Supplement Organisation has set up its new center at Mangalore for its office and web
based activities. It has 4 blocks of buildings as shown in the diagram below:
50 m
150 m
25 m
170 m
125 m
90 m
Number of Computers
Black A
25
Block B
50
Block C
125
Block D
10
Suggest a cable layout of connections between the blocks.
Suggest the most suitable place (i.e. block) to house the server of organisation with a suitable reason.
Suggest the placement of the following devices with justification
Repeater
Hub/Switch
The organization is planning to link its front office situated in the city in a hilly region where cable
connection is not feasible, suggest an economic way to connect it with reasonably high speed?
Ravya Industries has set up its new center at Kaka Nagar for its office and web based activities. The
company compound has 4 buildings as shown in the diagram below:
121
122
Production Unit
150
Finance Unit
35
Media Unit
10
Corporate Unit
30
Suggest the kind of network required (out of LAN,MAN,WAN) for connecting each of the following
office units:
Production Unit and Media Unit
Production Unit and Finance Unit
Which one of the following devices will you suggest for connecting all the computers within each of their
office units?
Switch/Hub
Modem
Telephone
Which of the following communication media, will you suggest to be procured by the company for
connecting their local offices in Chennai for very effective (High Speed) communication?
Ethernet cable
Optical fiber
Telephone cable
(iv) Suggest a cable/wiring layout for connecting the companys local office units located in Chennai.
Also, suggest an effective method/technology for connecting the companys office unit located in Delhi.
Answers: 4 Marks (Communication and Network Concepts)
(e1) (Any of the following option)
Layout Option 1
Layout Option 2
(e2) The most suitable place / block to house the server of this organisation would be Block C, as this
block contains the maximum number of computers, thus decreasing the cabling cost for most of the
computers as well as increasing the efficiency of the maximum computers in the network.
(e3) (i) For Layout 1, since the cabling distance between Blocks A and C, and that between B and C are
quite large, so a repeater each, would ideally be needed along their path to avoid loss of signals during the
course of data flow in these routes. For layout 2, since the distance between Blocks A and C is large so a
123
(e2) The most suitable place / block to house the server of this organisation would be Raj Building, as this
block contains the maximum number of computers, thus decreasing the cabling cost for most of the
computers as well as increasing the efficiency of the maximum computers in the network.
(e3)(i) Raj Building
(ii) In both the layouts, a hub/switch each would be needed in all the buildings, to interconnect the group
of cables from the different computers in each block e4) MAN, because MAN (Metropolitan Area
Networks) are the networks that link computer facilities within a city.
(i)(a) Production Unit and Media Unit :MAN
(b)Production Unit and Finance Unit:LAN
Switch/Hub
Optical fiber
Optical Fiber/Star Topology Wireless/Satellite Link/Leased Line
124
125
126
127
**********************
128
SAMPLE PAPER
Class- XII
Max Marks: 70
Computer Science(083)
Time: 3 Hrs
General Instructions:
Programming Language used is C++.
All questions are compulsory.
Q1 a)What is the difference between Call by Value and call by Reference ? Explain with code.
1
2
(3)
void main ( )
{int N [ ] = { 10 , 15 , 20 , 25 , 30}
int *z = N; while
(*z<30)
{
if(*z % 3 !=0 )
*z = *z + 2; else
*z = *z + 1; z++;
}
for (int R = 0 ; R <=4 ; R++ )
129
{
cout<<N[R]<< $ ;
If (R % 3 = = 0)
cout<<endl;
}
cout<<N[4] * 3 <<endl;
}
Give the output of the following program:
#include<iostream.h>
#include<ctype.h>
void ReCode ( char Text[ ], int Num ); void main
()
{
char Note [ ] = GooDLUck;
Recode (Note, 2); cout << Note <<endl;
}
void ReCode (char Text [ ], int Num)
{
for ( int K = 0 ; Text [K] !=\0 ; K++)
if ( K % 2 == 0)
Text [K] = Text [K] Num; else if ( islower (Text[K] ))
Text [K] = toupper ( Text [K] )
else
Text[K] = Text[K] + Num;
}
Study the following program and select the possible output from it :
#include <iostream.h>
#include<stlib.h>
const int MAX = 3;
void main()
{
randomize(); int
Number;
Number = 50 + random (MAX); for
(int p = Number; P>=50; P--) cout
<<p<<#;
cout <<endl;
}
2
2
130
131
(4)
Q3 a) Write a function CHANGE () in C++ , which accepts an array of integer and its size as parameters
and divide all those array elements by 7 which are divisible by 7 and multiply other elements by 3.
(3)
An array T[50][20] is stored in the memory along the column with each of the elements occupying
4 bytes , find out the base address and address of elements T[30][15],if an element T[25][10] is stored
at the memory location 9800.
(3)
Write function in C++ to perform Insert operation in a dynamically allocated Queue containing names of
employees .
(4)
Write a function in SWARARR() in C++ to swap(interchange) the first row elements with the last row
elements for a two dimensional array passed as the argument of the function.
(2)
Evaluate the following postfix notation of expression.
(2)
(2)
b)Consider the following table Organisation and Grossincome and answer (I) and (II) part of the
question:
133
Table: ORGANISATION
ECODE
NAME
2001
2002
2003
2004
2005
AJAY
VIJAY
RAM
RAHIM
ABBA S
POST
SGRAD E
DOJ
DOB
GENERAL MANAGER
D003
23-Mar-2003
13-Jan-1980
EXECUTIVE MANAGER
D002
12-Feb-2010
22-Jul-1987
DEPUTY MANAGER
D003
24-Jan-2009
24-Feb-1983
PROD. INCHARGE
D002
11-Aug-2006
03-Mar-1984
D001
29-Dec-2004
19-Jan-1982
ADD.GENERAL
MANAGER
Table:GROSSINCOME
SGRADE
SALARY
HRA
D001
56000
18000
D002
32000
12000
D003
24000
8000
Write SQL commands for the following statements:
(4)
To display the details of all MEMBERS OF ORGANISATION in descending order of DOJ.
To display NAME and POST of those MEMBERS whose SGRADE is either D002 or D003.
To display the content of all the ORGANISATION table, whose DOJ is in between 09-Feb-2006 and 08Aug-2009.
To add a new row with the following
2007, RUDRA, SALES INCHARGE, D002,26-Sep-2011, 26-Sept-1983
Give the output of the following SQL queries :
(2)
SELECT COUNT(SGRADE), SGRADE FROM ORGANISATION GROUP BY SGRADE;
SELECT MIN(DOB), MAX(DOJ) FROM ORGANISATION;
SELECT NAME,SALARY FROM ORGANISATION O, GROSSINCOME G WHERE
O.SGRADE=G.SGRADE AND O.ECODE<2003;
(iv) SELECT SGRADE, SALARY+HRA FROM GROSSINCOME WHERE SGRADE=D002
Q 6 : a) State and Verify Distributive Law. Verify using Truth Table.
2
b) Represent the Boolean expression yz+xz with the help of NAND gates only.
1
c)Obtain simplified form for a Boolean expression
F(x,y,z,w) = (1,3,4,5,7,9,11,12,13,15) using K Map
3
d) Write SOP form of Function F(x,y,z) whose truth table representation is given below:2
x
y z
F
0
0 0
0
0
0 1
0
0
1 0
1
0
1 1
0
1
0 0
1
1
0 1
0
1
1 0
1
1
1 1
1
Q7a) Compare any two Switching techniques.
1
Which of the following is not a Client Side script:
1
(i) VB Script (ii) Java Script
(iii) ASP
(iv) PHP
If someone has hacked your Website, to whom you lodge the Complain?
1
What do you mean by IP Address? How is it useful in Computer Security?
1
134
ABC Systems Organisation has set up its new center at Jabalpur for its office and web based activities. It
has 4 blocks of buildings as shown in the diagram below:
BLOCK C
BLOCK D
BLOCK A
BLOCK B
(ii) Hub/Switch
The organization is planning to link its International Office situated in Mumbai , which wired
communication link , you will suggest for a very high speed connectivity?
What is meant by Trojan Horse and Virus in terms of computers?
135
(b)
Ans.
(c)
Ans.
(d)
What
is the benefit of using default parameter/argument in a function? Give a suitable example to illustrate it
1. (a)
using C++ code.
The benefit of using default parameter/argument in a function are as following:
AnsThey can be used to add new parameters to existing function.
They can be used to combine similar function into one.
Example:
float intrest(float p, int t, float r = 0.10);
Now if any function call is appear as follows:
S_IN = intrest(5400, 2);// third argument missing
Here, the value 0.10 value is used for the third argument r.
Observe the following C++ code and write the name(s) of the header file(s), which will be essentially required to run
it in a C++ compiler:
void main()
{
float Area, Side;
cin>>Area;
Side=sqrt(Area);
cout<<One Side of the Square:<<Side<<endl;
}
Following header files will be essentially required to run the above code in a C++ compiler:
1. iostream.h
2. math.h
Observe the following C++ code carefully and rewrite the same after removing all the syntax error(s)
present in the code. Ensure that you underline each correction in the code.
Important Note:
- All the desired header files are already included, which are required to run the code.
- Correction should not change the logic of the program.
#define Change(A,B) 2*A+B;
void main()
{
Float X,Y,F;
cin>>X>>Y;
F=Change[X,Y];
cout<<Result:<<F<endline;
}
#define Change(A,B) 2*A+B;
void main()
{
float X,Y,F;
cin>>X>>Y;
F=Change(X,Y);
cout<<Result:<<F<<endl;
}
Observe the following C++ code carefully and obtain the output, which will appear on the screen after
execution of it.
136
Important Note:
- All the desired header files are already included in the code, which are required to run the code.
void main()
{
char *Text=AJANTA;
int *P, Num[]={1,5,7,9};
P=Num;
cout<<*P<<Text<<endl;
Text++;
P++;
cout<<*P<<Text<<endl;
}
Ans.
(e)
Ans.
Output:
1AJANTA
5JANTA
Observe the following C++ code carefully and obtain the output, which will appear on the screen after
execution of it.
#include<iostream.h>
class Mausam
{
int City,Temp,Humidity;
public:
Mausam(int C=1){City=C; Temp=10; Humidity=63;}
void Sun(int T) {Temp+=T;}
void Rain(int H) { Humidity+=H;}
void CheckOut()
{
cout<<City<<":"<<Temp<<"&"<<Humidity<<"%"<<endl;
}
};
void main()
{
Mausam M,N(2);
M.Sun(5);
M.CheckOut();
N.Rain(10);
N.Sun(2);
N.CheckOut();
M.Rain(15);
M.CheckOut();
}
Output:
1:15&63%
2:12&73%
1:15&78%
(f) Based on the following C++ code find out the expected correct output(s) from the option (i) to(iv). Also, find
out the minimum and the maximum value that can be assigned to the variable Guess used in the code at the
time when value of Turn is 3.
void main()
{
char Result[][10]={"GOLD","SILVER","BRONZE"};
137
int Getit=9,Guess;
for(int Turn=1;Turn<4;Turn++)
{
Guess=random(Turn);
cout<<Getit-Guess<<Result[Guess]<<"*";
}
}
(i)
(ii)
(iii)
(iv)
Ans. Correct answer is
9GOLD*9GOLD*8SILVER*
9GOLD*7BRONZE*8GOLD*
9GOLD*8SILVER*9GOLD*
9GOLD*8SILVER*8GOLD*
9GOLD*9GOLD*8SILVER*
Write any two similarities between Constructor and Destructor. Write the function headers for constructor and
2. (a) destructor of a class Flight.
Ans. Similarities:
Constructors and destructors do not have return type, not even void nor can they return values.
References and pointers cannot be used on constructors and destructors because their addresses cannot be
taken.
For example:
class Flight
{
public:
Flight(); // Constructor for class Flight
~Flight(); // Destructor for class Flight
};
Answer the questions (i) and (ii) after going through the following class:
(b) class Race
{
int CarNo, Track;
public:
Race();// Function 1
Race(int CN);// Function 2
Race(Race &R);// Function 3
void Register();// Function 4
void Drive();// Function 5
};
void main()
{
Race R;
:
}
(i)Out of the following, which of the option is correct for calling Function 2?
Option 1-Race T(30);
Option 2-Race U(R);
(ii)Name the feature of Object Oriented Programming, which is illustrated by Function 1, Function 2 and
Function 3 combined together.
Ans.
138
(c)
Data Members
Busno - to store Bus No
From to store Place name of origin
To to store Place name of destination
Type to store Bus Type such as O for ordinary
Distance to store the Distance in Kilometers
Fare to store the Bus Fare
Member Functions
A constructor function to initialize Type as O and Freight as 500
A function CalcFare() to calculate Fare as per the following criteria:
TypeFare
O
15*Distance
E
20*Distance
L
24*Distance
A function Allocate() to allow user to enter values for Busno, From, To, Type and Distance. Also,
this function should call CalcFare() to calculate Fare.
A function Show() to display the content of all the data members on screen.
Ans.
#include <iostream.h>
#include <conio.h>
class Bus
{
private:
char From[20],To[20];
int fare,busno,distance;
char Type;
public:
Bus ( );//Constructor
~Bus( );//Destructor
int CalcFare();
void Allocate();
void Show();
};
Bus :: Bus( )
{
fare=500;
Type='O';
}
void Bus :: Allocate( )
{
cout<<"Enter the Bus no: ";
cin>>busno;
cout<<"\nFrom: ";
cin>>From;
cout<<"\nTo: ";
cin>>To;
cout<<" \nEnter the Type: ";
cin>>Type;
cout<<"\nEnter the distance: ";
cin>>distance;
CalcFare();
139
}
int Bus:: CalcFare( )
{
if(Type=='O')
{
fare=15*distance;
}
else if(Type=='E')
{
fare=20*distance;
}
else if(Type=='L')
{
fare=24*distance;
}
else
cout<<"Wrong Type";
return fare;
}
void Bus :: Show()
{
cout<<"\n\n****Your Booking Detail***"<<endl;
cout<<"Bus no: "<<busno<<endl;
cout<<"From: "<<From<<endl;
cout<<"To: "<<To<<endl;
cout<<"Type: "<<Type<<endl;
cout<<"Distance: "<<distance<<endl;
cout<<"Total Fare: "<<fare<<endl;
}
Bus :: ~Bus( )
{
cout<<"Bus Detail is Closed";
}
void main( )
{
Bus s;
clrscr();
s.Allocate();
s.Show();
getch( );
}
(d)
Consider the following c++ code and answer the questions from (i) to (iv):
class Personal
{
int Class,Rno;
char Section;
protected:
char Name[20];
public:
personal();
void pentry();
void Pdisplay();
};
class Marks: private Personal
{
140
float M[5];
protected:
char Grade[5];
public:
Marks();
void Mentry();
void Mdisplay();
};
class Result: public Marks
{
float Total, Agg;
public:
char FinalGrade, comments[20];
Result();
void Rcalculate();
void Rdisplay();
};
(i)Which type of inheritance is shown in the above example?
(ii)Write the names of those data members, which can be directly accessed from the objects of
class Result.
(iii)Write the names of those member functions which can be directly accessed from the objects
of class Result.
(iv)Write names of those data members, which can be directly accessed from the Mentry()
function of class Marks.
Ans.
3.(a)
Ans.
(i)Multilevel Inheritance
(ii)FinalGrade, comments
(iii)Rcalculate(), Rdisplay(), Mentry(), Mdisplay();
(iv)Name[20], M[5], Grade[5]
Write code for a function void ChangOver (int P[],int N) in C++, which re-positions all the elements of the array by
shifting each of them to the next position and by shifting the last element to the first position.
For example:If the content of array is
01234
1215171321
141
}
An array T[15][10] is stored along the row in the memory with each element requiring 8 bytes of storage. If
the base address of array T is 14000, find out the location of T[10][7].
Ans.
=14000+(80)*8
=14000+640
=14640
(c)
Ans.
(d)
Ans.
Evaluate the following postfix expression. Show the status of stack after execution of each operation:
5, 2, *, 50, 5, /, 5, -, +
Element Scanned
5
2
*
50
5
-
STACK
5
5,2
10
10,50
10,50,5
10,45
142
+55
Write a function QDELETE() in C++ to perform delete operation on a Linked Queue, which contains Passenger
4
(e) no and Passenger name. Consider the following definition of node in the code.
struct node
{
long int Pno;
char Pname[20];
node *Link;
};
class Queue
{
NODE *front, *rear;
Ans.
Queue() {front=NULL; rear=NULL;}
public:
void Addq();
void Delete();
};
void Queue::Delete()
{
if(front==NULL)
cout<<Queue is empty;
else
{
NODE *t = front;
front = front->Link;
if(front==NULL)
rear = NULL;
delete t;
}
}
4 (a) Fill in the blanks marked as Statement 1 and Statement 2, in the program segment given below with
appropriate functions for the required task.
class Club
{
long int MNo; // Member Number
char MName[20];// Member Name
char Email[30];//Email of Member
public:
void Register(); // Function to register member
void Disp();// Function to display details
void ChangeEmail() // Function to change Email
{
cout<<"Enter Changed Email:";
cin>>Email;
}
long int GetMno() { return MNo;}
};
void ModifyData()
{
fstream File;
File.open("CLUB.DAT",ios::binary|ios::in|ios::out);
int Modify=0,Position;
long int ModiMno;
143
Write a function CountYouMe() in C++ which reads the contents of a text file story.txt and counts the words
You and Me (not case sensitive).
For example, if the file contains:
You are my best friend.
You and me make a good team.
The function should display the output as
Count for You: 2
Count for Me: 1
#include<conio.h>
Ans. #include<iostream.h>
#include<fstream.h>
#include<string.h>
void COUNT()
{
ifstream Fil;
Fil.open("STORY.TXT");
char Word [80];
int C1=0, C2=0;
while (!Fil.eof())
{
Fil>>Word;
if(strcmp(Word,"You")==0)
C1++;
else if (strcmp(Word,"me") ==0)
C2++;
}
cout<<"Count for You:"<<C1<<endl;
144
Ans
5 (a)
}
Assuming the class ANTIQUE as declared below, write a function in C++ to read the objects of ANTIQUE
from binary file ANTIQUE.DAT and display those antique items, which are priced between 10000 and
15000.
class ANTIQUE
{
int ANO;
char Aname[10];
float Price;
public:
void BUY() { cin>>ANO;gets(Aname);cin>>price;}
void SHOW()
{
cout<<ANO<<endl;
cout<<Aname<<endl;
cout<<Price<<endl;
}
float GetPrice() { return Price;}
};
void search(float pr)
{
Ifstream ifile(ANTIQUE.DAT, ios::in | ios::binary);
if(!ifile)
{
cout<<could not open ANTIQUE.DAT file ; exit(-1); }
else
{
ANTIQUE a; int found=0;
while(ifile.read((char *)&a, sizeof(a)))
{
Pr=a.GetPrice();
if(pr>=10000 && pr<=15000)
{
a.SHOW(); found=1; break;
}
}
}
if(found==0)
cout<<given price not match;
}
Explain the concept of candidate keys with the help of an appropriate example.
Write SQL queries for (b) to (g) and write the outputs for the SQL queries mentioned shown in (h1) to
2
(h4) parts on the basis of tables PRODUCTS and SUPPLIERS
Table: PRODUCTS
PID
PNAME
QTY
PRICE
COMPANY
SUPCODE
101
DIGITAL CAMERA 14X
120
12000
RENIX
S01
102
DIGITAL PAD 11i
100
22000
DIGI POP
S02
104
PEN DRIVE 16 GB
500
1100
STOREKING
S01
106
LED SCREEN 32
70
28000
DISPEXPERTS
S02
105
CAR GPS SYSTEM
60
12000
MOVEON
S03
Table: SUPPLIERS
145
SUPCODE
S01
S03
S02
Ans.
SNAME
GET ALL INC
EASY MARKET CORP
DIGI BUSY GROUP
CITY
KOLKATA
DELHI
CHENNAI
A table may have more than one such attribute/group of attribute that identifies a tuple uniquely, all such
attribute(s) are known as Candidate Keys.
Candidate Key
(b)
Ans
To display the details of all the products in ascending order of product names (i.e. PNAME).
SELECT * FROM PRODUCTS ORDER BY PNAME;
(c)
To display product name and price of all those products, whose price is in the range of 10000 and 15000
(both value inclusive).
select PNAME,PRICE FROM PRODUCTS WHERE PRICE>=10000 && PRICE<=15000;
Ans:
(d)
Ans.
(e)
Ans.
(f)
Ans:
(g)
To display the number of products, which are supplied supplier. i.e., the expected output should be:
S01 2
S02 2
S03 1
SELECT SUPCODE, COUNT(SUPCODE) FROM PRODUCTS GROUP BY SUPCODE;
To display the price, product name and quantity (i.e., qty) of those products which have quantity more
than 100.
SELECT PRICE,PNAME,QTY FROM PRODUCTS WHERE QTY>100;
To display the names of those suppliers, who are either from DELHI or from CHENNAI.
1
SELECT SNAME FROM SUPPLIERS WHERE CITY="DELHI" || CITY="KOLKATA";
To display the name of the companies and the name of the products in descending order of company
names.
1
SELECT COMPANY,PNAME FROM PRODUCTS ORDER BY COMPANY DESC;
Obtain the outputs of the following SQL, queries based on the data given in tables PRODUCTS and
SUPPLIERS above.
(h1) SELECT DISTINCT SUPCODE FROM PRODUCTS;
(h2) SELECT MAX(PRICE), MIN(PRICE) FROM PRODUCTS;
(h3) SELECT PRICE*QTY AMOUNT FROM PRODUCTS WHERE PID=104;
(h4) SELECT PNAME,SNAME FROM PRODUCTS P, SUPPLIERS S WHERE P.SUPCODE=S.SUPCODE AND
QTY>100;
(h1) SUPCODE
Ans:
(h)
Ans:
146
S01
S02
S03
(h2)
MAX(PRICE)
28000
(h3)AMOUNT
55000
(h4)
PNAME
DIGITAL CAMERA 14X
PEN DRIVE 16GB
6 (a)
Ans.
MIN(PRICE)
1100
SNAME
GET ALL INC
GET ALL INC
X + Z = X + X . Z + Y . Z
IMPORTANT NOTE: This question was wrong in board paper expected question may this X+Z=X+Y'.Z+Y.Z
x+z=x+y'.z+y.z
RHS=x+y'.z+y.z
=x+z(y'+y) (y'+y=1 Complementarity law)
=x+z(1)
=x+z
=LHS
Obtain the Boolean Expression for the logic circuit shown below:
(b)
Ans.
The equivalent Boolean expression for the given Logic Circuit is: F = PQ + (Q + R)
(c)
Write the Sum of Product form of the function F(A, B, C) for the following truth table representation of F.
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
Ans.
147
10
0
1
ABC
10
1
0
ABC
11
0
0
ABC
11
1
1
ABC
Now by adding all the minterms for which output is 1, we get desired sum-of-products expression which is
F(A,B,C) = ABC + ABC + ABC + ABC
(d)
Ans.
7. (a)
Ans.
(b)
Ans.
Obtain the minimal form for the following Boolean expression using Karnaugh map.
F(U, V, W, Z) = (0, 1, 2, 3, 6, 7, 8, 9, 10, 13, 15)
UV + VZ + VW + UVZ + UW
Write two advantages of using an optical fiber cable over an Ethernet cable to connect two service stations
which are 200 m away from each other.
Optical fiber cable guarantees secure transmission and a very high transmission capacity.
Optical fiber cable is immune to electrical and magnetic interference.
,1
Rovenza Communication International (RCI) is an online corporate training provider company for IT related courses.
The company is setting up their new campus in Kolkata. You as a network expert have to study the physical locations
of various blocks and the number of computers to be installed. In the planning phase, provider the best possible
answer for the queries (i) to (iv) raised by them.
Distance
60
120
70
148
Block
Administrative Block
Finance Block
Faculty Recording Block
Computers
30
20
100
(i)Suggest the most appropriate block, where RCI should plan to install the server.
(ii)Suggest the most appropriate block to block cable layout to connect all three blocks for efficient
communication.
(iii)Which type of network out of the following is formed by connecting the computers of these
three blocks?
LAN
MAN
Wam
(iv)Which wireless channel out of the following should be opted by RCI to connect to students from
all over the world?
Infrared
Microwave
. Satellite
(i)Faculty recording block
Ans.
(ii)
(iii)LAN
(iv)Satellite
(d)
Ans.
(e)
Ans.
1
Write two advantages of using open source software over proprietary software.
Open Source Software is software whose source code is available to customer and it can be modified and
redistributed without any limitations whereas source code of proprietary Software is not available.
Open Source Software may come free of cost or with a payment of normal charges whereas proprietary
software is neither open nor freely available.
Which of the following crime(s) does not come under cybercrime?
1
(i)Copying some important data from a computer without taking permission from the owner of the
data.
(ii)Stealing keyboard and mouse from a shop.
(iii)Getting into unknown persons social networking account and start messaging on his behalf.
(i)Stealing keyboard and mouse from a shop.
149