XII CS Study Mat-1

XII  Computer Science

STUDY MATERIAL

“COMPUTER SCIENCE (083)”
Class – XII
Session: 2010-2011

CONTENTS
Topic Page No
Unit 1: Programming in C++ 5-93
1.1 C++ Revision Tour 5 – 36
1.2 Object Oriented Programming 37 – 41
1.3 Function Overloading 42 – 43
1.4 Classes And Objects 44 – 51
1.5 Constructors And Destructors 52 – 59
1.6 Inheritance: Extending Classes 60 – 69
1.7 Data File Handling 70 – 86
1.8 Pointers 87 -93
Unit 2: Data Structures 94 – 128
2.1 Arrays 94 – 106
2.2 Stack 107 – 119
2.3 Queue 120 – 128
Unit 3: Database and SQL 129 – 144
3.1 Database Concepts 129 – 134
3.2 Structured Query Language 135 – 144
Unit 4: Boolean Algebra 145 – 163
Unit 5: Communication & Open Source Concepts 164 – 173
HOTS Questions 174 -184
Sample Papers 185 – 195
Marking Scheme/ Solution 196 – 205
Practice Papers 206 – 242
Action Plan

243 – 245
Steps For Quantitative & Qualitative Improvement Of The Result
246
Difficulties Faced By Teachers & Suggestions
247

1.1:C++ Revision Tour
POINTS TO FOCUS
C++ Character Sets:
Character set is a set of valid characters that the language can recognize.
Letters A-Z , a-z
Digits 0-9
Special Symbols Space + – * / ^ \ ( ) [ ] { } = != <> . ‘ “ $ , ; : % ! & ? _ # <= >= @
White Spaces Blank spaces, horizontal tab, carriage return
Other Characters Any of the 256 ASCII character
C++ Tokens:
The smallest individual unit of the program is known as Token.
Keywords Words reserved by the language with a special meaning. Like int, float, switch, case etc
Identifiers Long sequence of letters & digits to identify a memory block, program unit or program objects. Like name, a, x, A, X, date, file1, file2 etc.
Literals Constants that never changes their value during the execution of a program.
Type :
• Integer Constant
 Decimal – 1234,+97 (not begins with zero)
 Octal – 014, 023 (preceded by 0)
 Hexadecimal – 0XC (preceded by 0x or 0X)
• Character Constant (‘z’, ‘A’, ‘\a’, ‘\t’, ‘\’’, ‘0’, ‘3’ )
• Floating Constant (-13.0, -0.00065, 1.52E07, 0.172E-3)
• String Constants (“abc\0”, “Computer Science\0”)
Punctuators [ ] ( ) { } , ; : * = #
Operators <<, >>, +, -, *, /, % , ++, –, ==, <, >, <=, >=, !=, &&, ||, !
Variables:
Variables represent named storage locations whose values can be manipulated during program run.e.g: A= 10; here A is a variable which holds the value 10.
Data types:
Data types are the means to identify the type of data and associated operations of handling it. C++ offers two types of data types:
Fundamental data types. These are the data types that are not composed of any other data type. There are five fundamental data type: char, int, float, double and void.
Derived data types. These are the data types that are composed of fundamental data types. These are array, function, pointer, reference, constant, class, structure, union and enumeration.
Modifiers:
The keywords which, when appear before a data type, change its meaning, are modifiers. These are signed, unsigned, short and long.When the data type modifiers appear before a type, the meaning of the data type is changed in the sense that its size is affected thereby affecting minimal range of values the data type can represent. For instance, as int is by default 2 bytes long and hence can represent values – 32768 to 32767 but when modifier unsigned appears before it, its range become 0 to 65,535.
setw() Manipulator:
setw()manipulator is an operator that can be inserted directly into input output statements to give the space. For example.
cout<>, <<) ii)Arithmetic operators( +, -, * , / and %) iii)Increment/Decrement operator( ++,--) iv)Relational Operator (>,<,=,>=,<= , !=, ==) v) Logical operator( ! , ||, &) vi) Conditional operators. ( ? : ) Flow of Control Statements: The three flow control statements are: sequence, selection( if , switch), iteration(while loop, do while loop, for loop). If statement:The if statement allows branching depending upon the result of logical expression. Syntax: if (condition) or if (condition) { { statements; statements; } } else { statements; } Switch statement: The switch statement handles a series of decisions by checking a particular variable or expression for different values. Syntax: Switch(expression) { case (expression1): statements; break; case (expression2): statements; break; . . default: statements; } while statement: While loop allows programs to repeat a statement or series of statements as long as a certain test condition is true. Syntax: while (test expn) { statements; } do- while statement: It allows programs to repeat a statement or series of statements. It is similar to while loop but here the body of the loop is always executed first,then the test condition is evaluated. Syntax: do { statements; } while (test expn); for statement: This statement in the loop repeat continuously a certain number of times. Syntax: for(initialize; test- expn; update) { statements; } Continue and Break break : Enables a program to skip over part of the code while (test expn) { statement 1; if (val >2000)
break;
:
statement2
}
statement3;
for(initialize; test- expn;
update)
{
statement 1;
if (val >2000)
break;
:
statement2
}
statement3;
do
{
statement 1;
if (val >2000)
break;
:
statement2
}
while(test expn)
statement3;

continue: instead forcing termination, it forces the next iteration of the loop to take place, skipping any code in between

while (test expn)
{
statement 1;
if (val >2000)
continue;
:
statement2
}
statement3;

for(initialize; test- expn;
update)
{
statement 1;
if (val >2000)
continue;
:
statement2
}
statement3;
do
{
statement 1;
if (val >2000)
continue;
:
statement2
}
while(test expn)
statement3;

Console I/O Operations :
Console I/O functionsperform input from standard input device and out put to the standard output device of a system. Generally a keyboard is standard input device and screen (monitor) is the standard output device of a system. Every Program takes some input and generates the processed data as output. Every programming language provides facilities for handling input and output Operations. C++ provides ConsoleI/O functions that perform input from standard input device and out put to the standard output device of a system.
We are familiar with cout and cin that use << and >> operators for output and input operations.
The cout and cin are defined in C++ standard library file “iostream.h”
We can use some library functions for performing input and output.

Function Description Example
getchar()
This function reads a character from the keyboard.
char ch=getchar();
putchar()
This function prints a character to the screen.
putchar(ch);

The header file for the functions getchar()andputchar()is “stdio.h”. So the file must be included in the program that uses these functions.

gets() This function accepts a string of characters entered by the keyboard. char name[21];
gets(name);
puts() This function writes a string of characters on the screen. puts(name);
get() The function get() fetches a single character and stores it in a character variable. char ch;
cin.get(ch);
put()
The put() function output a character to the standard output. cout.put(ch);
getline()
This function reads a line of text that ends with a new-line character. char name[21]; cin.getline(name,30);
write()
This function is invoked with cout stream object and displays a line of text on the screen. cout.write(name,3);

The header file for above functions is “iostream.h”. So the file must be included in the program that uses these functions.
Standard Library and Header Files:
A Library is a collection of subprograms used to develop other programs and software. The C++ library of functions store functions of same category under separate files known as “header files” These files consists of standard functions that a program can use.These header files provide function prototypes, definitions for library functions. Data types and constants used with the library functions are also defined in them.The header files and their associate functions are:
Header File : ctype.h
Function Description
isalnum( ) Returns nonzero if a character is alphanumeric
isalpha( ) Returns nonzero if a character is alphabetic
isdigit( ) Returns nonzero if a character is a digit
islower( ) Returns nonzero if a character is lowercase
isupper( ) Returns nonzero if a character is an uppercase character
tolower( ) Converts a character to lowercase
toupper( ) Converts a character to uppercase
Header File : string.h
strcat concatenates two strings
strcmpi compares two strings (Case insensitive comparison), and returns one of the following –
–ve value : if first string comes before second string in dictionary order
Zero : if both the strings are equal.
+ve value: if first string comes after second string in dictionary order
strcmp compares two strings (Case sensitive comparison), and returns one of the following –
–ve value : if first string comes before second string in dictionary order
Zero : if both the strings are equal.
+ve value: if first string comes after second string in dictionary order
strcpy copies (overwrite) one string to another
strlen returns the length of a given string
strupr converts string into upper case
Header File : iomanip.h
setf Sets ios flags.
setw Sets the width of the field assigned for output.
setprecision Sets the total number of digits to be displayed when floating point numbers are to be displayed.
Header File : math.h
pow Returns base raised to the power passed as first & second argument respectively..
exp Returns natural logarith e raised to the power passed as argument.
fabs Returns absolute value of the number passed as argument.
ceil Returns smallest integer not less than the real number passed as argument.
floor Returns largest integer not greater than the real number passed as argument.
fmod Returns remainder of the division x/y.( x, y passed as argument)
sqrt Returns square root of the number passed as argument.
Other functions of math.h:
Trigonometrical functions:acos, asin, atan, sinh, cosh, tanh etc
Exponential functions:exp, frexp etc
Logarithmic functions:log, log10 etc.

Some more header files and their associated functions

stdio.h
getc getchar gets putc putchar puts gets remove rename

fstream.h
open close get getline read write put seekg
seekp tellg tellp eof

stdlib.h
rand srand random randomize malloc

randomize( )
randomize( ) initializes the random number generator with a random number.
Working of random ( ) function
Syntax : random(num)
random ( num) generates random numbers within the range 0 to (num-1).For example random(6) generates random numbers between 0 to 5.
Example:
In the following program, if the value of N given by the user is 20, what maximum and minimum value the program could possibly display?
#include
#include
void main()
{int N, Guessme;
randomize();
cin>>N;
Guessme = random(N-10) + 10;
cout<
#define PI 3.14159 // This defines two new constants: PI and NEWLINE. #define NEWLINE ‘\n’// Once they are defined, they can be used
// in the code in place of their values
int main ()
{
double r=5.0; // radius
double circle;

circle = 2 * PI * r;
cout << circle; cout << NEWLINE; return 0; } Output : 31.4159 In fact the only thing that the compiler preprocessor does when it encounters #definedirectives is to literally replace any occurrence of their identifier (in the previous example, these were PI and NEWLINE) by the code to which they have been defined (31.4159 and ‘\n” respectively). The #define directive is not a C++ statement but a directive for the preprocessor; therefore it assumes the entire line as the directive and does not require a semicolon (;) at its end. If we append a semicolon character (;) at the end, it will also be appended in all occurrences of the identifier within the body of the program that the preprocessor replaces. Declared constants (const) With the const prefix we can declare constants with a specific type in the same way as we would do with a variable. For example: const int pathwidth = 100; const char tabulator = '\t'; Here, pathwidth and tabulator are two typed constants. They are treated just like regular variables except that their values cannot be modified after their definition. Type Conversion in C++: 1. Implicit type conversion 2. Explicit type conversion (type casting) 1. Implicit conversion (Type promotion): Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. Usual arithmetic implicit type conversions are summarized in the following table: Step No. If either type of operand is Then resultant type of expression is Otherwise 1 long double long double step 2 2 double double step 3 3 float float step 4 4 short int or int(signed or unsigned) or char int step 5 5 unsigned long unsigned long step 6 6 long int or unsigned int (i) long int (provided long int can represent all values of unsigned int) (ii) unsigned long int (if all values of unsigned int can’t be represented by long int) step 7 7 long long step 8 8 unsigned unsigned both operands are int 2. Explicit type conversion (Type Casting):Type casting operators allow us to convert adatum of a given type to another. There are several ways to do this in C++. The simplest one, which has been inherited from the C language, is to precede the expression to be converted by the new type enclosed between parentheses (()): int i; float f = 3.14; i = (int) f; The previous code converts the float number 3.14 to an integer value (3), the remainder is lost. Here, the typecasting operator was (int). Another way to do the same thing in C++ is using the functional notation: preceding the expression to be converted by the type and enclosing the expression between parentheses: i = int ( f ); Both ways of type casting are valid in C++. sizeof( )operator: This operator accepts one parameter, which can be either a type or a variable itself and returns the size in bytes of that type or object: a = sizeof (char); This will assign the value 1 to ‘a’ because char is a one-byte long type.The value returned by sizeof is a constant, so it is always determined before program execution. typedef keyword: Using the keyword typedef, we can create an alias (a synonym) for existing fundamental or compound datatypes in C++.Syntax: typedef existing_type new_type_name ; where existing_type is a C++ fundamental or compound type and new_type_name is the name for the new type we are defining. For example: typedef char C; typedef unsigned int WORD; typedef char * pChar; typedef char field [50]; In this case we have defined four data types: C, WORD, pChar and field as char, unsigned int, char* and char[50] respectively, that we could perfectly use in declarations later as any other valid type: C mychar, anotherchar, *ptc1; WORD myword; pChar ptc2; field name; typedef does not create different types. It only creates synonyms of existing types.That means that the type of myword can be considered to be either WORD or unsigned int, since both are in fact the same type. Benefit of using typedef  typedef can be useful to define an alias for a type that is frequently used within a program.  It is also useful to define types when it is possible that we will need to change the type in later versions of our program, or if a type we want to use has a name that is too long or confusing. Introduction to Arrays: Collection of variables of same data type that are referenced by a common name. Example: Types of Array:  Single or One Dimensional int billy[5];  Double or Two Dimensional int jimmy [3][5]; One Dimensional Array: Declaration datatype name[No.of elements]={initial values of elements separated by comma}; Example - int a [7] = { 16, 2, 77, 40, 120,7,1 }; Representation of single dimensional array in memory: Points to remember: Example: /*Program to accept 10 numbers and display them along with their sum after storing in an array.*/ #include
#include
void main( )
{ clrscr( );
int a[10],s=0;
cout<<“Enter 10 numbers : ”; for(int i=0;i<10;i++) //Taking input cin>>a[i];
for(i=0;i<10;i++) //Processing array by reading elements one s=s+a[i]; // by one & adding them in a variable s for(i=0;i<10;i++) //Displaying output cout<
#include
void main( )
{ clrscr( );
int sum(int a[]);
int a[10],s=0;
cout<<“Enter 10 numbers : “; for(int i=0;i<10;i++) cin>>a[i];
s=sum(a);
for(i=0;i<10;i++) cout<
#include
void main( )
{ clrscr( );
void sort(int *a);
int a[10];
cout<<"Enter 10 numbers :"; for(int i=0;i<10;i++) cin>>a[i];
sort(a);
for(i=0;i<10;i++) cout<
#include
void main()
{ char a[8]=”Class12″;
clrscr();
cout<
#include
#include
void main()
{
char a[8]=”Class12\0″;
void disp(char *);
clrscr();
disp(a);
getch();
}
Two dimensional Array:
Declaration:
datatype name [Row] [Column];
Example: int a[3] [7] ;

Representation of two dimensional array in memory:

Points to remember:

Functions in C++:
A named set of statements (subprogram) that may take some values from its caller and returns a value after performing a specific job.
Benefits of using functions:
 Provides modularity.
 Provides reusability.
 Makes program modification easier.
 Makes program smaller and simpler.
Types of Functions in C++
Two types of functions are available in C++.
1. Library functions:Provided by C++ compiler in library and can be used by including respective header file.
2. User defined functions:Defined by user.
Defining Functions &returning values from functions:
A function is a group of statements that is executed when it is called from some point of the program.The following is its format:
( parameter1, parameter2, …) { statements }
where:
 return type is the data type specifier of the data returned by the function. If function does not returns any value return type should be void.
 name is the identifier by which it will be possible to call the function.
 parameters (as many as needed): Each parameter consists of a data type specifier followed by an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas.
 statements is the function’s body. It is a block of statements surrounded by braces { }.
Example:
#include
int addition (int a, int b)
{
int r;
r=a+b;
return (r);
}
void main ()
{ int z;
z = addition (5,3);
cout << "The result is " << z; } Output : The result is 8 Explanation:A C++ program always begins its execution by the main function. So we will beginthere.We can see how the main function begins by declaring the variable z of type int. Right after that, we see a call to a function called addition. The parameters and arguments have a clear correspondence. Within the main function we called to addition passing two values: 5 and 3, that correspond to the int a and int b parameters declared for function addition. At the point at which the function is called from within main, the control is lost by main and passed to function addition. The value of both arguments passed in the call (5 and 3) are copied to the local variables int a and int b within the function. Function addition declares another local variable (int r), and by means of the expression r=a+b, it assigns to r the result of a plus b. Because the actual parameters passed for a and b are 5 and 3 respectively, the result is 8.The following line of code: return (r); finalizes function addition, and returns the control back to the function that called it in the first place (in this case, main). At this moment the program follows it regular course from the same point at which it was interrupted by the call to addition. But additionally, because the return statement in function addition specified a value: the content of variable r (return (r);), which at that moment had a value of 8. This value becomes the value of evaluating the function call. So being the value returned by a function the value given to the function call itself when it is evaluated, the variable z will be set to the value returned by addition (5, 3), that is 8. To explain it another way, you can imagine that the call to a function (addition (5,3)) is literally replaced by the value it returns (8).The following line of code in main produces the printing of the result on the screen: cout <<"The result is "<< z; Scope of variables: The scope of variables declared within a function or any other inner block is only their own function or their own block and cannot be used outside of them. For example, in the previous example it would have been impossible to use the variables a, b or r directly in function main since they were variables local to function addition. Also, it would have been impossible to use the variable z directly within function addition, since this was a variable local to the function main. Therefore, the scope of local variables is limited to the same block level in which they are declared. Nevertheless, we also have the possibility to declare global variables; These are visible from any point of the code, inside and outside all functions. In order to declare global variables you simply have to declare the variable outside any function or block; that means, directly in the body of the program. Parameters (or Arguments) and their types: Parameters are the values passed to a function for its working. There are two types of parameters: 1. Actual parameters: Parameters that appears in the calling statement of the function are known as actual parameters. 2. Formal Parameters:Parameters that appears in the function prototype or header statement of the function definition are known as formal parameters.Example : Calling Functions: There are two ways to call the function by passing the parameters or arguments to a function :  Call by value / Pass by value  Call by reference / Pass by reference Parameters passed by value: Until now, in all the functions we have seen, the arguments passed to the functions have been passed by value. When we call a function by passing parameters by value, the values of actual parameters get copied into the formal parameters but not the variables themselves. The changes made in the values of formal parameters will not reflected back to the actual parameters. For example, suppose that we called our first function addition using the following code: int x=5, y=3, z; z = addition ( x , y ); What we did in this case was to call to function addition passing the values of x and y, i.e. 5 and 3 respectively, but not the variables x and y themselves. This way, when the function addition is called, the value of its local variables a and b become 5 and 3 respectively, but any modification to either a or b within the function addition will not have any effect in the values of x and y outside it, because variables x and y were not themselves passed to the function, but only copies of their values at the moment the function was called. Parameters passed by reference: There might be some cases where we need to manipulate from inside a function the value of an external variable. For that purpose we can use arguments passed by reference, as in the function duplicate of the following example: // passing parameters by reference #include
void duplicate (int& a, int& b, int& c)
{ a*=2;
b*=2;
c*=2;
}
int main ()
{ int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z; return 0; } Output: x=2, y=6, z=14 The first thing that should call your attention is that in the declaration of duplicate the type of each parameter was followed by an ampersand sign (&). This ampersand is what specifies that their corresponding arguments are to be passed by reference instead of by value. When a variable is passed by reference we are not passing a copy of its value, but we are somehow passing the variable itself to the function and any modification that we do to the formal parameters will have an effect in actual parameter passed as arguments in the call to the function. To explain it in another way, we associate a, b and c with the arguments passed on the function call (x, y and z) and any change that we do on a within the function will affect the value of x outside it. Any change that we do on b will affect y, and the same with c and z. That is why our program's output, that shows the values stored in x, y and z after the call to duplicate, shows the values of all the three variables of main doubled. If when declaring the following function:void duplicate (int& a, int& b, int& c) we had declared it this way: void duplicate (int a, int b, int c) i.e., without the ampersand signs (&), we would have not passed the variables by reference, but a copy of their values instead, and therefore, the output on screen of our program would have been the values of x, y and z without having been modified. For example, // passing parameters by value #include
void duplicate (int a, int b, int c)
{ a*=2;
b*=2;
c*=2;
cout << "a=" << a << ", b=" << b << ", c=" << c; } int main () { int x=1, y=3, z=7; duplicate (x, y, z); cout << "x=" << x << ", y=" << y << ", z=" << z; return 0; } Output : a=2, b=6, c=14 x=1, y=3, z=7 Passing by reference is also an effective way to allow a function to return more than one value. A Comparison: S.N. Parameters passed by value Parameters passed by reference 1. When we call a function by passing parameters by value, the values of actual parameters get copied into the formal parameters but not the variables themselves. When we call a function by passing parameters by reference, formal parameters create a reference or pointer directly to the actual parameters. 2. The changes made in the values of formal parameters will not be reflected back to the actual parameters. The changes made in the values of formal parameters will be reflected back to the actual parameters. 3. Example – // passing parameters by value #include
void swap (int a, int b)
{ a=a+b;
b=a-b;
c=a-b;
cout << "Values inside function \n”; cout<<”a=" << a << ", b=" << b; } int main () { int x=1, y=3; swap (x, y); cout << "Values inside main \n”; cout << "x=" << x << ", y=" << y; return 0; } Output : Values inside function a=3, b=1 Values inside main x=1, y=3 (Note: Changes made in formal parameters (a and b) are not reflected back to actual parameters (x and y)) Example - // passing parameters by reference #include
void swap (int &a, int &b)
{ a=a+b;
b=a-b;
c=a-b;
cout << "Values inside function \n”; cout<<”a=" << a << ", b=" << b; } int main () { int x=1, y=3; swap (x, y); cout << "Values inside main \n”; cout << "x=" << x << ", y=" << y; return 0; } Output : Values inside function a=3, b=1 Values inside main x=3, y=1 (Note: Changes made in formal parameters (a and b) are reflected back to actual parameters (x and y)) Default values in parameters: When declaring a function we can specify a default value for each of the last parameters. This value will be used if the corresponding argument is left blank when calling to the function. To do that, we simply have to use the assignment operator and a value for the arguments in the function declaration. If a value for that parameter is not passed when the function is called, the default value is used, but if a value is specified this default value is ignored and the passed value is used instead. Example: // default values in functions #include
using namespace std;
int divide (int a, int b=2)
{ int r;
r=a/b;
return (r);
}
int main ()
{ cout << divide (12); cout << endl; cout << divide (20,4); return 0; } Output: 6 5 Structures: Structure is a collection of variables referenced under one name. The keyword ‘struct’ tells the compiler what a structure is being defined. Syntax of Structure: struct tag { Type variable_name; Type variable_name; - - - - - - - - - - - - - - }structure_variable; Basic declaration and member variables: Structures are declared with the ‘struct’ keyword. Declaration of members are placed within this declaration. The following code snippets show an example of a struct declaration: struct person { char name[20]; int age; }; In the above example name and age are called member variables of the person datatype. Note that the semicolons after the closing curly braces are mandatory. After the above declaration, person can be used as follows to create newly defined variables of the person datatype #include
#include
struct person
{ char name[20];
int age;
};
int main ()
{
person a, b;
a.name = “Calvin”; b.name = “Hobbes”;
a.age = 30; b.age = 20;
cout << a.name << ": " << a.age << endl; cout << b.name << ": " << b.age << endl; return 0; } Executing the above code will output Calvin: 30 Hobbes: 20 Refrencing Structure elements: Once a structure variable has been defined,its members can be accessed through the use of the ‘.’ operator. Consider the above code fragment. To assign the value 30 to the age element of person the statement is as follows a.age =30; where ‘a’ reperesents the structure variable. The common syntax for accessing structure element is structurename.elementname Nested Structures: A structure can be nested inside another structure (a structure inside another). Example struct addr { int house_no; char area[26]; }; struct emp { int empno; char name[26]; addr address; }; emp worker; The structure emp has been defined having several elements including a structure address also. Accessing Nested Structure Members: The members of structures are accessed using ‘.’ operator. To access the house_no member of address structure which is an element of another structure worker,we shall write worker.address.house_no; To initialize it worker.address.house_no=1695; Example : Program using nested structure to accept and show details of a student. #include
#include
#include
struct date
{
int dd;
int mm;
int yy;
};
struct student
{
int sno;
char name[20];
char std[3];
date dob;
};
void main( )
{
clrscr( );
student s;
cout<<"\n Enter Student No. : "; cin>>s.sno;
cout<<"\n Enter Student Name : "; gets(s.name); cout<<"\n Enter Class : "; cin>>s.std;
cout<<"\n Enter Date of birth : "; cout<<"\n dd : "; cin>>s.dob.dd;
cout<<"\n mm : "; cin>>s.dob.mm;
cout<<"\n yyyy : "; cin>>s.dob.yy;
cout<<"\n Student Details : "; cout<<"\n Student No. : "<
#include
#include
struct date
{
int dd;
int mm;
int yy;
};
struct student
{
int sno;
char name[20];
char std[3];
date dob;
};
void main( )
{
clrscr( );
student s[5];
for(int i=0;i<=4;i++) { cout<<"\n Enter Details for Student "<>s[i].sno;
cout<<"\n Enter Student Name : "; gets(s[i].name); cout<<"\n Enter Class : "; cin>>s[i].std;
cout<<"\n Enter Date of birth : "; cout<<"\n dd : "; cin>>s[i].dob.dd;
cout<<"\n mm : "; cin>>s[i].dob.mm;
cout<<"\n yyyy : "; cin>>s[i].dob.yy;
}
for(i=0;i<=4;i++) {cout<<"\n Student Details for student "<
#include
struct complex
{int real;
int imag;
};
complex sum(complex a, complex b)
{complex c;
c.real=a.real+b.real;
c.imag=a.imag+b.imag;
return c;
}
void main( )
{clrscr( );
complex n1,n2,n3;
n1.real=2;
n1.imag=3;
cout<<"\n First Number : "<
struct three_d;
{int x,y,z;}
void movein(three_d &t, int step=1)
{t.x + = step;
t.y – = step;
t.z + = step;
}
void moveout(three_d &t, int step=1)
{t.x – = step;
t.y + = step;
t.z – = step;
}
void main( )
{three_d t1={10,20,5}, t2=(30,10,40};
movein(t1);
moveout(t2,5);
cout<2000)
break;
:
statement2
}
statement3;
for(inilialize; test- exprsn;
update)
{
statement 1;
if (val >2000)
break;
:
statement2
}
statement3;
do
{
statement 1;
if (val >2000)
break;
:
statement2
}
while(test exprsn)
statement3;

continue :Instead forcing termination, it forces the next iteration of the loop to take place, skipping any code in between

while (test exprsn)
{
statement 1;
if (val >2000)
continue;
:
statement2
}
statement3;

for(inilialize; test- exprsn;
update)
{
statement 1;
if (val >2000)
continue;
:
statement2
}
statement3;
do
{
statement 1;
if (val >2000)
continue;
:
statement2
}
while(test exprsn)
statement3;

Problem7: Given the following code fragment
int ch = 20;
cout<>val;
res = n + val > 1750 ? 400 : 200;
cout< 1750 is true.
i) 400, the reason is the same as explained above(1000 + 1000) > 1750 is true).
ii) 200, because (1000 + 500)1750 is false.
Problem10: Determine the output?
(i) a = 2;
b = ++a;
cout <
struct Pixel
{ int C,R;
};
void Display(Pixel P)
{ cout<<”Col”<
#include
#include
struct video
{ char title[20];
float tlength;
float tcost;
float trent;
};
videovid[10];
char ans;
void main()
{ clrscr();
int i=0;
do
{clrscr();
cout<<”Title =>”;
cin>>vid[i].title;
cout<<”Table Length =>”;
cin>>vid[i].tlength;
cout<<”Rent =>”;
cin>>vid[i].trent;
cout<<”Copies =>”;
cin>>vid[i].tcost;
cout<<”Do you want to continue =>”;
cin>>ans;
i++;
}while(ans==’y’);
}
Problem28: Write a program to accept the name and total marks of 20 students in an array. Display the names of the students (including marks ) securing highest and lowest marks using structure.
Solution: #include
#include
#include
#include
const N =20;
struct student
{char name[20];
int totmark;
}
void main()
{ student stud[50];
student temp;
int i,j,N=20;
int totmark;
char tname[20];
clrscr();
cout<<”Enter student’s information”; for(i=0;i>stud[i].name;
cout<<”Enter student’s total mark”; cin>>stud[i].totmark;
}
for(i=0;istud(j).totmark)
{ temp = stud(i);
stud(i) = stud[j];
stud[j] = temp;
}
}
}
cout<
const int Size 5;
void main( )
{int Array [Size] ;
Array = { 50, 40, 30, 20, 10 } ;
for (Ctr = 0 ; Ctr < Size; Ctr++) cout>>Array [Ctr];
}
Problem 6: Rewrite the following program after removing all the syntax error(s), if any. Underline each correction.
(i)#include (iostream.h)
void main( )
{ int X[ ] = { 60,50,30,40}, Y; Count = 4;
cin >> Y ;
for ( I = Count – 1 ; I >= 0, I – -)
switch( I )
{case 0 :
case 2 : cout<> Y + X [I] ;
}
}
(ii) #include
void main ( )
{int P[ ]={90,10,24,15}:Q, Number = 4 ; Q = 9;
for [ int I = Number – 1 ; I >= 0, I–]
Switch ( I )
{case 0 :
case 3 : cout >> P [ I ] * Q << endl ; break ; case 1 : case 2 : cout << P [ I ] + Q ; } } Problem 7: Write a C++ program to find the sum of two matrices.. Problem 8: Write a C++ program to find the difference of two matrices. Problem 9: Write a C++ program to find the product of two matrices. Problem 10: Write a C++ program to find the transpose of a m X n matrix. Problem 11: Write a C++ program to find the sum of the diagonal elements of 4X4 matrix. Problem 12: Find the output of the following program: #include
void Changethecontent(int Arr[], int Count)
{for (int C = 1;C < Count; C++) Arr[C-1] += Arr[C]; } void main() {int A[] = {3,4,5}, B[]={10,20,30,40}, C[]={900,1200}; Changethecontent(A, 3); Changethecontent(B, 4); Changethecontent(C, 2); for (int L = 0;L < 3;L++) cout<
void Indirect(int Temp=20)
{for (int 1=10; I<=Temp; I+=5) cout<
#include
void main( )
{randomize();
int Score[] = {25,20,34,56, 72, 63}, Myscore;
Myscore = Score[2 + random(2)];
cout<
#include
void main()
{ int N,Guessme;
randomize();
cin>>N;
Guessme=random(N)+10;
cout<
#include
void main()
{ char Text[ ]= “Mind@Work!”;
for (int I=0; Text[I] != ‘\0’; I++)
{if ( ! isalpha(Text[I]))
Text[I]=’*’;
else if (isupper (Text[I]))
Text[I]=Text[I]+1;
else
Text[i]=Text[I=1];
}
cout<
struct PLAY
{ int Score, Bonus;
};
void Calculate(PLAY &P, int N=10)
{P.Score++;
P.Bonus += N;
}
void main()
{PLAY PL={10,15};
Calculate(PL, 5);
cout<
struct Pixel
{ int C, R;
};
void Display (Pixel P)
{ cout << “Col” << P.C << “Row” << P.R << endl; } void main ( ) { Pixel X={50, 60}, Y, Z; Z = X; X . C += 20 ; Y = Z ; Y . C += 20 ; Y . R += 10 ; Z . C -= 5 ; Display ( X ) ; Display ( Y ) ; Display ( Z ) ; } 1.2: Object Oriented Programming POINTS TO FOCUS Programming Paradigms: A programming methodology defines the methodology of designing and implementing programs using the key features and other building blocks (such as key words, functions, pre processor directives etc) of a programming language. Some of the important paradigms are:  Procedural Programming  Object based programming  Object oriented programming Procedural Programming: Definition : Procedural programming is a programming paradigm that gives more emphasis to procedure than data. Advantage : Procedural Programming separates functions and data. So writing procedures separately was easy. Disadvantage : The Procedural programming is susceptible to design changes. The changes should be affecting more than one procedure in the program. The Procedural Programming leads to increased time and cost overheads during design changes. Example : C, Pascal etc Object Based Programming: Definition : Object based programming is a programming paradigm that encloses data and associated meaningful functions in one single entity called a class. Advantage : i)Object based Programming localizes the implementation details. When any change is made the user interface is not affected. ii) It is considered as a sub set of Object oriented programming. iii) It overcomes the difficulties of Procedural Programming iv) It supports user defined types v) It implements information hiding and abstraction etc. Disadvantage : Object based programming cannot implement real world relationships that exist among objects. Example : Visual Basic Object oriented programming Definition : Object oriented Programming is a programming paradigm that combines data and procedures in one single unit called object. Advantage : i) Object oriented Programming enables re use of code ii) It provides ease of comprehension. It makes the implementation of real world models easier. iii) It provides ease of fabrication and maintenance. The concepts of data abstraction and data encapsulation provides a very clean design. iv) It can be easily redesigned and extended. The above facilities facilitate redesign and maintenance. Example : C++, Java OOP Concepts: The Important OOP concepts are:  Data Abstraction  Data Hiding  Data Encapsulation  Inheritance  Polymorphism Object: Object is an identifiable entity with some characteristics and behaviour.Examples: Car, Apple, Chair etc.A car is a collection of wheels, doors, seats, windows. These are its characteristics. A car can move, speed up, slow down, stop, park, etc. These are its behaviours. Thus we can put everything we know about a car in one object. Implementing Objects: The characteristics or states are maintained with the help of variables or data items.The behaviour is implemented through functions or methods. Encapsulation: Encapsulation is the wrapping up of characteristics and behaviour into one unit. The following things should be taken care during implementation of Encapsulation. i) Any thing that an object does not know or cannot do is excluded from the object. ii) Encapsulation is used to hide unimportant implementation details from other objects. iii) Packaging an object’s variables within the protective custody of its methods is called encapsulation & this task is accomplished through Classes. Classes: A class is a group of similar objects. Examples: Vehicle, Fruits, Furniture.A class can also be defined as a way to bind the data describing an entity and itsassociated functions together. Thus the class implements Encapsulation. Encapsulation is having the benefits of modularity and information hiding. A class syntax for class definition is : class
{ private :
//hidden data members/methods here
protected :
//(un important implementation details here
public :
//exposed implementation details here
};
Data Hiding:
Data Hiding is a related concept of data abstraction. Unessential features or backgrounddetails are hidden from the world.
A class groups its members into three:
 Private
 Protected and
 Public
The private & protected members remain hidden from outside world. Thus through private & protected members class enforces data hiding.
Data Abstraction:
It is the act of representing the essential features without including the
background details and explanations. The class gives the outside world
only the essential data by using the concept of data hiding and the Public
members contains the essential data for all the members.
Inheritance:
Inheritance is a process in which a class inherits all the state and behavior of another class. This type of relationship is called child-Parent or is-a relationship. “Subclasses” are more specialized versions of a class, which inherit attributes and behaviors from their parent classes, and can introduce their own.
Using Inheritance all subclasses of a base class define only their unique properties & methods and reuse the common properties from the base class.
Inheritance is implemented by specifying the name of the base class from which the class being defined (derived class) has to inherit from.
class :
{
derived class own features
}
Abstract class:Abstract class is the one which defines an interface, but does not necessarily provide implementations for all its member functions. It is meant to be used as the base class from which other classes are derived.
Example: Shape. It can suggest that shapes can have colour, size, sides etc.
Concrete class:A derived class that implements all the missing functionality is called a Concrete class. It is derived from an abstract class.
Example: circle, rectangle etc.
Polymorphism:
Polymorphismis the attribute that allows one interface to be used with different situation. Polymorphism is implemented through virtual functions, overloaded functions and overloaded operators.
Overloading:
The term overloading means a name having two or more distinct meanings. Thus an overloaded function refers to a function having more than one distinct meaning. Similarly when two or more distinct meanings are defined for an operator, it is said to be an overloaded operator.
Function overloading:
A function name having several definitions that are differentiable by the number or types of their arguments is known as an overloaded function and this process is known as function overloading.
float add(int a, int b);
float add( float x, float y);

POINTS TO REMEMBER

 Statements are the instructions given to the computer to perform any kind of action.
 Advantages and disadvantages of various paradigms
 OOP concepts
 Implementing object using data members
 Implementing data hiding, abstraction, encapsulation using class
 Definition of class
 Implementing inheritance
 Abstract and concrete classes
 Implementing polymorphism

SOLVED PROBLEMS
Problem 1: What are the OOP concepts?
Solution: The Important OOP concepts are:
 Data Abstraction
 Data Hiding
 Data Encapsulation
 Object
 inheritance
 Polymorphism
Problem2: Explain the concept of data abstraction and its implementation in C++.
Solution: It is the act of representing the essential features without including the background details and explanations. The class gives the outside world only the essential data by using the concept of data hiding and the Public members contains the essential data for all the members. Thus data abstraction is achieved with the help of class.
Problem3: Explain the concept of data encapsulation and its implementation in C++.
Solution: Encapsulation is the wrapping up of characteristics and behaviour into one unit. A class is defined as a way to bind the data describing an entity and its associated functions together. Thus the class implements Encapsulation.
Problem4: Explain the concept of data hiding and its implementation in C++.
Solution: Data Hiding is a related concept of data abstraction. Unessential features or background details are hidden from the world.
A class groups its members into three:
 Private
 Protected and
 Public
The private & protected members remain hidden from outside world. Thus through private & protected members class enforces data hiding.
Problem5: Explain the benefits of data encapsulation
Solution: Encapsulation is having the benefits of modularity and information hiding.
Problem6: Explain the concept of object and its implementation in C++.
Solution: Object is an identifiable entity with some characteristics and behaviour. Examples: Car, Apple, Chair etc. The characteristics or states are maintained with the help of variables or data items. The behaviour is implemented through functions or methods.
Problem7: Explain the concept of polymorphism and its implementation in C++.
Solution: Polymorphism is the attribute that allows one interface to be used with different situation.
Polymorphism is implemented through virtual functions, overloaded functions and overloaded operators.
Problem8: Differentiate between abstract and concrete classes
Solution: Abstract class is the one which defines an interface, but does not necessarily provide implementations for all its member functions. It is meant to be used as the base class from which other classes are derived. Example: Shape. It can suggest that shapes can have colour, size, sides etc. A derived class that implements all the missing functionality is called a Concrete class. It is derived from an abstract class. Example: circle, rectangle etc.
Problem9: State the advantages of Object Oriented Programming.
Solution: i) Object oriented Programming enables reuse of code.
ii) It provides ease of comprehension. It makes the implementation of real world models easier.
iii) It provides ease of fabrication and maintenance. The concepts of data abstraction and data
encapsulation provides a very clean design.
iv) It can be easily redesigned and extended. The above facilities facilitate redesign and maintenance.
Problem10: Differentiate between Object Oriented and Object Based Programming.
Solution: Though both OBP and OOP are object oriented, OBP does not support inheritance and there by polymorphism whereas these are supported by OOP. So OBP is considered as a subset of OOP.
Problem11: Give any 2 examples for Object Oriented Programming
Solution: C++, Java
Problem12: A function printchar is defined as
void printchar(char ch = ‘*’, int len = 40)
{
for(x = 0;x
int operate (int a, int b)
{
return (a*b);
}
float operate (float a, float b)
{
return (a/b);
}
int main ()
{ int x=5,y=2;
float n=5.0,m=2.0;
cout << operate (x,y); cout << "\n"; cout << operate (n,m); cout << "\n"; return 0; } Solution: 10 2.5 Problem2: Illustrate the concept of function overloading with the help of a C++ program. Solution: #include
#include
void print(char *a)
{puts(a);
}
void print(char *a, char *b)
{puts(a);
puts(b);
}
void print()
{puts(“Welcome Guest”);
}
void main()
{clrscr();
char *name1,*name2; // var. declaration
puts(“Enter Your Name : “); //display message
gets(name1); //accepting string1
puts(“Enter Your Father’s Name : “); //display message
gets(name2); //accepting string2
print(); //function call
print(name1); //function call
print(name1,name2); //function call
getch();
}

UNSOLVED PROBLEMS

Problem 1: What is function overloading?
Problem 2: Illustrate the concept of function overloading with the help of an example.
Problem 3: What do you understand by function overloading? Give an example illustrating its use in a C++ program.

1.4: Classes and Objects
POINTS TO FOCUS
Class:
Collection of objects sharing common properties & behavior.
Or
Simply Collection of similar objects.
Need:
To define real world objects more effectively.( i.e. not only data associated with them but also their associated behavior or operations.

Defining Classes:
Declaration of Class
1. Data Members
2. Member Functions
3. Program access levels
4. Class Tagname
Syntax

class < Class Name >
{
private :
[Var Declaration]
[Function Declarations]
protected :
[Var Declaration]
[Function Declarations]
public :
[Var Declaration]
[Function Declarations]
};
Example :
class A
{ int a;
public:
void getdata()
{
cin>>a;
}
void showdata()
{
cout<>a;
}

void A:: showdata()
{
cout<
#include
#include
class stud
{private: //private members
int sno;
char sname[80];
int cls;
public: //public members
void input(void);
void output(void);
};
void stud :: input(void)
{
cout<<"Enter Sno : "; cin>>sno;
cout<<"Enter Sname : "; gets(sname); cout<<"\nEnter Class :"; cin>>cls;
}
void stud :: output(void)
{
cout<<"\n Sno : "<
#include
#include
class stud
{ int sno;
char sname[80];
public:
void input(void);
void output(void);
int cls;
};
void stud :: input(void)
{ cout<<"Enter Sno : "; cin>>sno;
cout<<"Enter Sname : "; gets(sname); } void stud :: output(void) { cout<<"\n Sno : "<>s.cls;//cls – Being a public member available outside the class
cout<<"\nEnter S.No :"; cin>>s.sno;/*Program gives error as sno – Being a private member not available outside the class */
s.output();
getch();
}
Important Points:
 The private members provide data hiding by preventing us from accessing the data directly
 The class declaration must end with a semi-colon.
 It is important to include the corresponding .h file; otherwise, we will get compile-time errors. In the #include, the name of the file is enclosed in quotes, not in angle brackets. Angle brackets are used for including standard library header files, and quotes are used for including our own header files (this tells the compiler where to look for the header file).
Note:A function declared using the friend keyword is not considered a member of the class in which it is declared a friend (although it can be a member of another class). A friend declaration controls the access a nonmember function has to class data.
Creation of Objects:
Once the class is created, one or more objects can be created from the class as objects are instance of the class.Just as we declare a variable of data type int as:
int x;
Objects are also declared as:
class name followed by object name;
ex e1;
This declares e1 to be an object of class ex .
For example a complete class and object declaration is given below:
class ex
{
private:
int x,y;
public:
void sum()
{
………
………
}
};
main()
{
ex e1;
……………
……………
}
The object can also be declared immediately after the class definition. In other words the object name can also be placed immediately before the closing flower brace symbol } of the class declaration.
Example
class ex
{
private:
int x,y;
public:
void sum()
{
………
………
}
}e1 ;
POINTS TO REMEMBER

 Class specification:, its definition and access specifiers
 Class method definitions: Inside the class definition and outside the class definition
 Refernceing class members
 Array as class member
 Size of object
 Friend function

SOLVED PROBLEMS
Problem 1: Define a class batsman with the following descriptions:
Private members:
bcode 4 digit code number
bname 25 characters
innings, notout, runs Integer type
batavg It is calculate according to the formula: batavg= runs/(innings-notout)
calcavg() Function to return the batavg
Public members:
Readdata() Function to accept values for bcode, name, innings, notout and invoke the function calcavg()
Displaydata() Function to display data members on the screen

Solution: class batsman
{
int bcode;
char bname[25];
int innings, notout, runs;
float batavg;
float calcavg()
{
return (runs/(innings-notout));
}
public :
void readdata();
void displaydata();
};
void batsman::readdata()
{
clrscr();
cout << "Enter the batsman code "; cin >> bcode;
cout << "Enter the batsman name "; gets(bname);; cout << "Enter total innings "; cin >> innings;
cout << "Enter total notout "; cin >> notout;
cout << "Enter total runs "; cin >> runs;
batavg = calcavg();
}
void batsman::displaydata()
{
clrscr();
cout << "Batsman Code " << bcode << endl; cout << "Batsman Name " << bname << endl; cout << "Total innings " << innings << endl; cout << "Total notout " << notout << endl; cout << "Total runs " << runs << endl; cout << "The batting average " << batavg; } Problem2: Define a class Travel with the following descriptions: Private members: T_Code of type sring No_of_Adults of type integer No_of_Children of type integer Distance of type integer TotalFare of type float Public members: A function AssignFare()which calculates and returns the value of the data member TotalFare as follows For each Adult Fare(Rs) For Distance(Km) 500 >=1000
300 <1000 &>=500
200 <500 For each Child the above Fare will be 50% of the Fare mentioned in the above table. For example : If Distance is 750, No_of_Adults = 3 and No_of_Children = 2 Then TotalFare should be calculated as No_of_Adults * 300 + No_of_Children * 150 i.e. 3*300 + 2*150=1200 A function EnterTravel( ) to input the values of the data members T_Code, No_of_Adults, No_of_Children and Distances, and invoke the Assign Fare( ) function. A function ShowTravel( ) which displays the content of all the data members for a Travel. Solution: class Travel { char T_Code[10]; int No_of_Adults; int No_of_Children; int Distance; float TotalFare; public: void EnterTravel(); float AssignFare(); void ShowTravel(); }; void Travel::EnterTravel() { cout << "Enter T_Code: "; gets(T_Code); cout << "Enter No. of Adults: "; cin >> No_of_Adults;
cout << "Enter No. of Children: "; cin >> No_of_Children;
cout << "Distance: "; cin >> Distance;
TotalFare = AssignFare();
}
float Travel::AssignFare()
{float Fare = 0.0;
if (Distance < 500) Fare = (No_of_Adults * 200) + (No_of_Children * 100); else if ((Distance >= 500) && (Distance < 1000)) Fare = (No_of_Adults * 300)+(No_of_Children * 150); else if (Distance >= 1000)
Fare=(No_of_Adults * 500)+(No_of_Children * 250);
return Fare;
}
void Travel::ShowTravel()
{ cout << "TCode: " << T_Code << endl; cout << "No. of Adults: " << No_of_Adults << endl; cout << "No. of Kids: " << No_of_Children << endl; cout << "Distance: " << Distance << endl; cout << "Total fare : " << TotalFare; } UNSOLVED PROBLEMS Problem 1: Define a class TEST in C++ with following description: Private Members TestCode of type integer Description of type string NoCandidate of type integer CenterReqd (number of centers required) of type integer A member function CALCNTR() to calculate and return the number of centers as (NoCandidates/100+1) Public Members A function SCHEDULE() to allow user to enter values for TestCode, Description, NoCandidate & call function CALCNTR() to calculate the number of Centres A function DISPTEST() to allow user to view the content of all the data members Problem 2: Define a class Tour in C++ with the description given below : Private Members : TCode of type string NoofAdults of type integer NoofKids of type integer Kilometres of type integer TotalFare of type float Public Members : A constructor to assign initial values as follows : TCode with the word “NULL” NoofAdults as 0 NoofKids as 0 Kilometres as 0 TotalFare as 0 A function AssignFare ( ) which calculates and assigns the value of the data member TotalFare as follows For each Adult Fare(Rs) For Kilometres 500 >=1000
300 <1000 &>=500
200 <500 For each Kid the above Fare will be 50% of the Fare mentioned in the above table For example : If Kilometres is 850, NoofAdults = 2 and NoofKids = 3 Then TotalFare should be calculated as NumofAdults * 300 + NoofKids * 150 i.e. 2*300 + 3*150=1050 A function EnterTour( ) to input the values of the data members TCode, NoofAdults, NoofKids and Kilometres; and invoke the Assign Fare( ) function. A function ShowTour( ) which displays the content of all the data members for a Tour. Problem 3: Define a class named HOUSING in C++ with the following descriptions: Private Members: REG_NO integer (Ranges 10- 1000) NAME Array of characters (String) TYPE Character COST Float Public Members: Function Read_Data() to read an object of HOUSING type. Function Display() to display the details of an object. Function Draw_Nos() to choose and display the details of 2 houses selected randomly from an array of 10 objects of type HOUSING. Use random function to generate the registration nos. to match with REG_NO from the array. 1.5:Constructors And Destructors POINTS TO FOCUS Constructors: Constructors are member functions of a class which are used to initialize the data members of the class objects.These functions are automatically called when an object of its class is created.There is no need to call these functions. Characteristics of constructors:  The name of a constructor is same as that of class in which it is declared.  Constructors do not have any return type, not even void.  Constructors are always defined in the public section of the class.  They cannot be inherited, though a derived class can call the base class constructor.  A constructor may not be static.  Like other C++ functions, constructors can also have default arguments.  It is not possible to take the address of a constructor.  Member functions may be called  Constructors are not called directly  Constructors show polymorphism in a class Types of Constructors: There are three types of constructors. 1. Default Constructors 2. Parameterized Constructors 3. Copy Constructors 1. Default Constructors A constructor that accepts no parameter is called the default constructors. Example class stud { int sno; char sname[40]; public : stud( ) // Default Constructor { sno=0; strcpy(sname,“new” ); } void getinfo( ) { cin>> sno;
gets(sname);
}
void showinfo( )
{ cout<< sno; puts(sname); } }; The above class stud has sno and sname as data members and three member functions i.e. stud (), getinfo(), showinfo( ) Here stud ( ) is a default constructor since having the same name as that of class and does not accepts any argument, also declared in the pubic section. As we declare the object of this class it will immediately call to the constructor of the class.It automatically assigns the value 0 to variable sno and a “new” to sname. Here consider the following main function void main() { stud obj; // Default constructor called Obj.showinfo(); // displays the value of sno as 0 and sname as “new” Obj.getinfo(); // reads the user given value from the user Obj.showinfo(); // displays the user given values } The default constructors are very useful when we want to create objects without having to type the initial values. With a default constructor objects are created just the same way as variables of other data types are created. 2. Parameterized Constructors A constructor that accepts parameters for its invocation is known as parameterized constructors. Example class stud { int sno; char sname[40]; Public : stud(int s, char n[ ] ) // Paramerized Constructor { sno=s; strcpy(sname,n); } void getinfo( ) { cin>> sno;
gets(sname);
}
void showinfo( )
{ cout<< sno; puts(sname); } }; This means we always specify the arguments whenever we declare an instance ( object) of the class. void main() {stud obj (1, “Ashu”);// Parameterized constructor invoked Obj.showinfo();// displays the value of sno as 1 and sname as “Ashu” Obj.getinfo(); // reads the user given value from the user Obj.showinfo(); // displays the user given values } Just like any other function a parameterized constructor can also have default arguments stud(int s=0, char n[ ]=“new\0” )  A constructor with default arguments is equivalent to a default constructor.  A class must not have a default arguments constructor and default constructor together as it generates ambiguity. 3. Copy Constructors: A copy constructor is a constructor of the form classname( & classname). It is used to initialize an object with the values of another object. The compiler will use the copy constructor whenever -  We initialize an instance using values of another instance of same type.  A function returns an object  A function receives an object as parameter. class stud { int sno; char sname[40]; Public : stud( stud &s) // Copy Constructor { sno=s.sno; strcpy(sname,s.name); } stud( ) // Default Constructor { sno=0; strcpy(sname,“new” ); } void getinfo( ) { cin>> sno;
gets(sname);
}
void showinfo( )
{ cout<< sno; puts(sname); } }; void main() { stud obj; // Default constructor called Obj.showinfo(); // displays the value of sno as 0 and sname as “new” stud objnew(obj);// Copy constructor invoked and initialize the members of object objnew with the // values of object obj i.e. 0 and “new”. Objnew.showinfo(); //displays the value of sno as 0 and sname as “new” Obj.getinfo(); //reads the user given value forobject obj Obj.showinfo(); // displays the user given values for object obj Objnew.getinfo(); // reads the user given value for object objnew Objnew.showinfo(); // displays the user given values for object objnew } Lets have a look: stud obj; // default constructor used stud obj1(23, “Nisha”); // parameterized constructor used stud obj2 = obj; // copy constructor used stud obj3= obj1; // copy constructor used Destructors: A destructor is a class member function that has the same name as the constructor (and the class ) but with a ~ (tilde) in front. ~stud() ; Destructor is used to deinitialize or destroy the class objects. When an object goes out of scope, its destructor is automatically invoked to destroy the object. POINTS TO REMEMBER  Declaring a constructor with arguments hides the default constructor.  A Constructor with default arguments is equivalent to a default constructor.  A constructor declared under private access specifier, makes the class private and object of a private class cannot be created.  A class must not have a default arguments constructor and default constructor together as it generates ambiguity.  Constructors also show the polymorphism as a single class can have multiple constructors of different forms. (Also known as constructor / function overloading.)  Destructors are invoked in the reverse order of invoking constructors. SOLVED PROBLEMS Problem 1: Find the output: #include
#include
#include
#include
class stud
{ int sno;
char sname[40];
public :
stud( ) // Default Constructor
{sno=0;
strcpy(sname,”new”);
cout<<"\nConstructing the object............"; } ~stud( ) // Destructor {cout<<"\nDestructing the object.............."; } void getinfo( ) {cout<<"\nEnter Student No. :"; cin>> sno;
cout<<"\nEnter Student Name :"; gets(sname); } void showinfo( ) {cout<< "\n Student No.: "<=1000
300 <1000 &>=500
200 <500 For each Child the above Fare will be 50% of the Fare mentioned in the above table. For example : If Distance is 750, No_of_Adults = 3 and No_of_Children = 2 Then TotalFare should be calculated as No_of_Adults * 300 + No_of_Children * 150 i.e. 3*300 + 2*150=1200 A function EnterTravel( ) to input the values of the data members T_Code, No_of_Adults, No_of_Children and Distances, and invoke the Assign Fare( ) function. A function ShowTravel( ) which displays the content of all the data members for a Travel. Solution: class Travel { char T_Code[10]; int No_of_Adults; int No_of_Children; int Distance; float TotalFare; public: Travel() { strcpy(T_Code, "NULL"); No_of_Adults = 0; No_of_Children = 0; Distance = 0; TotalFare = 0; } void EnterTravel(); float AssignFare(); void ShowTravel(); void EnterTravel(); float AssignFare(); void ShowTravel(); }; void Travel::EnterTravel() { cout << "Enter T_Code: "; gets(T_Code); cout << "Enter No. of Adults: "; cin >> No_of_Adults;
cout << "Enter No. of Children: "; cin >> No_of_Children;
cout << "Distance: "; cin >> Distance;
TotalFare = AssignFare();
}
float Travel::AssignFare()
{float Fare = 0.0;
if (Distance < 500) Fare = (No_of_Adults * 200) + (No_of_Children * 100); else if ((Distance >= 500) && (Distance < 1000)) Fare = (No_of_Adults * 300)+(No_of_Children * 150); else if (Distance >= 1000)
Fare=(No_of_Adults * 500)+(No_of_Children * 250);
return Fare;
}
void Travel::ShowTravel()
{ cout << "TCode: " << T_Code << endl; cout << "No. of Adults: " << No_of_Adults << endl; cout << "No. of Kids: " << No_of_Children << endl; cout << "Distance: " << Distance << endl; cout << "Total fare : " << TotalFare; } UNSOLVED PROBLEMS Problem 1: Answer the questions (i) and (ii) after going through the following program: class Match {int Time; public: Match() //Function 1 {Time=0; cout<<”Match commences”<
#include
class Bazar
{
char Type[20];
char Product[20];
int Qty;
float Price;
Bazar( ) //Function 1
{ strcpy (Type, “Electronic”);
strcpy(Product, “Calculator”);
Qty = 10;
Price = 225;
}
public :
void Disp( ) //Function 2
{cout << Type << “-“ << Product << “:” << Qty << ”@” << Price << endl; } }; void main( ) { Bazar B ; //Statement 1 B. Disp( ); //Statement 2 } a. Will Statement 1 initialize all the data members for object B with the values given in the Function 1 ? (Yes OR No). If yes, justify your answer suggesting the correction(s) to be made in the above code.(Hint: Based on the characteristics of Constructor declaration) b. What shall be the possible output when the program gets executed? (Assuming, if required the suggested correction(s) are made in the program). Problem 7: Answer the questions (a) and (b) after going through the following class: class Interview { Int Month: Public: Interview(int y) { Month=y;} Interview(Interview & t); }; (a) Create an object, such that it invokes Constructor 1. (b) Write complete definition for Constructor 2. Problem 8: What is a copy constructor? What do you understand by constructor overloading? Problem 9: What is default constructor? How does it differ from destructor? Problem 10: Why is a destructor function required in classes? Illustrate with the help of an example. Problem 11: Answer the questions (i) and (ii) after going through the following class: class Science {char Topic[20]; int Weightage; public: Science ( ) //Function 1 { strcpy (Topic, “Optics” ); Weightage = 30; cout<<“Topic Activated”; } ~Science( ) //Function 2 { cout’<<”Topic Deactivated”; } }; (i)Name the specific features of class shown by Function 1 and Function 2 in the above example. (ii) How would Function 1 and Function 2 get executed? 1.6: Inheritance: Extending Classes POINTS TO FOCUS Inheritance: Creating or deriving a new class using another class as a base is called inheritance in C++. The new class created is called a Derived class and the old class used as a base is called a Base class in C++ inheritance terminology. The derived class will inherit all the features of the base class in C++ inheritance. The derived class can also add its own features, data etc., It can also override some of the features (functions) of the base class, if the function is declared as virtual in base class. Need for Inheritance: Inheritance is one of the important concepts of object-oriented language. There are several reasons why this concept was introduced in object oriented language. Some major reasons are: (i) The capability to express the inheritance relationship which ensures the closeness with the real world model. (ii) Idea of reusability, i.e., the new class can use some of the features of old class. (iii) Transitive nature of inheritance, i.e., it can be passed on further Types of Inheritance: 1. Single Inheritance: A derived class inherits properties from a single base class. Ex: 2. Multiple Inheritance: A derived class inherits properties from two or more base classes. Ex: 3. Multilevel Inheritance: In this type of inheritance, A derived class acts as a base class for other classes. For example, class A inherited in class B and class B is inherited in class C. 4. Hierarchical Inheritance: In this type of inheritance a base class has a number of derived classes.Ex: 5. Hybrid Inheritance: In this type of inheritance, we can have mixture of number of inheritances. (Combination of Multilevel & Hierarchical Inheritance) Visibility Mode:  Private: Public and Protected members of base class inherited as the Private members of the derived class.  Protected: Public and Protected members of base class inherited as the Protected members of the derived class.  Public: Protected members of base class inherited as the Protected members of the derived class and Public members of base class inherited as the Public members of the derived class. Visibility/Accessibility of Inherited Base class Member in Derived class: Consider the following chart to find which members are accessed from the derived class object after inheritance Example PERSON Private Members Person_Id Person_Name Dob Protected Members Calcage( ) Public Members GetInfo( ) ShowInfo( ) Base class STUDENT Private Members Fee Protected Members Annualfee( ) Public Members GetDetail( ) ShowDetail( ) Derived class PERSON Private Members Person_Id Person_Name Dob Protected Members Calcage( ) Public Members GetInfo( ) ShowInfo( ) PRIVATE PUBLIC STUDENT Private Members Fee Protected Members Annualfee( ) Public Members Calcage( ) GetInfo( ) ShowInfo( ) Annualfee( ) GetDetail( ) ShowDetail( ) PROTECTED STUDENT Private Members Fee Calcage( ) GetInfo( ) ShowInfo( ) Protected Members Annualfee( ) Public Members GetDetail( ) ShowDetail( ) STUDENT Private Members Fee Protected Members Calcage( ) GetInfo( ) ShowInfo( ) Annualfee( ) Public Members GetDetail( ) ShowDetail( ) Implementing Inheritance: Syntax: Single Inheritance class < Derived Class Tag Name >:
{
Derived Class Definition
};

Multiple Inheritance

class < Derived Class Tag Name >:,,…….,
{
Derived Class Definition
};

Accessibility of members by an object of a derived class:
After derivation all the data members and member functions available under public mode of derived class are directly accessible by object of a derived class.

#include
#include
#include
class person
{ int id;
char name[20];
public :
person(int k,int m)
{
cout<<"\n constructing person ...."; id=k; cls=m; } ~person() { cout<<"\n destructing person ............"; } int cls; void getinfo() { cout<<"\n enter id : ";cin>>id;
cout<<"\n enter name : "; gets(name); } void showinfo() { cout<<"\nid : "<>fee;
}
void showfee()
{
showinfo();
cout<<"\nMonthly fee :"<>s.cls;
s.getfee();
s.showfee();
cout<<"\nClass: "<
#include
#include
class person
{ int id;
char name[20];
public :
void getinfo()
{
cout<<"\n enter id : ";cin>>id;
cout<<"\n enter name : "; gets(name); } void showinfo() { cout<<"\nid : "<>fee;
}
void showfee()
{ showdetail();
cout<<"\nMonthly fee :"<
#include
#include
class person
{ int id;
char name[20];
public :
int cls;
void getinfo()
{
cout<<"\n enter id : ";cin>>id;
cout<<"\n enter name : "; gets(name); } void showinfo() { cout<<"\nid : "<>fee;
}
void showfee()
{
showinfo();
showcourse();
cout<<"\nMonthly fee :"<
#include
#include
class person
{ int id;
char name[20];
public :
int cls;
void getinfo()
{
cout<<"\n enter id : ";cin>>id;
cout<<"\n enter name : "; gets(name); } void showinfo() { cout<<"\nid : "<>fee;
}
void showfee()
{
showcourse();
cout<<"\nMonthly fee :"<
void main()
{
fstream F(“Temp.txt”,ios::in|ios::out);
F<<“Welcome to Jaipur”; cout<
void main()
{
fstream F(“Report.txt”,ios::in|ios::out);
F<<“Text File”; F.seekg(-3,ios::cur); F<<“US”; F.close(); } //The contents of the text file is “Text FUSe” Example of a Binary File /*Binary files are generally used to store the contents of an objects of a structure or a class.*/ #include
class Stu
{ int Adno;
char Name[21];
float Pct;
public:
void NewStudent();
void ShowStudent();
float RetPct(){ return Pct; }
};
void main()
{
fstream F(“Report.txt”,ios::in|ios::out|ios::binary);
Stu S;
S.NewStudent();
F.write((char*) &S, sizeof(S));
F.seekg(0);
while(!F.eof())
{
F.read((char*) &S, sizeof(S));
F.ShowStudent();
}
F.close();
}
Using File I/O:
Objective: To insert some data on a text file

Program ABC.txt file contents
#include
using namespace std;
int main()
{
ofstream fout;
fout.open(“abc.txt”);
fout<<"This is my first program in file handling"; fout<<"\n Hello again"; fout.close(); return 0; } This is my first program in file handling Hello again Reading data from a Text File: #include
#include
#include
using namespace std;
int main()
{
ifstream fin;
char str[80];
fin.open(“abc.txt”);
fin>>str; // read only first //string from file
cout<<"\n From File :"<
#include
#include
using namespace std;
int main()
{
char ch;
ifstream fin;
fin.open(“abc.txt”);
while(!fin.eof())// using eof()function
{
fin.get(ch);
cout<
#include
#include
using namespace std;
int main()
{
char ch;
ifstream fin;
fin.open(“abc.txt”);
while(fin) // file object
{fin.get(ch);
cout<
#include
#include
using namespace std;
int main()
{ char str[100];
ifstream fin;
fin.open(“c:\\abc.txt”);
while(!fin.eof())
{
fin.getline(str,99);
cout<
#include
#include
using namespace std;
int main()
{ char ch;
ifstream fin;
fin.open(“file6.cpp”);
while(!fin.eof())
{
fin.get(ch);
cout<
#include
using namespace std;
struct student
{ int roll ;
char name[30];
char address[60];
};
int main()
{ student s;
ofstream fout;
fout.open(“student.dat”);
cout<<"\n Enter Roll Number :"; cin>>s.roll;
cout<<"\n Enter Name :"; cin>>s.name;
cout<<"\n Enter address :"; cin>>s.address;
fout.write((char *)&s,sizeof(student));
fout.close();
return 0;
}
To Read data from a binary File using read( ) member function
#include
#include
#include
using namespace std;
struct student
{ int roll ;
char name[30];
char address[60];
};
int main()
{ student s;
ifstream fin;
fin.open(“student.dat”);
fin.read((char *)&s,sizeof(student));
cout<<"\n Roll Number :"<
#include
using namespace std;
class student
{ int roll ;
char name[30];
char address[60];
public:
void read_data( ); // member function prototype
void write_data( ); // member function prototype
};
void student::read_data( ) // member function defintion
{ cout<<"\n Enter Roll :"; cin>>roll;
cout<<"\n Student name :"; cin>>name;
cout<<"\n Enter Address :"; cin>>address;
}
void student:: write_data()
{ cout<<"\n Roll :"<
#include
#include
using namespace std;
class student
{ int roll ;
char name[30];
char address[60];
public:
void read_data( ); // member function prototype
void write_data( ); // member function prototype
};
void student::read_data( ) // member function definition
{ cout<<"\n Enter Roll :"; cin>>roll;
cout<<"\n Student name :"; cin>>name;
cout<<"\n Enter Address :"; cin>>address;
}
void student:: write_data()
{ cout<<"\n Roll :"<
#include
#include
using namespace std;
class student
{ int admno;
char name[30];
char address[60];
public:
void read_data()
{ cout<<"\n Enter Admission No :"; cin>>admno;
fflush(stdin);
cout<<"\n Enter Name :"; cin.getline(name,29); fflush(stdin); cout<<"\n Enter Address :"; cin.getline(address,59); } void write_data() { cout<<"\n\n Admission No :"<>temp_admno;
while(fin.read((char *)&s,sizeof(student)))
{ if (temp_admno==s.get_admno())
{
s.read_data();
}
fout.write((char *)&s,sizeof(student));
}
fin.close();
fout.close();
remove(“student.dat”);
rename(“temp.dat”,”student.dat”);
return;
}
void modify_alternate_method()
{ student s;
int temp_admno;
fstream file;
file.open(“student.dat”,ios::in|ios::out|ios::ate|ios::binary);
cout<<"\n Enter admno to modify :"; cin>>temp_admno;
file.seekg(0); // one method to reach at begining
// long n = file.tellg(); // find out total no of bytes
// file.seekg((-1)*n,ios::end); // move backward total no of bytes from end
while(file.read((char*)&s,sizeof(student)))
{ if(temp_admno == s.get_admno())
{ s.read_data();
int n = -1*sizeof(student);
file.seekp(n,ios::cur);
file.write((char *)&s,sizeof(student));
}
}
file.close();
return;
}
void delete_record(void)
{ int temp_admno;
student s;
ifstream fin;
ofstream fout;
fin.open(“student.dat”);
fout.open(“temp.dat”);
system(“cls”);
cout<<"\n Enter admission No to Delete :"; cin>>temp_admno;
while(fin.read((char *)&s,sizeof(student)))
{
if (temp_admno!=s.get_admno())
fout.write((char *)&s,sizeof(student));
}
fin.close();
fout.close();
remove(“student.dat”); // stdio.h
rename(“temp.dat”,”student.dat”); // stdio.h
return;
}
void search_record()
{ int found=0;
student s;
int temp_admno;
ifstream fin(“student.dat”);
cout<<"\n Enter Admno to search :"; cin>>temp_admno;
while(fin.read((char*)&s,sizeof(student)))
{
if(temp_admno==s.get_admno())
{
found=1;
s.write_data();
}
}
fin.close();
if(found ==0)
cout<<"\n Admission No. "<>choice;
switch(choice)
{ case 1: system(“cls”);
write_to_file();
break;
case 2: read_from_file();
getch();
break;
case 3: modify_record();
break;
case 4: modify_alternate_method();
break;
case 5: delete_record();
break;
case 6: count_record();
break;
case 7: search_record();
break;
case 8: break;

default: cout<<"\n Wrong choice.... Try again"; getch(); } }while(choice!=8); return 0; } POINTS TO REMEMBER  Stream class: Class hierarchy,  functions belongs to stream classes,  Opening and Closing files  File Modes.  Sequential Input/Output with Files: get( ), getline( ) and put( ) functions, and checking end of file using EOF.  Reading and Writing Class objects  File Pointers and Random Access: seekg( ), seekp( ), tellg( ), tellp( )  Basic Operations on Binary Files: Searching, Appending, Inserting, Modifying, Deleting records SOLVED PROBLEMS Problem 1: Differentiate between text file and binary file. Solution: Test file: In these types of files all the data is firstly converted into their equivalent char and then it is stored in the files. Binary file: In these types of files all the data is stored in the binary format as it is stored by the operating system. So no conversion takes place. Hence the processing speed is much more than text files. Problem2: What is the difference between ios::out and ios::app mode? Solution: ios::out is output mode which is default with ofstream and files can be written only. ios::app preserves previous contents and write data at the end ( move forward only) Problem3: Write a user defined function in C++ to read the content from a text file STORY.TXT, count and display the number of alphabets present in it. Solution: void display() { ifstream ifile; afile.open("STORY.TXT"); char ch; int c=0; while(ifile) { ifile.get(ch); if (isalpha(ch)) c++; } cout << "The number of alphabets are " << c; } Problem4: AssumJe a text file named TEXT1.TXT already contains some text written into it, write a function named vowelwords(), that reads the file TEXT1.TXT and create a new file named TEXT2.TXT, which shall contain only those worgs from the file TEXT1.TXT which don’t start with an uppercase vowel(). Solution: void vowelwords() { fstream afile,bfile; char ch,ch1; afile.open("TEXT1.TXT", ios::in); bfile.open("TEXT2.TXT", ios::out); ch1 = ' '; clrscr(); while(afile) { afile.get(ch); cout << "\nOutside " << ch; if((ch =='A')||(ch =='E')||(ch=='I')||(ch=='O')||(ch=='U')&&(ch1==' ')) { while(ch != ' ') { afile.get(ch); ch1 = ch; if(ch == ' ') break; } } else bfile.put(ch); } afile.close(); bfile.close(); } Problem5: Given a binary file STUDENT.DAT, containing records of the following class Student type: class Student { char S_Admno[10]; // Admission number of student char S_Name[30]; // Name of student int Percentage; // Marks Percentage of student public : void EnterData() { gets(S_Admno); gets(S_Name); cin >> Percentage;
}
void DisplayData()
{
cout << setw(12) << S_Admno; cout << setw(32) << S_Name; cout << setw(3) << Percentage << endl; } int ReturnPercentage() {return Percentage;} }; Write function in C++, that would read contents of file STUDENT.DAT and display the details of those Students whose Percentage is above 25. Solution: void Perabove75() { Student std; fstream File; File.open("STUDENT.DAT", ios::binary|ios::in); while (File.read((char *)&std, sizeof(Student))) if (std.ReturnPercentage() > 75)
std.DisplayData();
File.close();
}

UNSOLVED PROBLEMS
Problem 1: Observe the program segment carefully and answer the question that follows:
class item
{int item_no;
char item_name[20];
public:
void enterDetail( );
void showDetail( );
int getItem_no( ){ return item_no;}
};
void modify(item x, int y )
{fstream File;
File.open( “item.dat”, ios::binary | ios::in | ios::out) ;
item i;
int recordsRead = 0, found = 0;
while(!found && File.read((char*) &i , sizeof (i)))
{
recordsRead++;
if(i . getItem_no( ) = = y )
{
_________________________//Missing statement
File.write((char*) &x , sizeof (x));
found = 1;
}
}
if(! found)
cout<<”Record for modification does not exist” ; File.close() ; } If the function modify( ) is supposed to modify a record in the file “ item.dat “, which item_no is y, with the values of item x passed as argument, write the appropriatestatement for the missing statement using seekp( ) or seekg( ), whichever is needed, inthe above code that would write the modified record at its proper place. Problem 2: Observe the program segment carefully and answer the question that follows: class member {int member_no; char member_name[20]; public: void enterDetail( ); void showDetail( ); int getMember_no( ){ return member_no;} }; void update(member NEW ) {fstream File; File.open( “member.dat”, ios::binary|ios::in|ios::out) ; member i; while(File .read((char*) & i , sizeof (i))) { if(NEW . getMember_no( ) = = i . getMember_no( )) { _________________________//Missing statement File.write((char*) &NEW , sizeof (NEW)); } } File.close() ;} If the function update( ) is supposed to modify the member_name field of a record in the file “member.dat” with the values of member NEW passed as argument, write theappropriate statement for the missing statement using seekp() or seekg(), whichever isneeded, in the above code that would write the modified record at its proper place. Problem 3: Given the binary file STUDENT.DAT , containing the records of the following class: class student {int roll_no; char name[20]; float percent; public: void getData( ); void show( ); float returnPercent( ) {return percent; } }; Write a function BELOW75( ) in C++ , that would count and display the records of thosestudents whose score is below 75 percent. Problem 4: class book {int book_no; char book_name[20]; float price; public: void enter_book_Details( ) { cin>> book_no>> price; gets(book_name);
}
void show_book_Details( );
};
Assuming a binary file “BOOK.DAT” contains objects belonging to class book, write a user-defined function to add more records to the end of it.
Problem 5: Write a function in C++ to count and display the number of student records stored in the binary file “Student,dat” . Assume that student is a structure and 10 bytes of memory is required to store each student record.
Problem 6: Write a function in C++ to count the number of uppercase alphabets present in a text file“STORY.TXT”.
Problem 7: Write a function in C++ to count the number of alphabets present in a text file “XY.TXT”.
Problem 8: Write a function in C++ to count and display the number of lines starting with alphabet ‘A’ in a text file “MYFILE.TXT”.
Problem 9: Write a function in C++ to count the number of words present in the text file “MyFile.txt”. Assume that each word is separated by a blank space and no blank space appears in the beginning and at the end of the file.
Problem 10: A librarian maintains the record of books in a file named as “STOCK_BOOK.DAT”. Write a function in C++ to delete a record for book_no 10.
Problem 11: Given the binary file TELEPHONE.DAT , containing the records of the following classDirectory:
class Directory
{
char name[20];
char address[30];
char areaCode[5];
char phone_no[15];
public:
void register( );
void show( );
int checkCode( char AC[] )
{
return strcmp(areaCode, AC);
}
};
Write a function COPYABC( ) in C++ , that would copy only those records having areaCode as“123” from TELEPHONE.DAT to TELEBACK.DAT.
Problem 12: Write a function in C++ to count the number of vowels present in a text file STORY.TXT”.
Problem 13: Observe the program segment carefully and answer the question that follows:
class item
{
int item_no;
char item_name[20];
public:
void enterDetail( );
void showDetail( );
int getItem_no( ){ return item_no;}
};
void modify(item x )
{
fstream File;
File.open( “item.dat”, ios::binary|ios::in|ios::out ) ;
item i;
while(File .read((char*) & i , sizeof (i)))//Statement 1
{
if(x . getItem_no( ) = = i . getItem_no( ))
{
File.seekp(File.tellg( ) – sizeof(i));
File.write((char*) &x , sizeof (x));
}
}

File.close() ;
}
If the function modify( ) modifies a record in the file “ item.dat” with the values of item xpassed as argument, rewrite statement 1 in the above code using ios::eof( ) , so as to modifyrecord at its proper place.
Problem 14: A file named as “STUDENT.DAT” contains the student records, i.e. objects of class student.Assuming that the file is just opened through the object FILE of fstream class, in the requiredfile mode, write the command to position the get pointer to point to fifth record from thebeginning.

1.8: Pointers
POINTS TO FOCUS
Introduction:
A pointer is a variable which holds a memory address, typically the location of another variable. Any variable declared in a program has two components:
(i) Address of the variable
(ii) Value stored in the variable
For example: int p = 21;
The above declaration tells the C++ compiler for
(i) Reservation of space in memory for storing the value.
(ii) Associating the name p with this memory location.
(iii) Storing the value 21 at this location.
Location name  p
Value at location  21
Location  1001
Static Memory Allocation:
When the amount of memory to be allocated is known in advance and memory is allocated during compilation, it is referred to as static memory allocation. For example:
int a=10;
Dynamic Memory Allocation:
When the amount of memory to be allocated is not known in advance and memory is allocated during execution, it is referred to as dynamic memory allocation. There are two operators new and delete in C++ for dynamic memory allocation. The operator new allocates memory dynamically whereas the operator delete is used for deallocation, when the memory is no longer in use.
Declaration and Initialization of Pointers:
A pointer variable name is preceded by an asterisk (*) sign. The data type of the pointer should be the same as the data type of the variable to which it will point.
Syntax: type *var_name;
Example:
int *iptr; //declaration of an integer pointer
int p = 21;
iptr= &p; //iptr stores the address of integer variable p

C++ has two unary operators for referencing to the components of any variable. & (address operator) returns the address of the variable and * (indirection operator) returns the value stored at any address in the memory.
Address of p  1050 int p =21, j;
p  21 int * iptr;

iptr  1050 iptr=&p;

j  21 j=p;

new operator:
Syntax: pointer variable = new data_type;
Example:
char *cptr;
cptr = new char;
char *captr;
captr = new char[10];
delete operator:
Syntax: delete pointer variable;
Example:
delete cptr;
delete [] captr;
C++ has the concept of constant pointer and pointer to a constant. For example:
char * const cptr1=”Computer Science”; //constant pointer
Here the address of cptr1 cannot be modified.
int const *iptr=&x; //pointer to a constant
const char * const cptr2=”KV”; //pointer to a constant
Here the constant value, to which the pointer pointing to, can not be modified.
A NULL pointer is a pointer which indicates that it is not pointing to any valid memory address. For example:
int *iptr=NULL;
Pointer Arithmetic:
Only addition and subtraction may be performed on pointers. All the pointers increases and decreases by the length of the data type they point to. Adding 1 to a pointer adds the size of pointer’s base type. Let iptr be an integer pointer, currently pointing to memory address 2002. If the int size is 2 bytes, then after the execution of
iptr++;
iptr will be pointing to 2004.
Arrays and Pointers:
An array name is equivalent to a pointer pointing to the first element of array. The address of the first byte is called Base Address. In C++ we may have an array of pointers also. If an array name (a pointer actually) is incremented, it points to the next element of the array.
Functions and Pointers:
A function may return a reference or a pointer variable. Pointer to a function can be passed to function, returned from functions.
Structure and Pointers:
C++ allows pointers to structures like other data types and these pointers to structures are known as structure pointers.
Syntax: struct_name *struct_pointer;
The members of the structure are accessed by using -> (arrow operator).
Syntax: struct_pointer->struct_member;
Self Referencial Structures:
When an element of a structure is declared as a pointer to the structure itself, this type of structure is called self-referential structure. Example:
struct node
{ char data[20];
node *next;
};
 The node structure contains both a data member and a pointer to the next node structure (hence, self-referential)

 next of first node points to next node
 next of last node = NULL
 The data structure itself consists of one or more nodes, “linked” by pointers
Objects and Pointers:
C++ allows us to have pointers to objects known as object pointers.
Syntax: class_name *object_pointer;
This Pointers:
While defining a class the space is allocated for member functions only once and separate space is allocated for each object. There exists a serious problem i.e. which object’s data member is to be manipulated by any member function.
The “this” pointer is an already created object pointer that points to currently calling object. The this pointer is automatically passed to a member function when it is called.
For Example:
#include
#include
class employee
{ char name[20];
float salary;
public:
employee(char *n, float s)
{ strcpy(name,s);
salary=s;
}
employee greater(employee &e)
{ if(e.salary>=salary)
return &e;
else
return this;
}
void display()
{
cout<<”\nName:”<display();
emp=e2.greater(e3);
e2->display();
}
Output:
Name:ABC
Salary:10000
Name:PQR
Salray:20000
Pointers to Pointers:
We can define pointer pointing to another pointer that points to the target value.
Syntax: int **ptr_to_ptr;
In the case of pointer to a pointer, the first pointer contains the address of the second pointer, which points to the objects that contains the value desired.

POINTS TO REMEMBER
 Pointer Declaration and Initialization
 Dynamic allocation Operators: new and delete,
 Creating dynamic array, array pointer, pointer arithmetic.
 String Pointer
 Const Pointer, Structure Pointer, this Pointer
 Self referencial structure

SOLVED PROBLEMS
Problem 1: What will be the output of the following program:
#include
void main()
{int Numbers[] = {2,4,8,10};
int *ptr = Numbers;
for (int C = 0; C<3; C++) {cout<< *ptr << “@”; ptr++; } cout<
struct Game
{
char magic[20];
int score;
};
void main()
{ Game M={“Tiger”, 500};
Char * Choice;
Choice =M.Magic;
Choice[4]=’P’;
Choice[2]=’L’;
M.Score+=5;
cout<< M.Magic<
void main()
{int X[] = {10,25,30,55,110};
int *p = X;
while(*p< 110) {if (*p%3!=0) *p =*p + 1; else *p =*p + 2; p++; } for(int i=4;i>=1;i–)
{ cout<
void main( )
{ int a =32, *ptr = &a;
char ch = ‘A’, &cho = ch;
cho += a; *ptr += ch;
cout << a << “ “<< ch << endl; } Problem 2: Give the output of the following program (Assuming all required header files are included in the program): void main( ) {int array [ ]={ 2, 3, 4, 5}; int *arptr = array; int value =*arptr; value = *arptr++; cout << value <<’\t’; value = *arptr; cout << value <<’\t’; value = * ++arptr; } Problem 3: Find the output of the following program: #include
#include
class state
{ char *state_name;
int size;
public:
state()
{ size=0;
state_name = new char [size+1];
}
state (char *s)
{
size = strlen(s);
state_name = new char[size + 1];
strcpy(state_name, s);
}
void display( )
{ cout<
#include
#include
#include
void changestring(char text[], int &counter)
{char *ptr = text;
int length=strlen(text);
for(;counter
#include
class country
{ char *country name;
int length;
public:.
country ( )
{length =0; country_name=new char [length+1];}
country (char *s)
{length = strlen(s);
country_name=new char [length +1];
strcpy (country_name, s);
}
void display ( )
{cout<< country_name <
#include
void main()
{int arr[10],n,i;
clrscr();
cout<<”\n Enter the number of elements:”; cin>>n;
cout<<”\n Enter “ << n <<” elements:”; for(i=0; i>arr[i];
cout<<”\n Entered array is:\n”; for(i=0; i
#include
int linear_search(int [],int,int);
void main()
{ int A[20],N, index,i,ITEM;
clrscr();
cout<<”Enter number of elements:”; cin>>N;
cout<,”\nEnter the elements:”; for(int i=0; i>A[i];
cout<<”\n Enter element to be searched:”; cin>>ITEM;
index = linear_search(A,N,ITEM);
if(index=-1)
cout<<”\n Element not Found:”; else cout <<””\n Element found at Index “<
#include
int binary_search(int [],int,int);
void main()
{ int A[20],N, index,i,ITEM;
clrscr();
cout<<”Enter number of elements:”; cin>>N;
cout<,”\nEnter the elements:”; for(int i=0; i>A[i];
cout<<”\n Enter element to be searched:”; cin>>ITEM;
index = binary_search(A,N,ITEM);
if(index=-1)
cout<<”\n Element not Found:”; else cout <<””\n Element found at Index “<a[mid])
beg=mid+1;
else
last=mid-1;
}
return -1;
}
3. Insertion:Insertion of new element can be done at a specific position and if the array is sorted insertion of the element will be at appropriate place. Insertion is not possible if the array is already full which is called “OVERFLOW” but replacement of an existing element is possible.
//function for inserting an element in an array at a specific position
void insert(int a[],int n, int index,int item)
{ for(int i=n-1; i>=index;i–)
a[i+1]=a[i];
a[index]=item;
}
Note: Check the condition for overflow in main( ) function.
//function for inserting an element in a sorted array
void insert(int a[],int n, int item)
{int i,pos;
if(item>=a[n-1])
a[n]=item;
else
{pos=0;
While(a[pos]<=item) pos++; for(i=n-1; i>=pos; i–)
a[i+1]=a[i];
a[pos]=item;
}
4. Deletion:Deletion of an element means its removal from the array. Deletion may not be possible if the element does not exist. Deletion can be done in any one of the following ways:
(i) Deletion of an element from a specific position
(ii) Deletion of an element from an unsorted array
(iii) Deletion of an element from a sorted array.
//function for deleting an element in a sorted array
int Del_element(int a[],int n, int item)
{ int i,pos=0;
If(itema[n-1])
return -1;
while(a[pos]<=item) Pos++; if(a[pos]==item) {for(i=pos+1; i=0)
{a[j+1]=a[j];
j–;
}
a[j+1]=temp;
cout<,”\n After Pass “<a[j+1])
{temp=a[j];
A[j]=a[j+1];
A[j+1]=temp;
}
}
cout<,”\n After Pass “<
#include
void main()
{int arr[10][10],m,n,i,j;
clrscr();
cout<<”\n Enter the number of rows:”; cin>>m;
cout<<”\n Enter the number of columns:”; cin>>n;
cout<<”\n Enter “ << m*n <<” elements:”; for(i=0; i>arr[i][j];
cout<<”\n Entered array is:\n”; for(i=0; i=size)
a2[i][j]=0;
else a2[i][j]= arr[j];
cout<
#include
#include
const M = 10;
const N = 10;
void display_diagonals(int MATRIX[M][N], int r, int c)
{ clrscr();
// Finding the diagonal from left index to right
cout << "Diagonal One : "; for(int i=0; i=0; j–)
{ cout << MATRIX[i][j] << " "; i++; } } getch(); } void main() { int MATRIX[M][N]; int i, j; int r, c; cout << "Enter total no. of rows: "; cin >> r;
cout << "Enter total no. of columns: "; cin >> c;
if ((r == c) && ((r%2==1) && (c%2==1)))
{ cout << "Input steps"; cout << "\n\Enter the element in the array\n"; for(i=0; i> MATRIX[i][j]; }
}
else
return;
display_diagonals(MATRIX, r, c);
}
Problem5: Given array :89,20,31,56,20.
Sort this array in ascending order using (i) Bubble Sort (ii) Insertion sort
Solution: Given array is 89,20,31,56,20
(i) Bubble sort
I 20,89,31,56,20
II 20,31,89,56,20
III 20,31,56,89,20
IV 20,31,56,20,89
V 20,31,56,20,89
VI 20,31,56,20,89
VII 20,31,20,56,89
VIII 20,31,20,56,89
IX 20,31,20,56,89
X 20,20,31,56,89
(ii) Insertion Sort
I -∞ ,89,20,31,56,20
II – ∞,20,89,31,56,20
III – ∞20,31,89,56,20
IV -∞,20,31,89,56,20
V – ∞20,20,31,56,89
Problem6: Sort the following list of numbers manually using the Insertion sort method 80,17,27,58,20,66,55
Solution: The contents of the list after each pass are shown below:
Pass
1. 80 17 27 58 20 66 55
2. 17 80 27 58 20 66 55
3. 17 27 80 58 20 66 55
4. 17 27 58 80 20 66 55
5. 17 20 27 58 80 66 55
6. 17 20 27 58 66 80 55
7. 17 20 27 55 58 66 80
Problem7: Consider the sorted list = 1,4,7,15,19,23,35,41. Manually search for the value 23 using binary search.
Solution: Steps: 1. LB=0, UB=7, Mid=3
Since, value >list[3],therefore LB=Mid+1
2. LB=4, UB=7 MID=5

UNSOLVED PROBLEMS

Problem 1: Write a function to search an element using Binary Search.
Problem 2: Write a function in C++ which accepts an integer array and its size as arguments and swaps the elements of every even location with its odd location
eg., if the array initially contains
2, 4, 1, 6, 5, 7, 9, 2, 3, 10
then it should contain
4, 2, 6, 1, 7, 5, 2, 9, 10, 3
Problem 3: Write a function in C++ to combine the contents of two equi-sized arrays A and B by computing their corresponding elements with the formula 2 *A[i]+3*B[i], where value I varies from 0 to N-1 and transfer the resultant content in the third same sized array.
Problem 4: Write a function in C++ to merge the contents of two sorted arrays A and B, into the third array C. Assume array A is sorted in ascending order, B is sorted in descending order, the resultant array is required to be in ascending.
Problem 5: An array MAT[30][10] is stored in the memory row wise with each element occupying 8 bytes of memory. Find out the base address and the address of the element MAT[15][5], if the location of MAT[5][7] is stored at the address 3000.
Problem 6: An array X[15][10] is stored in memory with each element requiring 2 bytes of storage. If the base address of array is 2000, calculate the location of X [7][8] when the array is stored by (1) row major order (2) column major order.
Problem 7: An array ARR[15][35] is stored in the memory along the column with each of its elements occupying 8 bytes. Find out the base address and the address of an element ARR[2][5] , if the location is stored at the address 4000
Problem 8: Write a function in c++ which accepts a 2D array of integers, number of rows and number of columns as arguments and assign the elements which are divisible by 3 or 5 into a one dimensional array of integers.
If the 2D array is
The resultant 1D arrays is 12 , 3 , 9 , 24 , 25 , 45 , 9 , 5 , 18

Problem 9: Write a function in C++ which accepts a 2D array of integers and its size as arguments and displays the elements of the middle row and the elements of middle column.
Example if the array content is
3 5 4
7 6 9
2 1 8
Output through the function should be:
Middle row: 76 9 Middle column: 5 6 1
Problem 10: Write a user defined function named upperhalf( ) which takes a 2D array A, with size n rows and n columns as arguments and print the upper half of the matrix
1 2 3 1 2 3
6 7 8 7 8
2 3 4 4

2.2: Stack
POINTS TO FOCUS
Introduction:
The term list means a linear collection of elements. Array is an example of linear lists. A linked list is a collection of data elements, called nodes pointing to the next nodes by means of pointers. Each node is divided into two parts DATA (info) and LINK (next). It is a dynamic data structure as it can grow or shrink.
Abstract Idea of Stack:
The stack is a very common data structure used in programs. By data structure, we mean something that is meant to hold data and provides certain operations on that data.
One way to describe how a stack data structure behaves is to look at a physical analogy, a stack of books…

Now, a minimal set of things that we might do with the stack are the following:
Place a book on the top… Take one off the top… See if the stack is empty… NOT Empty, there are books on the stack!
We’ll consider other, more complex operations to be inappropriate for our stack. For example, pulling out the 3rd book from the top cannot be done directly because the stack might fall over.
Abstraction:
Stacks hold objects, usually all of the same type. Most stacks support just the simple set of operations we introduced above; and thus, the main property of a stack is that objects go on and come off of the top of the stack.
Here are the minimal operations we’d need for an abstract stack (and their typical names):
1. push: Places an object on the top of the stack.
2. pop: Removes an object from the top of the stack and produces that object.
3. IsEmpty: Reports whether the stack is empty or not.
Because we think of stacks in terms of the physical analogy, we usually draw them vertically (so the top is really on top).
Order produced by a stack:
Stacks are linear data structures. This means that their contexts are stored in what looks like a line (although vertically). This linear property, however, is not sufficient to discriminate a stack from other linear data structures. For example, an array is a sort of linear data structure. However, you can access any element in an array–not true for a stack, since you can only deal with the element at its top.
One of the distinguishing characteristics of a stack, and the thing that makes it useful, is the order in which elements come out of a stack. Let’s see what order that is by looking at a stack of letters…
Suppose we have a stack that can hold letters, call it stack. What would a particular sequence of push and pops do to this stack?
We begin with stack empty:
—–
stack
Now, let’s perform stack.push(A), giving:
—–
| A | <-- top ----- stack Again, another push operation, stack.push(B), giving: ----- | B | <-- top ----- | A | ----- stack Now let's remove an item, letter = stack.pop(), giving: ----- ----- | A | <-- top | B | ----- ----- stack letter And finally, one more addition, stack.push(C), giving: ----- | C | <-- top ----- | A | ----- stack You'll notice that the stack enforces a certain order to the use of its contents, i.e., the Last thing In is the First thing Out. Thus, we say that a stack enforces LIFO order. Now we can see one of the uses of a stack...To reverse the order of a set of objects. Alogrithm of Stack Operations: Adding into stack procedure add(item : items); {add item to the global stack stack; top is the current top of stack and n is its maximum size} begin if top = n then stackfull; top := top+1; stack(top) := item; end: {of add} Deletion in stack procedure delete(var item : items); {remove top element from the stack stack and put it in the item} begin if top = 0 then stackempty; item := stack(top); top := top-1; end; {of delete} Array Implementation of Stack: Array is a static data structure. So the space is allocated according to the maximum number of elements present at that point. Pushing an element in the stack is possible through top only. In case the array is full and no new element can be accommodated, it is called STACK-FULL. This condition is called OVERFLOW.Popping i.e. deletion of an element takes place from the top. In case the last element is popped, the stack becomes empty. If one tries to delete an element from an empty stack, this is called UNDERFLOW. Let's think about how to implement this stack in the C++ programming language. First, if we want to store letters, we can use type char. Next, since a stack usually holds a bunch of items with the same type (e.g., char), we can use an array to hold the contents of the stack. Now, consider how we'll use this array of characters, call it contents, to hold the contents of the stack. At some point we'll have to decide how big this array is; keep in mind that a normal array has a fixed size. Let's choose the array to be of size 4 for now. So, an array getting A, then B, will look like: ----------------- | A | B | | | ----------------- 0 1 2 3 contents We need to keep track of the top of the stack since not all of the array holds stack elements. One choice is to use an integer, top, which will hold the array index of the element at the top of the stack. Example Again suppose the stack has (A,B) in it already... stack (made up of 'contents' and 'top') ----------------- ----- | A | B | | | | 1 | ----------------- ----- 0 1 2 3 top contents Since B is at the top of the stack, the value top stores the index of B in the array (i.e., 1). Now, suppose we push something on the stack, stack.push('C'), giving: stack (made up of 'contents' and 'top') ----------------- ----- | A | B | C | | | 2 | ----------------- ----- 0 1 2 3 top contents (Note that both the contents and top part have to change.) So, a sequence of pops produce the following effects: 1. letter = stack.pop() 2. stack (made up of 'contents' and 'top') 3. ----------------- ----- ----- 4. | A | B | | | | 1 | | C | 5. ----------------- ----- ----- 6. 0 1 2 3 top letter 7. contents 8. letter = stack.pop() 9. stack (made up of 'contents' and 'top') 10. ----------------- ----- ----- 11. | A | | | | | 0 | | B | 12. ----------------- ----- ----- 13. 0 1 2 3 top letter 14. contents 15. letter = stack.pop() 16. stack (made up of 'contents' and 'top') 17. ----------------- ----- ----- 18. | | | | | | -1| | A | 19. ----------------- ----- ----- 20. 0 1 2 3 top letter 21. contents so that you can see what value top should have when it is empty, i.e., -1. Let's use this implementation of the stack with contents and top. What happens if we apply the following set of operations? 22. stack.push('D') 23. stack.push('E') 24. stack.push('F') 25. stack.push('G') giving: stack (made up of 'contents' and 'top') ----------------- ----- | D | E | F | G | | 3 | ----------------- ----- 0 1 2 3 top contents and then try to add H withstack.push('H')will result into stck overflow. Program to show PUSH and POP operation on a stack (Array implementation) //PUSH and POP operations on a stack-array implementation #include
#include
#include # define SIZE 20
void PUSH(int stack[],int item, int &top)
{if(top==size-1)
{cout<<”\n OVERFLOW”; exit(1); } else { top++; stack[top]=item; } } int POP(int stack[], int &top) { if(top==-1) { cout<<”\n UNDERFLOW”; Exit(1); } else { int ret=stack[top]; top--; } return (ret); } void DISPLAY(int stack[], int top) { if (top==-1) cout<,”Stack empty”; else {cout<,stack[top]<<”<--“ <=0;i–)
cout<,stack[i]<,endl; } } void main() {int stack[size],item, top=-1, res; char ch=’y’; clrscr(); while(ch==’y’ || ch==’Y’) {cout<<”\n Enter the ITEM for insertion:”; cin>>item;
PUSH(stack,item,top);
cout<<”\n The stack is :\n”; DISPLAY(stack,top); cout<<”\n Want to insert more elements? (y/n)”; cin>>ch;
}
cout<<”\n Deletion of elements:\n”; ch=’y’; while(ch==’y’ || ch==’Y’) {res=POP(stack,top); cout<<”\n Deleted element is:”<< res; cout<<”\n The stack is :\n”; DISPLAY(stack,top); cout<<”\n Want to delete more elements? (y/n)”; cin>>ch;
}
getch();
}
Linked List Implementation of Stack:
A linked list is a dynamic data structure. So the space requirement is not predetermined.The linked-stack is created after getting a node for the ITEM to be inserted. TOP points to the newly inserted node. The dynamic allocation of memory is done by using new operator as shown below:
struct node
{ int info;
Node *next;
}*newptr;
Now, the following statement creates a node dynamically
newptr =new node;
if(newptr==NULL)
cout<<”stack Underflow”; Pushing can only occur at the top, TOP gets modified every time. Popping also requires modification of TOP. Top is made to point to the next node in the sequence. Deallocation of memory is done by the operate delete. delete ptr; Program to show basic operations on a stack (Linked List implementation) #include
#include
#include
#include
#include
struct node
{ int data;
node *link;
};
node *push(node *top, int val); // Add stack
node *pop(node *top, int &val); // Delete stack
void show_Stack(node *top); // Show stack
void main()
{node *top;
int val;
int choice;
char opt = ‘Y’; // To continue the do loop in case
top = NULL; // Initialization of Stack
clrscr();
do
{cout << "\n\t\t Main Menu"; cout << "\n\t1. Addition of Stack"; cout << "\n\t2. Deletion from Stack"; cout << "\n\t3. Traverse of Stack"; cout << "\n\t4. Exit from Menu"; cout << "\n\nEnter Your choice from above "; cin >> choice;
switch (choice)
{
case 1:do
{cout << "Enter the value to be added in the stack "; cin >> val;
top = push(top, val);
cout << "\nDo you want to add more element ? “;
cin >> opt;
} while (toupper(opt) == ‘Y’);
break;
case 2:opt = ‘Y’; // Initialize for the second loop
do
{top = pop(top,val);
if (val != -1)
cout << "Value deleted from Stack is " << val; cout << "\nDo you want to delete more element ? “;
cin >> opt;
} while (toupper(opt) == ‘Y’);
break;
case 3:show_Stack(top);
break;
case 4:exit(0);
}
}
while (choice != 4);
}
node *push(node *top, int val)
{ node *temp;
temp = new node;
temp->data = val;
temp->link = NULL;
if(top ==NULL)
top = temp;
else
{ temp->link = top;
top = temp;
}
return(top);
}
node *pop(node *top,int &val)
{ node *temp;
clrscr();
if (top == NULL )
{ cout<<"Stack Empty "; val = -1; } else { temp = top; top = top->link;
val = temp->data;
temp->link = NULL;
delete temp;
}
return (top);
}
void show_Stack(node *top)
{ node *temp;
temp = top;
clrscr();
cout<<"The values are \n"; while (temp != NULL) { cout <<"\n"<< temp->data;
temp = temp->link;
}
}
Converting INFIX to POSTFIX notation:
An arithmetic expression is an expression having variables, constants and operators. The hierarchy of the operators is as follows:
Arithmetic Operators Precedence
Exponents( ^ or ↑) Highest
Multiplication(*) and Division (/) Middle
Addition (+) and Subtraction (-) Lowest
Logical Operators Precedence
NOT(!) Highest
AND (&&) Middle
OR (||) Lowest
Operators at the same level are executed in a left to right order and can be enclosed with parenthesis to override the above rules.
The usual way of writing expressions is by writing operator between two operands. This notation is called infix notation. In postfix notation operator is placed after the two operands.
Stack can be used to convert an infix expression into postfix notation.
Steps:
1. Scan the given infix expression from left to right and repeat the step 2 to 5 for each element until the stack is empty.
2. If an operand is encountered, place it onto the output (pop).
3. If a left parenthesis is encountered, push it into stack.
4. If an operator is encountered, then:
(i) If a symbol of lower or same priority is encountered, pop entries from the stack until an entry of lower priority is reached.
(ii) After popping, push the operator onto stack
5. If a right parenthesis is encountered, pop the stack elements until a corresponding left parenthesis is reached.
6. End
Example:Convert ((A+B)*C/D+E^F)/G into postfix notation from showing stack status after every step.
Answer:
Step Input Action Stack Status Output
1 ( Push (
2 ( Push ((
3 A Print (( A
4 + Push ((+ A
5 B Print ((+ AB
6 ) Pop & Print ( AB+
7 * Push (* AB+
8 C Print (* AB+C
9 / Pop & print ( AB+C*
Push (/ AB+C*
10 D Print (/ AB+C*D
11 + Pop & Print ( AB+C*D/
12 E Print ( AB+C*D/E
13 ^ Push (^ AB+C*D/E
14 F Print (^ AB+C*D/EF
15 ) Pop & Print Empty AB+C*D/EF^
16 / Push / AB+C*D/EF^
17 G Print / AB+C*D/EF^G
18 Pop Empty AB+C*D/EF^G/
Remark: * and / has same priority so in step 9, so * is popped and after that / is pushed.
Example:Convert the expression (TRUE && FALSE) || !(FALSE||TRUE) into postfix notation from showing stack status after every step.
Answer:
Step Input Action Stack Status Output
1 ( Push (
2 TRUE Print ( TRUE
3 && Push (&& TRUE
4 FALSE Print (&& TRUE FALSE
5 ) Pop Empty TRUE FALSE &&
6 || Push || TRUE FALSE &&
7 ! Push || ! TRUE FALSE &&
8 ( Push || ! ( TRUE FALSE &&
9 FALSE Print || ! ( TRUE FALSE && FALSE
10 || Push || ! ( || TRUE FALSE && FALSE
11 TRUE Print || ! ( || TRUE FALSE && FALSE TRUE
12 ) Pop || ! TRUE FALSE && FALSE TRUE ||
13 Pop || TRUE FALSE && FALSE TRUE || !
14 Pop Empty TRUE FALSE && FALSE TRUE || ! ||
Remark: Here TRUE , FALSE are operands and !, ||, && are operators.
Evaluation of a POSTFIX expression:
Steps:
1. Read the expression from left to right, if an operand is encountered, push it into stack.
2. If a binary operator is encountered, pop two operands from stack and if a unary operator is encountered, pop one operand and then evaluate it.
3. Push back the result onto stack.
4. Repeat it till the end of the expression.
Let us see how the above algorithm will be imlemented using an example.
Postfix String : 123*+4-
Initially the Stack is empty. Now, the first three characters scanned are 1,2 and 3, which are operands. Thus they will be pushed into the stack in that order.

Stack
Expression
Next character scanned is “*”, which is an operator. Thus, we pop the top two elements from the stack and perform the “*” operation with the two operands. The second operand will be the first element that is popped.

Stack
Expression
The value of the expression(2*3) that has been evaluated(6) is pushed into the stack.

Stack
Expression
Next character scanned is “+”, which is an operator. Thus, we pop the top two elements from the stack and perform the “+” operation with the two operands. The second operand will be the first element that is popped.

Stack
Expression
The value of the expression(1+6) that has been evaluated(7) is pushed into the stack.

Stack
Expression
Next character scanned is “4”, which is added to the stack.

Stack
Expression
Next character scanned is “-“, which is an operator. Thus, we pop the top two elements from the stack and perform the “-” operation with the two operands. The second operand will be the first element that is popped.

Stack
Expression
The value of the expression(7-4) that has been evaluated(3) is pushed into the stack.

Stack
Expression
Now, since all the characters are scanned, the remaining element in the stack (there will be only one element in the stack) will be returned.
End result :
Postfix String : 123*+4-
Result : 3
Example:Evaluate the following postfix notation of expression (show status of stack after execution of each operation).
5, 11, -, 6, 8, +, 12, *, /
Answer:
Step Input Action Stack Status
1 5 Push (5) 5
2 11 Push (11) 5, 11
3 – Pop (11)
Pop (5)
Push (5-11) -6
4 6 Push (6) -6, 6
5 8 Push (8) -6, 6, 8
6 + Pop (8) -6, 6
Pop (6) -6
Push (6+8) -6, 14
7 12 Push (12) -6, 14, 12
8 * Pop (12) -6, 14
Pop (14) -6
Push (14 * 12) -6, 168
9 / Pop (168) -6
Pop (-6)
Push (-6/ 168) -1/28

Example:Evaluate the following postfix notation of expression (show status of stack after execution of each operation).
TURE, FALSE, TRUE, FALSE, NOT, OR, TRUE, OR, OR, AND
Answer:
Step Input Action Stack Status
1 TRUE Push TRUE
2 FALSE Push TRUE, FALSE
3 TRUE Push TRUE, FALSE, TRUE
4 FALSE Push TRUE, FALSE, TRUE, FALSE
5 NOT Pop(False) TRUE, FALSE, TRUE
Push (Not FALSE=TRUE) TRUE, FALSE, TRUE, TRUE
6 OR Pop(TRUE) TRUE, FALSE, TRUE
Pop (TRUE) TRUE, FALSE
push (TRUE or TRUE=TRUE) TRUE, FALSE, TRUE
7 TRUE push TRUE, FALSE, TRUE, TRUE
8 OR pop (TRUE) TRUE, FALSE, TRUE
pop(TRUE) TRUE, FALSE,
push (TRUE or TRUE=TRUE) TRUE, FALSE, TRUE
9 OR pop (TRUE) TRUE, FALSE,
pop(FALSE) TRUE
push (TRUE or FALSE=TRUE) TRUE, TRUE
10 AND pop (TRUE) TRUE,
pop(TRUE)
push (TRUE and TRUE=TRUE) TRUE

POINTS TO REMEMBER
 Introduction to Stack
 Array Implementation of Stack
 Linked list implementation of Stack
 Converting INFIX to POSTFIX notation
 Evaluation of a POSTFIX expression

SOLVED PROBLEMS
Problem 1: Write a function in C++ to delete a node containing Book.s information, from adynamically allocated Stack of Books implemented with the help of the following
structure.
struct Book
{ int BNo ;
char BName[20] ;
Book *Next ;
} ;
Solution: void Pop(Book *Top)
{ Book *Temp;
if( Top= = NULL)
cout<<”Stack Underflow..”; else { cout<<”\nThe Book number of the element to delete:”<BNo;
cout<<”\nThe Book name of the element to delete:”<BName;
Temp=Top;
Top=Top->Next;
Delete Temp;
}
}
Problem2: Write a function in C++ to perform a PUSH operation on a dynamically allocated
stack containing real number.
struct Node
{ float Number ;
Node *Link ;
} ;
class STACK
{ Node *Top ;
public :
STACK( ) {Top = NULL ;}
void PUSH( ) ;
void POP( ) ;
~STACK( ) ;
} ;
Solution: void STACK::PUSH( )
{ Node *Temp;
Temp=new Node;
if(Temp= =NULL)
{
cout<<”\nNo memory to create the node..”; exit(1); } cout<<”\nEnter the Number to be inserted: “; cin>>Temp->Number;
Temp->Link=Top;
Top=Temp;
}
Problem3: class stack
{ int data[10] :
int top ;
public :
stack( ) { top = – 1; }
void push( ) ; //to push an element into the stack
void pop( ) ; //to pop an element from the stack
} ;
Complete the class with all function definitions. Use another stack to transfer data
temporarily.
Solution: void stack::push( )
{ if(top>=9)
cout<<”Stack Overflow..”; else { top++; cout<<”\nEnter the element to be inserted.”; cin>>data[top];
}
}
void stack::pop( )
{ if(top= =-1)
cout<<”\nStack Underflow”; else { cout<<”\nThe element to be deleted = “<>TempX>>Temp->Y;
Temp->Link=Top;
Top=Temp;
}
}

UNSOLVED PROBLEMS
Problem 1: Write a function in C++ to insert an element into a dynamically allocated Stack where each node contains a real number as data. Assume the following definition of STACKNODE for the same.
struct STACKNODE
{ float DATA;
STACKNODE *LINK;
};
Problem 2: Give the Postfix form of the following expression showing stack status:
A*( B + (C + D) * (E * F)/ G) * H
Problem 3: Evaluate the following postfix notation of expression (Show stack status after execution of each operation):
3, 9, 4, +, *, 10, 2, /, –
Problem 4: Evaluate the following postfix notation of expression (Show status of stack after execution of each operation) :
50,40,+,18,14,-, 4,*,+
Problem 5: Evaluate the following postfix notation of expression (Show status of stack after execution of each operation) :
45, 7, +, 8, 10, -, *
Problem 6: Evaluate the following postfix notation of expression (Show status of stack after execution of each operation) :
True,False,AND,True,True,NOT,OR,AND
Problem 7: Write a function in C++ to insert an element in an array stack.
Problem 8: Evaluate the following postfix notation of expression :
15, 3, 2, +, /, 7, +, 2, *
Problem 9: Evaluate the following postfix notation of expression :
25, 8 ,3 ,- ,/, 6, *, 10, +
Problem 10: Evaluate the following postfix notation of expression (Show status of
stack after execution of each operations):
5, 20, 15, -, *,25, 2, *, +
Problem 11: Evaluate the following postfix notation of expression (Show status of
stack after execution of each operation ):
4, 10, 5, +, *, 15, 3, /, –
Problem 12: Change the following infix expression into postfix expression.
(A+B)*C+D/E-F
Problem 13: Evaluate the following postfix expression using a stack. Show the
contents of stack after execution of each operation:
20, 8, 4, /, 2, 3, +, *, –
Problem 14: Evaluate the following postfix notation of expression:
20,30,+,50,40,-,*

2.3: Queue
POINTS TO FOCUS
Introduction:
A queue is a subclass of lists in which insertion and deletion take place at specific ends i.e. REAR and FRONT respectively. It is a FIFO (First In First Out) data structure. By convention, we name the queue insert operation enqueue and the remove operation dequeue.

Addition into a queue:
procedure addq (item : items);
{add item to the queue q}
begin
if rear=n then queuefull
else begin
rear :=rear+1;
q[rear]:=item;
end;
end;{of addq}
Deletion in a queue:
procedure deleteq (var item : items);
{delete from the front of q and put into item}
begin
if front = rear then queueempty
else begin
front := front+1
item := q[front];
end;
end; {of delete}
Array Implementation of Queue:
Array is a static data structure. So the space is allocated according to the maximum number of elements present at that point.
Insertion of an element in the queue is possible through REAR end. In case the array is full and no new element can be accommodated, it is called QUEUE-FULL. This condition is called OVERFLOW.
Deletion of an element takes place from the FRONT. In case the last element is deleted, the queue becomes empty. If one tries to delete an element from an empty queue, this is called UNDERFLOW.
// Program illustrating basic operations in an array queue
#include
#include
#include
class queue
{ int data[10];
int front, rear;
public:
queue()
{ front = -1;
rear = -1;
}
void add(); // To add an element into the queue
void remove(); // To remove an element from the wueue
void Delete(int ITEM); //To delete all elements which are equal to ITEM;
};
void queue::add()
{ if (rear == front)
{ if (rear == -1)
front = rear = 0;
else
rear = (rear + 1) % 10;
cout << "Enter data : "; cin >> data[rear];
}
else
cout << "Queue full :: Overflow error!!\n"; } void queue::remove() { if (front != -1) {cout << data[front] << " deleted "; if (front == rear) front = rear - 1; else front = (front - 1) % 10; } else cout << "Queue empty ! Underflow error!!\n"; } void main() { clrscr(); queue Q; Q.add(); Q.remove(); } Linked List Implementation of Queue: A linked list is a dynamic data structure. So the space requirement is not predetermined.The linked-queue is created after getting a node for the ITEM to be inserted. REARpoints to the newly inserted node. //Program illustrating basic operations in a linked queue #include
#include
#include
#include
#include
struct node
{ char data;
node *link;
};
node *add_Q(node *rear, char val); // Add queue
node *del_Q(node *front, char &val);// Delete queue
void show_Q(node *front); // Show queue
void main()
{node *front, *rear;
char val;
int choice;
char opt = ‘Y’; // To continue the do loop in case
front = rear = NULL; // Initialization of Queue
clrscr();
do
{cout << "\n\t\t Main Menu"; cout << "\n\t1. Addition of Queue"; cout << "\n\t2. Deletion from Queue"; cout << "\n\t3. Traverse of Queue"; cout << "\n\t4. Exit from Menu"; cout << "\n\nEnter Your choice from above "; cin >> choice;
switch (choice)
{ case 1:do
{cout << "Enter the value to be added in the queue "; cin >> val;
rear = add_Q(rear, val);
if (front == NULL)
front = rear;
cout << "\nDo you want to add more element ? “;
cin >> opt;
} while (toupper(opt) == ‘Y’);
break;
case 2:opt = ‘Y’; // Initialize for the second loop
do
{front = del_Q(front, val);
if (front == NULL)
rear = front;
if (val != -1)
cout << "Value deleted from Queue is " << val; cout << "\nDo you want to delete more element ? “;
cin >> opt;
} while (toupper(opt) == ‘Y’);
break;
case 3:show_Q(front);
break;
case 4:exit(0);
}
}while (choice != 4);
}
node *add_Q(node *rear, char val)
{ node *temp;
temp = new node;
temp->data = val;
temp->link = NULL;
rear->link = temp;
rear = temp;
return (rear);
}
node *del_Q(node *front, char &val)
{ node *temp;
clrscr();
if (front == NULL)
{ cout << "Queue Empty "; val = -1; } else { temp = front; front = front->link;
val = temp->data;
temp->link = NULL;
delete temp;
}
return (front);
}
void show_Q(node *front)
{ node *temp;
temp = front;
clrscr();
cout << "The Queue values are"; while (temp != NULL) { cout <<"\n"<< temp->data;
temp = temp->link;
}
}
Circular Queue:
When queue is implementated using array a situation aries when overflow occurs whenever though the free cells are available. To overcome this drawback, we have circular queue. In a circular queue the first element of the array is assumed to be immediately next to its last element, i.e. if the last position of the array is having an element, a new element can be inserted next to it, at the first position of the array (if empty).

// Program illustrating basic operation of circular queue
#include
#include
#include
#include
#include
#include
#define MAX 100
char queue[MAX][MAX];
int front, rear;
void add_Q(char queue[MAX][MAX], int front, char val[MAX], int &rear);
void del_Q(char queue[MAX][MAX], int &front, int rear);
void show_Q(char queue[MAX][MAX], int front, int rear);
void main()
{int choice;
char data[MAX];
char opt = ‘Y’; // To continue the do loop in case
rear = -1; // Initialization of Queue
front = -1;
clrscr();
do
{
cout << "\n\t\t Main Menu"; cout << "\n\t1. Addition of Queue"; cout << "\n\t2. Deletion from Queue"; cout << "\n\t3. Traverse of Queue"; cout << "\n\t4. Exit from Menu"; cout << "\n\nEnter Your choice from above "; cin >> choice;
switch (choice)
{
case 1:do
{ cout << "Enter the character string : "; gets(data); add_Q(queue, front, data, rear); cout << "Do you want to add more element ? “;
cin >> opt;
} while (toupper(opt) == ‘Y’);
break;
case 2:opt = ‘Y’;
do
{ del_Q(queue, front, rear);
cout << "\nDo you want to delete more element ? “;
cin >> opt;
} while (toupper(opt) == ‘Y’);
break;
case 3:show_Q(queue, front, rear);
break;
case 4:exit(0);
}
}while (choice != 4);
void add_Q(char queue[MAX][MAX], int front, char val[MAX], int &rear)
{if ((rear + 1) % MAX == front)
{ cout << "Queue Full "; } else { rear = (rear + 1) % MAX; strcpy(queue[rear], val); } } void del_Q(char queue[MAX][MAX], int &front, int rear) {char value[MAX]; if (front == rear) { cout << "Queue Empty "; } else { front = (front + 1) % MAX; strcpy(value, queue[front]); cout << "The value deleted from the queue is "<Name);
ptr->Link=NULL;
if(rear= = NULL)
front=rear=ptr;
else
{
rear->Link=ptr;
rear=ptr;
}
}
Problem2: Write a function in C++ to Delete an element into a dynamically allocated Queue where each node contains a real number as data. Assume the following definition of MYNODE for the same:
struct MYNODE
{
float NUM;
MYNODE * Link;
};
Solution: class Queue
{
MYNODE *front,*rear;
public:
Queue( )
{ front=rear=NULL; }
void Insert( );
void Delete( );
void Display( );
};
void Queue::Delete( )
{
MYNODE *temp;
if(front= = NULL)
cout<<”Queue Underflow”; else { cout<<”\nThe content of the element to delete:”<NUM;
temp=front;
front=front->Link;
delete temp;
}
}
Problem3: Write a function in C++ to delete a node containing customer.s information, from
a dynamically allocated Queue of Customers implemented with the help of the
following structure:
struct Customer
{ int CNo ;
char CName[20] ;
Customer *Link ;
} ;
Solution: class Queue
{ Customer *front,*rear;
public:
Queue( )
{ front=rear=NULL; }
void Insert( );
void Delete( );
void Display( );
};
void Queue::Delete( )
{ Customer *Temp;
if(front= =NULL)
cout<<.Queue Underflow. No element to delete.; else { cout<<”\n The customer number for the element todelete”<CNo;
cout<<.\n The customer name for the element todelete”<CName;
Temp=front;
front = front->Link;
delete Temp;
}
}
Problem4: class queue
{ int data[10] ;
int front, rear ;
public :
queue( ) { front = – 1 ; rear = – 1 ; }
void add( ) ; //to add an element into the queue
void remove( ) ; //to remove an element from the queue
} ;
Complete the class with all function definitions for a circular array Queue. Use
another queue to transfer data temporarily.
Solution: void queue::add( )
{ if((front= = 0 && rear = = 9) | | (front= =rear+1)
cout<<.\nQueue Overflow.; else if (rear= = -1) { front=rear=0; cout<<”\nEnter the element to be inserted”; cin>>data[rear];
}
else if(rear= =9)
{ rear=0;
cout<<”\nEnter the element to be inserted”; cin>>data[rear];
}
else
{ rear++;
cout<<”\nEnter the element to be inserted”; cin>>data[rear];
}
}
void queue::remove( )
{ if(front= = -1)
cout<<.\nQueue Underflow..; else { cout<<”\nThe element to be deleted”<Name);
ptr->Link=NULL;
if(rear= = NULL)
front=rear=ptr;
else
{
rear->Link=ptr;
rear=ptr;
}
}
Problem6: Write a function in C++ to perform a DELETE operation in a dynamicallyallocated queue considering the following description :
struct Node
{ float U, V ;
Node *Link ;
} ;
class QUEUE
{
Node *Rear, *Front ;
public :
QUEUE( ) {Rear = NULL ; Front = NULL ;}
void INSERT( ) ;
void DELETE( ) ;
~ QUEUE( ) ;
} ;
Solution: void Queue::DELETE( )
{
NODE *temp;
if(front= = NULL)
cout<<”\nQueue Underflow”; else { cout<<”\nThe value of U of the element to delete:”<U;
cout<<”\nThe value of V of the element to delete:”<V;
temp=Front;
Front=Front->Link;
delete temp;
}
}
Problem7: Define member functions queins( ) to insert nodes and quedel ( ) to delete nodes
of the linked list implemented class queue, where each node has the following
structure:
struct node
{ char name[20] ;
int age ;
node *Link ;
} ;
class queue
{ node *rear, *front ;
public :
queue( ) { rear = NULL; front = NULL} ;
void queins( ) ;
void quedel( ) ;
} ;
Solution: void queue::queins( )
{ node *ptr;
ptr=new node;
if(ptr= = NULL)
{
cout<<”\nNo memory to create a new node..”; exit(1); } cout<<”\nEnter the name..”; gets(ptr->name);
cout<<”\nEnter the age..”; cin>>ptr->age;
ptr->Link=NULL;
if(rear= = NULL)
front=rear=ptr;
else
{
rear->Link=ptr;
rear=ptr;
}
}
void queue::quedel( )
{ node *temp;
if(front= = NULL)
cout<<”Queue Underflow”; else { cout<<”\nThe name of the element to delete: “<name;
cout<<”\nThe age of the element to delete: “<age;
temp=front;
front=front->Link;
delete temp;
}
}

UNSOLVED PROBLEMS

Problem 1: Write a insert function in c++ in a dynamically allocated Queue containing Phonno and names of customer.
Problem 2: Write a function in C++ to delete an element from a dynamically allocated circular Queue where each node contains a real number as data.
Problem 3: Write a function to perform a Push operation in a dynamically allocated stack considering the following description struct node { int data; struct node * next; };
Problem 4: Write a function in C++ to perform Insert operation in a dynamically allocated Queue containing names of students.

3.1: Database Concepts
POINTS TO FOCUS
Database:
Database is a collection of different kinds of data which are connected with some relation.In different way, it is a computer based record keeping system. The collection of data referred is to as a database.
Purpose of Database:
Years ago, for keeping record, a typical file-processing system is used. A number of different application programs are written to extract records from and add records to the appropriate files. But this scheme has a number of major limitations and disadvantages, such as data redundancy, data inconsistency, unsharable data, unstandardized data, insecure data, incorrect data, etc.
A database management system is answer to all these problems as it provides a centralized control of the data.
1. Databases reduce the data redundancy to a large extent
2. Databases can control data inconsistency to a large extent
3. Databases facilitate sharing of data
4. Databases enforce standards
5. Databases can ensure data security
6. Integrity can be maintained through databases
Data : It is row facts, figures, characters, etc with which we have to start.
Information :The processed data or meaningful data is known as information.
Database : An organized collection of relational data is called as database.
DBMS : It is a Database Management System. It is a system to be used for create database, store the data, secure it and fetch data whenever required. MS Access, Oracle is the example of DBMS.
Database Abstraction:
A major purpose of a database system is to provide the users only that much information that is required by them. This means that the system does not disclose all the details of data, rather it hides certain details of how the data is stored and maintained. A good database system ensures easy, smooth and efficient data structures in such a way so that every type of database user : end user, application system analyst, and physical storage system analyst, is able to access its desired information efficiently.
Various Levels of Database Implementation:
1. Internal Level (Physical Level): This level describes how the data are actually stored on the storage medium. At this level, complex low-level data structures are described in details. Eg. RollNo is in Byte(4), offset = 34.
2. Conceptual Level(Logical Level): It describes what data are actually stored in the database. It also describes the relationships existing among data. Eg. ItemCode is in Numeric(5).
3. External Level (View Level): This is the level closest to the users. It is concerned with the way in which the data are viewed by individual users. Most of the users of the database are not concerned with all the information contained in the database. Eg. View 1 contains RollNo, Name, DOB.
Data Independence:
The ability to modify a scheme definition in one level without affecting a scheme definition in the next higher level is called Data Independence.
i. Physical Data Independence: It refers to the ability to modify the scheme followed at the physical level without affecting the scheme followed at the conceptual level.
ii. Logical Data Independence: It refers to the ability to modify the conceptual scheme without causing any changes in the schemes followed at view levels.
Data Models :
The external level and conceptual level user certain data structures to help utilize the database efficiently. There are three data models that are used for database management system are :
1. Relational Data Model 2. Hierarchical Data Model 3. Network Data Model
The Relational Model:
The relational model was propounded by E.F. Codd of the IBM and has since been acknowledged as a very important concept in DBMS. The relational model has established itself as the primary data model for commercial data processing applications.
Relation: A relation is a table, i.e. data arranged in rows and columns.
Domain: It is a pool of values from which the actual values appearing in a given column are drawn.

Item# Item_Name Fund
101 Computer VVN
102 Chair SF
103 Table SF

Item_Master
Purchase_Master
Item# Pur_Date Supplier Quantity
101 25/04/2007 Super Mart Computers 20
101 15/05/2008 Supreme Computers 25
102 21/03/2007 Sharma Furnitures 50
102 11/12/2007 Shiv Furnitures 24
103 12/02/2008 Sharma Furnitures 30

Eg. The values appearing in the ItemCode# column of both the Item_Master table and the Pur_Master are drawn from the underlined domain of all valid Item Codes.
A domain is said to be atomic if elements of the domain are considered to be indivisible units.
Tuple: The rows of tables are generally referred to as Tuples.
Attributes: The columns of tables are generally referred to as attributes.
Degree: The number of attributes in a relation determine the degree of a relation. A relation having 5 attributes is said to be a relation of degree 5.
Cardinality: The number of tuples in relation is called the Cardinality of the relation. Eg. Cardinality of Purchase_Master relation is 5.
Views:
A view is a kind of table whose contents are taken from other tables depending upon a conditions. Views do not contain data of their own. The contents of a view are determined by carrying out the execution of the given query.
A view is a virtual table that does not really exists in its own right but is instead derived from one or more underlying base table(s).
Keys:
It is important to be able to specify how rows in a relation are distinguished conceptually, rows are distinct from one another, but from a database perspective the difference among them must be expressed in terms of their attributes. Keys come here for a rescue.
Primary Key: It is a set of one or more attributes that can uniquely identify tuples within the relation. Eg. Item# is the primary key for Item_Master.
Candidate Key: All attributes combinations inside a relation that can serve as primary key are Candiadate keys as they are candidates for the Primary Key position.
Alternate Key: A candidate key that is not the primary key is called an alternate key.
Foreign Key: A non-key attribute, whose values are derived from the primary key of some other table, is known as Foreign Key in its current table. Here Item# of Purchase_Master is foreign key, because it is derived from Item_Master.
Referential Integrity: It is a system of rules that a DBMS uses to ensure that relationships between records in related tables are valid, and that users don’t accidentally delete or change related data.
The Relational Algebra:
It is set of operations that can be used to manipulate relations. Each operation operates on one or more than one relation and produces a new relation.
(i) Union : If the degree of two relations is same and their corresponding attributes are defined on the same domain then the relations are called union compatible. The operator for union is ‘’;
Ex : C = A  B
(ii) Intersection: If two relations A and B are union compatible then they can also participate in an intersection operation. Its result is the common tuples. The operator for intersection is ‘’;
Ex : C = A  B
(iii) Difference: The operator is ‘-‘;
Ex : C = A – B
The tuples of C are belonging to A which do not belong to B.
(iv) Cartesian Product: It returns a concatenation of each tuple of A with each tuple of B.
Ex : C = A X B
(v) Select:Whenever user desires to search or select tuples of a relation depending upon a condition being true, the operation is known as a select operation. The operator is ‘’.
Ex : marks > 95 (Students)
(vi) Projection: A projection operation on a relation produces a vertical subset of the relation in the sense that it returns the relation minus certain columns.
Ex : name, roll (Students)
(vii) Natural Join ( |X| ) :
If two relations A and B have at least one common attribute then they can participate in a Join operation. The resultant relation contains the attributes of both A and B.

POINTS TO REMEMBER

 A database consists of a number of tables. Each table comprises of rows(records) and columns(attributes). Each record contains values for the corresponding attributes. The values of the attributes for a record are interrelated. For example, different cars have different values for the same specifications (length, color, engine capacity, etc.).
 In the database oriented approach, we store the common data in one table and access it from the required tables. Thus the redundancy of data decreases.
 The database oriented approach supports multiple views of the same data. For example, a clerk may only be able to see his details, whereas the manager can view the details of all the clerks working under him.
 Multiple views of the same database may exist for different users. This is defined in the view level of abstraction.
 The logical level of abstraction defines the type of data that is stored in the database and the relationship between them.
 The design of the database is known as the database schema.
 The instance of the database is the data contained by it at that particular moment.
 The Database Administrator has the total control of the database and is responsible for the setting up and maintaining the database.
 A Data Model is the methodology used by a particular DBMS to organize and access the data
 Hierarchical, Network and Relational Model are the three popular data models. However, the relational model is more widely used.
Hierarchical Model:
 The hierarchical model was developed by IBM in 1968.
 The data is organize in a tree structure where the nodes represent the records and the branches of the tree represent the fields.
 Since the data is organized in a tree structure, the parent node has the links to its child nodes.
 If we want to search a record, we have to traverse the tree from the root through all its parent nodes to reach the specific record. Thus, searching for a record is very time consuming.
 The hashing function is used to locate the root.
 SYSTEM2000 is an example of hierarchical database
Network Model:
 Record relationship in the network model is implemented by using pointers.
 Record relationship implementation is very complex since pointers are used. It supports many-to-many relationships and simplified searching of records since a record has many access paths.
 DBTG Codasyl was the first network database.
Relational Model:
 The Relational Model, organizes data in the form of independent tables (consisting of rows and columns) that are related to each other.
 A table consists of a number of rows (records/tuples) and columns (attributes). Each record contains values for the attributes.
 The degree of the table denotes the number of columns.
 A domain in the relational model is said to be atomic is it consists of indivisible units. For example, name is not atomic since it can be divided into first name and last name.
 E. F. Codd laid down 12 rules (known as Codd’s 12 rules) that outline the minimum functionality of a RDBMS. A RDBMS must comply with at least 6 of the rules.
 A Super Key is a of attributes that collectively identify a entity in a entity set. For example, the bank account number is a super key in the bank accounts table.
 A Candidate Key (also known as Primary Key) is the smallest subset of the super key for which there does not exist a proper subset that is a super key.
 Out of the multiple candidate keys, only one is selected to be the primary key and the remaining are alternate keys.
 A foreign key is the primary key of a table that is placed into a related table to represent one-to-many relationship among these tables.

SOLVED PROBLEMS
Problem 1: Write the purpose of the Database?
Solution: Purpose of the database are as follows
Databases reduce the data redundancy to a large extent: Data redundancy means duplication of data. Non-database systems maintain separate copy of data for each application.
Databases can control data inconsistency to a large extent:This is really a corollary of the previous point. When the redundancy is not controlled, there may be occasions on which the two entries about the same data do not agree (that is, when one of them stores the updated information and the does not). At such times, database is said to be inconsistent. Obviously, an inconsistent database will provide incorrect or conflicting information.
Databases facilitate sharing of data: Sharing of data means that individual pieces of data in the database may be shared among several different users, in the sense that each of those users may have access to the piece of data and each of them may use it for different purposes.
Databases enforce standards: The database management systems can ensure that all the data (that is stored centrally) follow the applicable standards. There may be certain standards laid by the company or organization using the database. Or there may be certain industry standards that must be satisfied by the data. Similarly, there may be national or international standards. Standardizing stored data formats is particularly desirable as an aid to data interchange or migration between systems.
Databases can ensure data security: The information stored inside a database is sometimes of great value to a corporation. Therefore, it must be kept secure and private.
Problem2: Differentiate between Candidate Key and Primary Key in context of RDMBS.
Solution: Candidate Key- It is the one which that is capable of becoming primary key i.e. a field or attribute that has unique value for each row in the relation.
Primary Key- It is a designated attribute or a group of attributes whose value is uniquely identify the tuples in the relation.
Problem3: Differentiate between Candidate Key and Alternate Key in context of RDMBS.
Solution: Candidate key is the one that is capable of becoming primary key.
A candidate key that is not a primary key is called an ALTERNATE KEY.

UNSOLVED PROBLEMS

Problem 1: What is the main function of DBA.
Problem 2: What is foreign Key? What is its purpose.
Problem 3: Define the terms Tuple and Attribute.
Problem 4: What do you understand by the terms Cardinality and Degree of the table?

3.2: Structure Query Language
POINTS TO FOCUS
Introduction:
SQL is the set of commands that is recognized by nearly all RDBMS. It is a language that enables us to create and operate on relational databases, which are sets of related information stored in tables.
Processing Capabilities of SQL:
1. Data Definition Language : The SQL DDL provides commands for defining relation schemas, deleting relations, creating indexes, and modifying relation schemas.
2. Interactive Data Manipulation Language : The SQL DML includes a query language based on both the relational algebra and the tuple relational calculus. It includes also commands to insert, delete and modify tuples in the database.
3. Emedded Data Manipulation Language : The embedded form of SQL ids designed for use within general-purpose programming languages such as PL/1, Cobol, Fortran, etc.
4. View Definition : The SQL DDL also includes commands for defining views.
5. Authorization : The SQL DDL includes commands for specifying access rights to relations and views.
6. Integrity : The SQL provides forms of integrity checking. Future products and standards of SQL are likely to include enhanced features for integrity checking.
7. Transaction Control : SQL includes commands for specifying the beginning and ending of transactions along with commands to have a control over transaction processing.
Data Definition Language:
A database scheme is specified by a set of definitions which are expressed by a special language called a data definition language (DDL). The result of compilation of DDL statements is a set of tables which are stored in a special file called data dictionary or directory.
A Data Dictionary is a file that contains “Metadata” i.e. “Data about Data”.
Classification of SQL Statements:
1. Data Definition Language Commands
2. Data Manipulation Language Commands
3. Transaction Control Language Commands
4. Session Control Commands
5. System Control Commands
DDL Commands:
It allows us to perform tasked related to data definition. Through these commands user can perform tasks like :
i. Create, alter and drop schema objects :
CREATE TABLE, ALTER TABLE, DROP TABLE, CREATE INDEX, ALTER INDEX, DROP INDEX, RENAME, TRUNCATE, etc.
ii. Grant and revoke privileges and roles :
These commands are also known as Data Control
iii. Analyse, audit or add command :
ANALYSE, AUDIT, NOAUDIT, COMMENT
DML Commands:
It is a language that enables users to access or manipulate data as organized by the appropriate data model.
The DMLs are basically of two types :
1. Procedural DMLs require a user to specify what data is needed and how to get it.
2. Non-procedural DMLs require a user to specify what data is needed without specifying how to get it.
INSERT INTO, DELETE, SELECT, LOCK TABLE, etc.
TCL Commands :
A transaction is successfully completed if and only if all its constraints steps are successfully completed. To manage and control the transactions, the transaction control commands are used.
COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION
Data Types :
Data Types are means to identify the types of data and associated operations.
There are various data types in Oracle :
1. Varchar2(size) : Variable length character string having maximum length size bytes.
2. Number(p, s) : Number having precision p and scale s.
3. Long : Character data of variable length up to 2 gigabytes.
4. Date : Valid date range from January 1, 4712 BC to December 31, 4712 AD.
5. Raw(size) : Raw binary data of length size bytes.
6. Long Raw : Raw binary data of variable length up to 2 gigabytes.
7. Rowid : Hexadecimal string representing the unique address of a row in its table.
8. char(size) : Fixed length character data of length size bytes.
SQL Command With Syntax
Create Table : To create a table.
Syntax :
CREATE TABLE

( [(size)] [,[(size)]….);
Eg.
Create table student
(rollno number(2),
name varchar2(20),
dob date);
Constraints :
Constraints are the means by which user can prevent invalid data entry into the table.
i. Not Null constraint : It ensures that the column cannot contain a NULL value.
Create Table Student
(RollNo number(2) Not Null,
Name varchar2(20) Not Null,
Dob date,
City varchar2(20) );
ii. Unique constraint : A candidate key is a combination of one or more columns, the value of which uniquely identifies each row of a table.
Create table student
(RollNo number(2) Unique,
Name varchar2(20) Not null,
Dob date,
City varchar2(20) );
iii. 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.
Create table student
(RollNo number(2) Primary Key,
Name varchar2(20) Not null,
Dob date,
City varchar2(20) );
iv. 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) references Student (Rollno),
Name varchar2(20) Not null,
Amount number(4),
Fee_Date date);
v. 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 certain conditions.
Create table Employee
(EmpNo number(4) Primary Key,
Name varchar2(20) Not null,
Salary number(6,2) check (salary > 0),
DeptNo number(3)
);
Create View :
A view is defined as a logical table based on a database table or another view.
Syntax :
Create View
As Select from

[Where ];
Eg.
Create View Stud_Jaipur As Select * from StudentWhere City = ‘Jaipur’;
Drop Table :
It is used to delete a table.
Syntax : Drop Table

;
Eg. Drop Table student;
Drop View :
It is used to delete a view.
Syntax : Drop View ;
Eg. Drop view stud_Jaipur;
Alter Table :To change or modify the definition of table.
(i) To add column :
Alter table Student
Add Class number(2);
(ii) To modify a column definition :
Alter table Student
Modify ( rollno number(3));
(iii) To drop a column :
Alter table student
Drop column city;
Update — Set :
It is used to modify the data of a column in a table.
Syntax :
Update

Set = [, = , ….]
[where ];
Eg.
Update student
Set name = ‘Rahul Sharma’
Where rollno = 5;
Insert into :
To insert data into the table.
Syntax :
Insert into

[]
Values ();
1. Omitting column list in Insert Clause :
Insert into Students
Values(1, ‘Amit Sharma’, ’12-Jun-1990’, ‘Jaipur’);
2. Listing columns in the Insert Clause :
Insert into Students (rollno, name)
Values (23, ‘Abhishek Mehta’);
Delete:
To delete values from the table.
1. Delete from Students;
It deletes all the records from the table students.
2. Delete from students where city = ‘Ajmer’;
It deletes all the records from the table students where city is Ajmer.
Select :
To fetch data from the table or a group of tables.
Syntax :
SELECT [distinct] [, ] …
FROM
[WHERE ];
Examples :
(i) select * from students;
– It lists all data from the table students.
(ii) select rollno, name from students;
– It displays only rollno and name of the table students.
(iii) select * from students where class = 12;
– It displays data from table students for class 12 only.
(iv) select * from students where class = 12 and city = ‘Jaipur’;
– It displays data whose class is 12 and city is Jaipur.
(v) select name from students where name like ‘ABH%’;
– It displays name of students which is started with ABH.
(vi) select distinct city from students;
– It displays the distinct value of column city from the table students.
(vii) select rollno, name from students order by dob;
– It displays rollno and name from the table students in order of their dob.
(viii) select rollno, name from students order by dob desc;
– It displays rollno and name from the table students in descending order of their dob.
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.
1. SUM() :It returns the sum of values of numeric type of a column.
Eg. Select sum(salary) from employee;
2. AVG() :It returns the average of values of numeric type of a column.
Eg. Select avg(salary) from employee;
3. MIN() :It returns the minimum of the values of a column of a given relation.
Eg. Select min(salary) from employee;
4. MAX() :It returns the maximum of the values of a column of a given relation.
Eg. Select max(salary) from employee;
5. COUNT():It returns the number of rows in a relation.
Eg. Select count(*) from employee;

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 , —- [functions]
FROM
GROUP BY ;
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;

POINTS TO REMEMBER
 SQL is a query language that allows user to specify the conditions(instead of algorithm)
 Basic structure of an SQL query:
General Structure: SELECT, ALL/DISTINCT, *,AS, FROM, WHERE
Comarison: IN BETWEEN, LIKE “%_”
Grouping: GROUP BY, HAVING, COUNT(), SUM(), AVG(), MAX(), MIN()
Display Order: ORDER BY, ASC/DESC
Logical Operators: AND, OR, NOT
 DDL (Data Definition Language): Create, Alter, Drop
 DML (Data Manipualtion Language): Select, Delete, Insert, Update
 DCL (Data Control Language): Grant, Revoke
 TCL (Transcation Control Language): COMMIT, ROLLBACK, SAVEPOINT

SOLVED PROBLEMS
Problem 1: Differentiate between the terms primary key and alternate key.
Solution: All candidate keys, which are not the primary key of the table are called alternate keys.
Problem 2: Consider the following tables Consignor, Consignee and Consignment. Write SQL commands for the statements (i) to (iv) and give the outputs for SQL queries (v) to (viii).

Solution: (i) To display the names of all Senders from Mumbai
SELECT sendername from Sender where sendercity=’Mumbai’;
(ii) To display the RecIC, Sendername, SenderAddress, RecName, RecAddress for every Recipient.
Select R.RecIC, S.Sendername, S.SenderAddress, R.RecName, R.RecAddress
from Sender S, Recepient R
where S.SenderID=R.SenderID;
(iii)To display Recipient details in ascending order of RecName
SELECT * from Recipent ORDER By RecName;
(iv)To display number of Recipients from each city
SELECT COUNT( *) from Recipient Group By RecCity;
(v)SELECT DISTINCT SenderCity from Sender;
SenderCity
Mumbai
New Delhi
(vi)SELECT A.SenderName, B.RecName From Sender A, Recipient B
Where A.SenderID = B.SenderID AND B.RecCity =’Mumbai’;
A.SenderNameB.RecName
R Jain H Singh
S Jha P K Swamy
(vii)SELECT RecName, RecAddress From Recipient
Where RecCity NOT IN (‘Mumbai’, ‘Kolkata’);
RecName RecAddress
S Mahajan 116, A Vihar
S Tripathi 13, BID, Mayur Vihar
(viii) SELECT RecID, RecNameFROM Recipent
Where SenderID=’MU02’ or SenderID=’ND50’;
RecID RecName
ND08 S Mahajan
ND48 S Tripathi
Problem 3: Write a query on the customers table whose output will exclude all customers with a rating <=100, unless they are located in Shimla. Solution: SELECT * FROM customers WHERE rating >100 OR city =’Shimla’ ;
Problem 4: Write a query that selects all orders except those zeros or NULLs in the amount field.
Solution: SELECT * FROM Orders WHERE amt <>0 AND (amt IS NOT NULL) ;
Problem 5: Write a query that lists customers in descending order of rating. Output the rating field first, followed by the customer’s name and number.
Solution: SELECT rating, cust-name, cust-num FROM customers ORDER BY rating DESC ;
Problem 6: Write a command that puts the following values, in their given order, into the salesman table:
cust-name-Manisha, city-Manali, comm.- NULL, cust-num-1901.
Solution: INSERT INTO salesman (city, cust-name, comm.,cust-num)
VALUES(‘Manisha’,NULL,1901) ;

UNSOLVED PROBLEMS
Problem 1: Define the following terms : (i) Candidate Key (ii) Alternate Key
Problem 2: Differentiate between DDL and DML.
Problem 3: What is relational data model?
Problem 4: What are views? How are they useful?
Problem 5: What is the difference between Where and Having Clause ?
Problem 6: Write SQL commands for the statements (i) to (viii) and give outputs for SQL queries (ix) to (xii)

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7839 REA MANAGER 67 12-DEC-98 5000 0 10
1234 PREM CLERK 87 11-FEB-77 12000 1500 20
6754 SITA MANAGER 89 12-MAR-99 10000 1000 20
6574 GITA SALESMAN 98 11-JUN-99 9000 0 30
9876 HONEY CLERK 65 12-JUN-00 12000 800 20
8976 REEMA SALESMAN 91 10-SEP-88 6000 100 30
(i) Display names of employees whose names include either of the substring “TH” or “LL”.
(ii) Display data of all employees sorted by their department, seniority and salary.
(iii) Find all the employees who have no manager.
(iv) To display all employees who were hired during 1995.
(v) Show the average salary for all departments with more than 3 people for a job.
(vi) Find out number of employees having ‘MANAGER’ as job.
(vii) Create view DEPT20 with name and the salary of employees for dept 20.
(viii) Display department no. and number of employees in each department.
(ix) SELECT SYSDATE FROM DUAL;
(x) SELECT ENAME,SAL FROM EMPLOYEE WHERE DEPTNO=20;
(xi) SELECT COUNT(*) FROM EMP;
(xii) SELECT AVG(SAL) FROM EMP;
Problem 7: Write SQL commands for the statements (i) to (iv) and give outputs for SQL queries (v) to (viii)

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 Wasington
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 DESIGNATION
102 75000 15000 Manager
105 85000 25000 Director
144 70000 15000 Manager
210 75000 12500 Manager
255 50000 12000 Clerk
300 45000 10000 Clerk
335 40000 10000 Clerk
400 32000 7500 Salesman
451 28000 7500 Salesman
(i) To display W_ID, FIRSTNAME, ADDRESS and CITY of all employees living in NEW YORK from the table WORKERS.
(ii) To display the content of workers table in ascending order of LASTNAME.
(iii) To display the FIRSTNAME, LASTNAME and total salary of all alerks from the tables WORKERS and DESIGN, where total salary is calculated as SALARY + BENEFITS.
(iv) To display the minimum salary among Managers and Clerks from the table DESIG.
(v) SELECT FIRSTNAME, SALARY FROM WORKERS, DESIG WHERE DESIGNATION = ‘Manager’ AND WORKERS.W_ID = DESIG.W_ID
(vi) SELECT COUNT(DISTINCT DESIGNATION) FROM DESIG.
(vii) SELECT DESIGNATION, SUM(SALARY FROM DESIGNATION GROUP BY DESIGNATION HAVING COUNT(*)<3; (viii) SELECT SUM(BENEFITS) FROM WORKERS WHERE DESIGNATION = ‘Salesman’; Problem 8: Write the SQL query commands based on following table Table : Book Book_id Book name Author_name Publisher Price Type Quantity C0001 Fast Cook Lata Kapoor EPB 355 Cookery 5 F0001 The Tears William Hopkins First Publi. 650 Fiction 20 T0001 My First c++ Brain & Brooke FPB 350 Text 10 T0002 C++ Brain works A.W. Rossaine TDH 350 Text 15 F0002 Thunderbolts Anna Roberts First Publ. 750 Fiction 50 Table : issued Book_Id Quantity Issued T0001 4 C0001 5 F0001 2 Write SQL query for (a) to (f) (a) To show book name, Author name and price of books of First Pub. Publisher (b) To list the names from books of text type (c) To Display the names and price from books in ascending order of their prices. (d) To increase the price of all books of EPB publishers by 50. (e) To display the Book_Id, Book_name and quantity issued for all books which have been issued (f) To insert a new row in the table issued having the following data. ‘F0003’, 1 (g) Give the output of the following i. Select Count(*) from Books ii. Select Max(Price) from books where quantity >=15
iii. Select book_name, author_name from books where publishers=’first publ.’
iv. Select count(distinct publishers) from books where Price>=400
Problem 9: What are group Functions?
Problem 10: What do you understand by constraints?
Problem 11: Write SQL commands for (a) to ( j) and write output for (h) on the basis of Teacher relation given below.
No Name Age Department Date of Join Salary Sex
1. jigal 34 Computer 10/01/97 12000 M
2. Sharmila 31 History 24/03/98 20000 F
3. Sandeep 32 Maths 12/12/96 30000 M
4. Sangeeta 35 History 01/07/99 40000 F
5. Rakesh 42 Maths 05/09/97 25000 M
6. Shyam 50 History 27/02/97 30000 M
7. Shiv Om 44 Computer 25/02/97 21000 M
8. Shalakha 33 Maths 31/07/97 20000 F

(a) To show all information about the teacher of history department.
(b) To list the names of female teachers who are in Maths department
(c) To list names of all teachers with their date of joining in ascending order.
(d) To display students name, fee,age for male teacher only
(e) To count the number of teachers with age>23.
(f) To insert a new row in the TEACHER table with the following data:
9,”Raja”,26,”Computer”,13/05/95,2300,”M”.
(g)To show all information about the teachers in this table
(h)Add a new column named “Address”.
(i)Arrange the whole table in the alphabetical order to name
(j)Display the age of the teachers whose name starts with ‘S,.
(k)Give the output of following statement.
(i) Select COUNT(distinct department) from TEACHER.
(ii) Select MAX(Age)from Teacher where sex=”F”
(iii) Select AVG(Salary) from Teacher where Dateofjoin< ‘12/07/96’ (iv) Select SUM(Salary) from teacher where Dateofjoin< ‘12/07/96’ Problem 12: Write SQL commands for the statements (i) to (vi) on the basis of the following table EMPLOYEE: Name EmpNo DeptNo Job Sal Comm G. Hussain 2098 10 President 7000 Pallav 3099 30 Manager 9000 1400 Y.D. Sharma 8001 20 Clerk 8500 Bhawna 7901 10 President 4520 300 A. Dasgupta 5400 20 Analyst 6580 P. Arora 3400 10 Clerk 12000 Col. Singhvi 2100 30 Manager 1200 500 Amit 3100 30 Analyst 3250 A D’souza 2211 10 Clerk 6900 i. Show sum and average salary for marketing deptt. ii. Check all employees have unique names. iii. Find al employess whose deptt is same as of ‘Amit’. iv. Increase the salary of all employees by 10%, v. Find the deptt that is paying max salaries to its employees. Display the details of all the employees having salary less than 10000. Problem 13: Write the SQL commands for (a) to (d) and write the output for (e) on the basis of table Hospital : No Name Age Department Dateofadmin Charge Sex 1 Arpit 62 Surgery 21/01/06 300 M 2 Zayana 18 ENT 12/12/05 250 F 3 Kareem 22 Orthopedic 19/02/06 450 M 4 Abhilash 26 Surgery 24/11/06 300 M 5 Dhanya 24 ENT 20/10/06 350 F 6 Siju 23 Cardiology 10/10/06 800 M 7 Ankita 16 ENT 13/04/06 100 F 8 Divya 15 Cardiology 10/11/06 500 F 9 Nidhin 25 Orthopedic 12/05/06 700 M 10 Hari 28 Surgery 19/03/06 450 M (a) To show all information about the patients of cardiology department. (b) To list the name of female patients who are in ENT department. (c) To list names of all patients with their date of admission in ascending order. (d) To count the no of patients with age > 20.
(e) Give the output of the following SQL commands:
(i) Select COUNT(DISTINCT charges ) from hospital;
(ii) Select MIN(age) from hospital where Sex=’M’;
(iii) Select SUM(charges) from hospital where Sex =’F’;
(iv) Select avg(charges) from hospital where dateofadm>{12/05/06};

POINTS TO FOCUS
Introduction:
In 1938 Claude E. Shannon wrote a paper titled ‘A Symbolic Analysis of Relay Switching Circuits’. In this paper he applied Boolean algebra to solve relay logic problems. As logic problems are binary decisions and Boolean algebra effectively deals with these binary values. Thus it is called ‘Switching Algebra’.
Binary Valued Quantities:
The decision which results into either YES (TRUE) or NO(FALSE) is called a Binary Decision.
Example:- I have to go or Not? In this we have two decisions either for True or for False.
Logical Operator:
In Algebraic function e use +,-,*,/ operator but in case of Logical Function or Compound statement we use AND,OR & NOT operator.
Example: He likes Computer Science NOT IP.
Precedence of Boolean operators (from highest to lowest):
~ – NOT operation
* – AND operation
+ – OR operation
Truth Table:
The table which is used for calculation of results in true & False for all combination of Input variable.
Example:-
X Y R
1 1 1
1 0 0
0 1 0
0 0 0

1(One) represents TRUE values and 0(Zero) represents FALSE value.
If result of any logical statement or expression is always TRUE or 1, it is called Tautology and if the result is always FALSE or 0 it is called Fallacy.
Logical Operator:
There are three Basic Logical Operator:
1. NOT
2. OR
3. AND
NOT Operator:
This operator operates on single variable and operation performed by not operator is called Complementation i.e. for 0 to 1 or 1 to 0.
Truth Table:-
X R
0 1
1 0

Example: – The best Example of Not gate is Inverter which is used in our Home.

OR Operator
The OR operator gives the True result if all or anyone of the input signal is true, it is used as a logical addition and denoted by +.
0+0=0
0+1=1
1+0=1
1+1=1
Truth Table:-
X Y R

0 0 0

0 1 1
1 0 1
1 1 1
AND Operator
AND operator gives the True result if all inputs are one or true otherwise false, this is known as logical multiplication denoted by DOT (.) Operator.
0.0=0
0.1=0
1.0=0
1.1=1
Truth Table :-
X Y R
0 0 0

0 1 0
1 0 0
1 1 1
Overlapped Portion shows X.Y

Logic Gate:
A gate is simply an electronic circuit which operates on one or more signals to produce an output signal.
NOT gate (inverter)
The output Q is true when the input A is NOT true, the output is the inverse of the input:
Q = NOT A
A NOT gate can only have one input. A NOT gate is also called an inverter.
Input A Output Q
0 1
1 0

Traditional symbol Truth Table
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.
Input A Input B Output Q
0 0 0
0 1 0
1 0 0
1 1 1

Traditional symbol Truth Table
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.
Input A Input B Output Q
0 0 0
0 1 1
1 0 1
1 1 1

Traditional symbol Truth Table
Principle of Duality:
This principle tell us starting with the one relation or gate other can be drived by
1. Changing each OR sign (+) to an AND sign(.)
2. Changing each AND sign to an OR sign(.)
3. Replacing each 0 by 1 and each 1 by 0.
The derived relation using duality principle is called dual of original expression.
Example:- 0+0=0 by applying 0 to 1 & + to . it becomes 1.1=1
Basic Theorem of Boolean Algebra:
In working with logic relations in digital form, we need a set of rules for symbolic manipulation which will enable us to simplify complex expressions and solve for unknowns. Originally, Boolean algebra which was formulated by George Boole, an English mathematician (1815-1864) described propositions whose outcome would be either true or false.
In computer work it is used in addition to describe circuits whose state can be either 1 (true) or 0 (false).Using the relations defined in the AND, OR and NOT operation, a number of postulates are stated in
 P1 : X = 0 or X = 1
 P2 : 0 .0 = 0
 P3 : 1 + 1 = 1
 P4 : 0 + 0 = 0
 P5 : 1 .1 = 1
 P6 : 1 .0 = 0. 1 = 0
 P7 : 1 + 0 = 0 + 1 = 1
 T1 : Commutative Law
A + B = B + A
A. B = B. A
 T2 : Associative Law
(A + B) + C = A + (B + C)
(A. B). C = A. (B. C)
 T3 : Distributive Law
A. (B + C) = A. B + A .C
A + (B. C) = (A + B) (A + C)
 T4 : Identity Law
A + A = A
A .A = A
 T5 : Negation Law

 T6 : Redundance Law
A + A B = A
A .(A + B) = A
 T7 :
0 + A = A
1 .A = A
1 + A = 1
0. A = 0
 T8 :

 T9 :

 T10 : De Morgan’s Theorem

minterm:
Minterm si a Product of all the literals within the logic System.
Step involved in minterm expansion of Expression
1. First convert thegiven expression in sum of product form.
2. In each term is any variable is missing(e.g. in the following example Y is missing in first term and X is missing in second term), multiply that term with (missing term +complement( missing term) )factor e.g. if Y is missing multiply with Y+Y’ )
3. Expand the expression .
4. Remove all duplicate terms and we will have minterm form of an expression.
Example: Convert X+Y
X+Y=X.1+Y.1
=X.(Y+Y’)+Y(X+X’)
=XY+XY’+XY+X’Y
=XY+XY’+XY
Other procedure for expansion could be
1. Write down all the terms
2. Put X’s where letters much be inserted to convert the term to a product term
3. Use all combination of X’s in each term to generate minterms
4. Drop out duplicate terms
Shorthand Minterm notation:
Since all the letters must appear in every product, a shorthand notation has been developed that saves actually writing down the letters themselves. To form this notation, following steps are to be followed:
1. First of all, Copy original terms
2. Substitute 0’s for barred letters and 1’s for nonbarred letters
3. Express the decimal equivalent of binary word as a subscript of m.
Rule1. Find Binary equivalent of decimal subscript e.g.,for m6 subscript is 6, binary equivalent of 6 is 110.
Rule 2. For every 1’s write the variable as it is and for 0’s write variable’s complemented form i.e., for 110 t is XYZ. XYZ is the required minterm for m6.
maxterm:
A Maxterm is a sum of all the literals (with or without the bar) within the logic system. Boolean Expression composed entirely either of Minterms or Maxterms is referred to as Canonical Expression.
Canonical Form:
Canonical expression can be represented is derived from
(i) Sum-of-Products(SOP) form
(ii) Product-of-sums(POS) form
Sum of Product (SOP)
1. Various possible input values
2. The desired output values for each of the input combinations
X Y R
0 0 X’Y’
0 1 X’Y
1 0 XY’
1 1 XY

Product of Sum (POS)
When a Boolean expression is represented purely as product of Maxterms, it is said to be in Canonical Product-of-Sum from of expression.
X Y Z Maxterm
0 0 0 X+Y+Z
0 0 1 X+Y+Z’
0 1 0 X+Y’+Z
0 1 1 X+Y’+Z’
1 0 0 X’+Y+Z
1 0 1 X’+Y+Z’
1 1 0 X’+Y’+Z
1 1 1 X’+Y’+Z’

Karnaugh Maps:
Karnaugh map or K Map is a graphical display of the fundamental product in a truth table.

Example:Reduce the following Boolean expression using K-Map:
F(P,Q,R,S)=Σ(0,3,5,6,7,11,12,15)
Soln: R’S’ R’S RS RS’

P’Q’ 1
0
1 1
3
2
P’Q
4 1
5 1
7 1
6
PQ 1
12
13 1
15
14
PQ’
8
9 1
11
10

This is 1 quad, 2pairs & 2 lock
Quad(m3+m7+m15+m11) reduces to RS
Pair(m5+m7) reduces to P’QS
Pair (m7+m6) reduces to P’QR
Block m0=P’Q’R’S’
M12=PQR’S’
hence the final expressions is F=RS + P’QS + P’QR + PQR’S’ + P’Q’R’S’

Example: Reduce the following Boolean expression using K-Map:
F(A,B,C,D)=∏(0,1,3,5,6,7,10,14,15)
Soln:

0 0 0
0 0 0
0 0
0

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
Y(A,B,C,D)= (A+B+C) (A+C+D) (A+D) (B+C)

More about Gate 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 B)
A NAND gate can have two or more inputs, its output is true if NOT all inputs are true.
Input A Input B Output Q
0 0 1
0 1 1
1 0 1
1 1 0

Traditional symbol Truth Table
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.
Input A Input B Output Q
0 0 1
0 1 0
1 0 0
1 1 0

Traditional symbol Truth Table
EX-OR (EXclusive-OR) gate
The output Q is true if either input A is true OR input B is true, but not when both of them are true: Q = (A AND NOT B) OR (B AND NOT A)
This is like an OR gate but excluding both inputs being true.
The output is true if inputs A and B are DIFFERENT.
EX-OR gates can only have 2 inputs.
Input A Input B Output Q
0 0 0
0 1 1
1 0 1
1 1 0

Traditional symbol Truth Table

EX-NOR (EXclusive-NOR) gate
This is an EX-OR gate with the output inverted, as shown by the ‘o’ on the output.
The output Q is true if inputs A and B are the SAME (both true or both false): Q = (A AND B) OR (NOT A AND NOT B)
EX-NOR gates can only have 2 inputs.
Input A Input B Output Q
0 0 1
0 1 0
1 0 0
1 1 1

Traditional symbol Truth Table
Summary truth tables
The summary truth tables below show the output states for all types of 2-input and 3-input gates.
Summary for all 2-input gates
Inputs Output of each gate
A B AND NAND OR NOR EX-OR EX-NOR
0 0 0 1 0 1 0 1
0 1 0 1 1 0 1 0
1 0 0 1 1 0 1 0
1 1 1 0 1 0 0 1
Summary for all 3-input gates
Inputs Output of each gate
A B C AND NAND OR NOR
0 0 0 0 1 0 1
0 0 1 0 1 1 0
0 1 0 0 1 1 0
0 1 1 0 1 1 0
1 0 0 0 1 1 0
1 0 1 0 1 1 0
1 1 0 0 1 1 0
1 1 1 1 0 1 0

Note that EX-OR and EX-NOR
gates can only have 2 inputs.
Combinations of logic gates:
Logic gates can be combined to produce more complex functions. They can also be combined to substitute one type of gate for another.
Input A Input B Output Q
0 0 0
0 1 0
1 0 1
1 1 0
For example to produce an output Q which is true only when input A is true and input B is false, as shown in the truth table on the right, we can combine a NOT gate and an AND gate like this:

Q = A AND NOT B

Working out the function of a combination of gates
Truth tables can be used to work out the function of a combination of gates.
For example the truth table on the right show the intermediate outputs D and E as well as the final output Q for the system shown below.

Inputs Outputs
A B C D E Q
0 0 0 1 0 1
0 0 1 1 0 1
0 1 0 0 0 0
0 1 1 0 1 1
1 0 0 0 0 0
1 0 1 0 0 0
1 1 0 0 0 0
1 1 1 0 1 1

D = NOT (A OR B)
E = B AND C
Q = D OR E = (NOT (A OR B)) OR (B AND C)

Substituting one type of gate for another
Logic gates are available on ICs which usually contain several gates of the same type, for example four 2-input NAND gates or three 3-input NAND gates. This can be wasteful if only a few gates are required unless they are all the same type. To avoid using too many ICs you can reduce the number of gate inputs or substitute one type of gate for another.
Reducing the number of inputs
The number of inputs to a gate can be reduced by connecting two (or more) inputs together. The diagram shows a 3-input AND gate operating as a 2-input AND gate.

Making a NOT gate from a NAND or NOR gate
Reducing a NAND or NOR gate to just one input creates a NOT gate. The diagram shows this for a 2-input NAND gate.
Any gate can be built from NAND or NOR gates
As well as making a NOT gate, NAND or NOR gates can be combined to create any type of gate! This enables a circuit to be built from just one type of gate, either NAND or NOR. For example an AND gate is a NAND gate then a NOT gate (to undo the inverting function). Note that AND and OR gates cannot be used to create other gates because they lack the inverting (NOT) function.
To change the type of gate, such as changing OR to AND, you must do three things:
 Invert (NOT) each input.
 Change the gate type (OR to AND, or AND to OR)
 Invert (NOT) the output.
For example an OR gate can be built from NOTed inputs fed into a NAND (AND + NOT) gate.
NAND gate equivalents
The table below shows the NAND gate equivalents of NOT, AND, OR and NOR gates:
Gate Equivalent in NAND gates
NOT
AND
OR
NOR
Substituting gates in an example logic system
The original system has 3 different gates: NOR, AND and OR. This requires three ICs (one for each type of gate).
To re-design this system using NAND gates only begin by replacing each gate with its NAND gate equivalent, as shown in the diagram below.

Then simplify the system by deleting adjacent pairs of NOT gates (marked X above). This can be done because the second NOT gate cancels the action of the first.
The final system is shown on the right. It has five NAND gates and requires two ICs (with four gates on each IC). This is better than the original system which required three ICs (one for each type of gate).
Substituting NAND (or NOR) gates does not always increase the number of gates, but when it does (as in this example) the increase is usually only one or two gates. The real benefit is reducing the number of ICs required by using just one type of gate.

Evaluating Logic Circuit Outputs
Once the Boolean expression for a circuit output has been obtained, the output logic level can be determined for any set of input levels.
This are two examples of the evaluating logic circuit output:
Let A=0, B=1, C=1, D=1
X = A’BC (A+D)’
= 0’*1*1* (0+1)’
= 1 *1*1* (1)’
= 1 *1*1* 0
= 0
Let A=0, B=0, C=1, D=1, E=1
X = [D+ ((A+B)C)’] * E
= [1 + ((0+0)1 )’] * 1
= [1 + (0*1)’] * 1
= [1+ 0′] *1
= [1+ 1 ] * 1
= 1
In general, the following rules must always be followed when evaluating a Boolean expression:
1.First, perform all inversions of single terms; that is, 0 = 1 or 1 = 0.
2.Then perform all operations within parentheses.
3.Perform an AND operation before an OR operation unless parentheses indicate otherwise.
4. If an expression has a bar over it, perform the operations of the expression first and then invert the result.
Determining Output Level from a Diagram
The output logic level for given input levels can also be determined directly from the circuit diagram without using the Boolean expression.

Implementing Circuits From Boolean Expression
If the operation of a circuit is defined by a Boolean expression, a logic-circuit diagram can he implemented directly from that expression.
Suppose that we wanted to construct a circuit whose output is y = AC+BC’ + A’BC. This Boolean expression contains three terms (AC, BC’, A’BC), which are ORed together. This tells us that a three-input OR gate is required with inputs that are equal to AC, BC’, and A’BC, respectively.
Each OR-gate input is an AND product term, which means that an AND gate with appropriate inputs can be used to generate each of these terms. Note the use of INVERTERs to produce the A’ and C’ terms required in the expression.

Universality of NAND & NOR Gates
It is possible to implement any logic expression using only NAND gates and no other type of gate. This is because NAND gates, in the proper combination, can be used to perform each of the Boolean operations OR, AND, and INVERT.

In a similar manner, it can be shown that NOR gates can be arranged to implement any of the Boolean operations.

Alternate Logic Gate Representations:
The left side of the illustration shows the standard symbol for each logic gate, and the right side shows the alternate symbol. The alternate symbol for each gate is obtained from the standard symbol by doing the following:
1. Invert each input and output of the standard symbol. This is done by adding bubbles (small circles) on input and output lines that do not have bubbles, and by removing bubbles that are already there.
2. Change the operation symbol from AND to OR, or from OR to AND. (In the special case of the INVERTER, the operation symbol is not changed.)

Several points should be stressed regarding the logic symbol equivalences:
1. The equivalences are valid for gates with any number of inputs.
2. None of the standard symbols have bubbles on their inputs, and all the alternate symbols do.
3. The standard and alternate symbols for each gate represent the same physical circuit: there is no difference in the circuits represented by the two symbols.
4. NAND and NOR gates are inverting gates, and so both the standard and alternate symbols for each will have a bubble on either the input or the output. AND and OR gates are non inverting gates, and so the alternate symbols for each will have bubbles on both inputs and output.
Logic Symbol Interpretation
Concept of Active Logic Levels:
When an input or output line on a logic circuit symbol has no bubble on it, that line is said to be active-HIGH. When an input or output line does have a bubble on it, that line is said to be active-LOW. The presence or absence of a bubble, then, determines the active-HIGH/active-LOW status of a circuit’s inputs and output, and is used to interpret the circuit operation.

POINTS TO REMEMBER
 Boolean Algebra: A modern algebra which uses the set of numbers 0 and 1, and consists of three basic operations OR, AND and NOT.
 BUS: A group of wires carrying digital signals (group of 0’s and 1’s).
 Canonical Expression: A boolean expression containing either Maxterms or Minterms.
 Non – Canonical Expression: A boolean expression containing Product Terms or Sum Terms. These Product Terms or Sum Terms need not be Maxterms or Minterms.
 Maxterm: Sum containing all the variables of the given Boolean function.
 Minterm: Product containing all the variables of the given Boolean function
 Karnaugh-Map: A graphical display of the fundamental products in a truth table.
 Gate: A logic circuit with one or more signals but one output signal.
 AND Gate: A logic circuit whose output is 1(High) only when all inputs are 1(High).
 OR Gate: A logic circuit whose output is 1(High) only when one or more inputs are 1(High).
 NOT Gate (Inverter): A gate with one input and one output signal, output being complement of the input.
 NAND Gate: Logically means an AND gate followed by an inverter. All inputs must be 1(High) to get a 0(Low) output.
 NOR Gate: Logically means an OR gate followed by an inverter. All inputs must be 0(Low) to get a 1(High) output.
 XOR Gate: A gate which produceses 1(High) output only when inputs have even number of 1’s.
 XNOR Gate: Logically means an XOR gate followed by an inverter. Inputs must have even number of 1’s to get a 1(High) output.
 Truth Table: A table of combinations showing all inputs output possibilities for a Boolean expression.
 Complement: A word in which all 1’s have been changed to 0’s and all 0’s to 1’s. The output of an inverter.
 Postulates, Laws & Theorems:
 P1 : X = 0 or X = 1
 P2 : 0 .0 = 0
 P3 : 1 + 1 = 1
 P4 : 0 + 0 = 0
 P5 : 1 .1 = 1
 P6 : 1 .0 = 0. 1 = 0
 P7 : 1 + 0 = 0 + 1 = 1
 T1 : Commutative Law
A + B = B + AA. B = B. A
 T2 : Associative Law
(A + B) + C = A + (B + C)(A. B). C = A. (B. C)
 T3 : Distributive Law
A. (B + C) = A. B + A .C A + (B. C) = (A + B) (A + C)
 T4 : Identity Law (Indempotence Law)
A + A = A A .A = A
 T5 : Negation Law ( Involution Law)

 T6 : Redundance Law (Absorption Law)
A + A B = A A .(A + B) = A
 T7 : Properties of 0 and 1
0 + A = A 1 .A = A 1 + A = 1 0. A = 0
 T8 : Complementarity Law

 T9 : De Morgan’s Theorem

SOLVED PROBLEMS

Problem 1: Construct a Truth Table for the logical functions at points C, D and Q in the following circuit and identify a single logic gate that can be used to replace the whole circuit.

Solution: First observations tell us that the circuit consists of a 2-input NAND gate, a 2-input EX-OR gate and finally a 2-input EX-NOR gate at the output. As there are only 2 inputs to the circuit labeled A and B, there can only be 4 possible combinations of the input (22) and these are: 0-0, 0-1, 1-0 and finally 1-1. Plotting the logical functions from each gate in tabular form will give us the following truth table for the whole of the logic circuit below.
Inputs Output at
A B C D Q
0 0 1 0 0
0 1 1 1 1
1 0 1 1 1
1 1 0 0 1
From the truth table above, column C represents the output function from the NAND gate and column D represents the output function from the Ex-OR gate. Both of these two output expressions then become the input condition for the Ex-NOR gate at the output. It can be seen from the truth table that an output at Q is present when any of the two inputs A or B are at logic 1. The only truth table that satisfies this condition is that of an OR Gate. Therefore, the whole of the above circuit can be replaced by just one single 2-input OR Gate.
Problem 2:
Find the Boolean algebra expression for the following system.

Solution: The system consists of an AND Gate, a NOR Gate and finally an OR Gate. The expression for the AND gate is A.B, and the expression for the NOR gate is A+B. Both these expressions are also separate inputs to the OR gate which is defined as A+B. Thus the final output expression is given as:

The output of the system is given as Q = (A.B) + (A+B), but the notation A+B is the same as the De Morgan´s notation A.B, Then substituting A.B into the output expression gives us a final output notation of Q = (A.B)+(A.B), which is the Boolean notation for an Exclusive-NOR Gate as seen in the previous section.
Inputs Intermediates Output
B A A.B A + B Q
0 0 0 1 1
0 1 0 0 0
1 0 0 0 0
1 1 1 0 1
Then, the whole circuit above can be replaced by just one single Exclusive-NOR Gate and indeed an Exclusive-NOR Gate is made up of these individual gates.
Problem 3: Find the Boolean algebra expression for the following system.

Solution: This system may look more complicated than the others to analyse but it also consists of simple AND, OR and NOT gates. Again as with the previous example we can write the Boolean notation for each logic function to give us a final expression for the output at Q.

The output from the 3-input AND gate is only a “1” when ALL the inputs are at logic level “1” (A.B.C). The output from the lower OR gate is only a “1” when one or both inputs B or C are at logic level “0”. The output from the 2-input AND gate is a “1” when input A is a “1” and inputs B or C are at “0”. Then the output at Q is only a “1” when inputs A.B.C equal “1” or A is equal to “1” and both inputs B or C equal “0”, A.(B+C). Then by using “de Morgan’s theorem” inputs B and input C cancel out as to produce an output at Q they can be either at logic “1” or at logic “0”. Then this just leaves input A as the only input needed to give an output at Q as shown in the table below.
Inputs Intermediates Output
C B A A.B.C B C B+C A.(B+C) Q
0 0 0 0 1 1 1 0 0
0 0 1 0 1 1 1 1 1
0 1 0 0 0 1 1 0 0
0 1 1 0 0 1 1 1 1
1 0 0 0 1 0 1 0 0
1 0 1 0 1 0 1 1 1
1 1 0 0 0 0 0 0 0
1 1 1 1 0 0 0 0 1

Problem 4: Prove that X.(X+Y)=X by algebraic method.
Solution: L.H.S.= X.(X+Y)=X .X + X .Y
= X + X .Y
= X .(1+Y)
=X . 1 = X = R.H.S

UNSOLVED PROBLEMS
Problem 1: State and verify absorption law using truth table.
Problem 2: Write the equivalent Boolean Expression for the following logic circuit:

Problem 3: Write the POS form of a Boolean function G, which is represented in a truth table as follows

Problem 4: Reduce the following Boolean expression using K-map:
H(U,V,W,Z) = Σ(0,1,4,5,6,7,11,12,13,14,15)
Problem 5: State and Verify Absorption law in Boolean Algebra.
Problem 6: Draw a logical circuit diagram for the following Boolean Expression: A.(B+C’)
Problem 7: Convert the following Boolean expression into its equivalent Canonical Product of sum form (POS): A.B’C + A’.B.C + A’.B.C’.
Problem 8: Reduce the following Boolean expression using K-map:
F(A,B,C,D) = Σ(0,1,2,,4,5,8,9,10,11)
Problem 9: Reduce the following Boolean Expression using K-map.
F(A,B,C,D) = π(0,2,3,4,6,7,8,10,12)
Problem 10: Choose the correct answers in the following questions.
1. What function is implemented by the circuit shown

A x’y’+z
B (x’+y’)z
C x’y’z
D x’+y’+z
E NA
2. What function is implemented by the circuit shown

A x+y+z
B x+y+z’
C x’y’z
D x’+y’+z’
E NA
3. What function is implemented by the circuit shown

A xz’+y
B xz+y
C x’z+y’
D x’y’+y’z’
E x’y’+y’z
4. Which gate is the following circuit equivalent to?

A AND
B OR
C NAND
D NOR
E None of the above
5. Which of the following functions equals the function: f=x+yz’ ?
A x(y’+z)
B x(y’+z)
C (y+x)(z’+x)
D (y+x’)(x’+z’)
E NA
6. Any possible binary logic function can be implemented using only.
A AND
B OR
C NOT
D AA (anyone is sufficient)
E NAND
7. The function in the following circuit is:
A abcd
B ab+cd
C (a+b)(c+d)
D a+b+c+d
E (a’+b’)(c’+d’)
8. Given F=A’B+(C’+E)(D+F’), use de Morgan’s theorem to find F’.
A ACE’+BCE’+D’F
B (A+B’)(CE’D’F)
C A+B+CE’D’F
D ACE’+AD’F+B’CE’+B’D’F
E NA
9. The function in the following circuit is:

A x’+y’+z’
B x+y+z
C x’z’+y’z’
D xy+z
E z
10. Try Harder Simplify the following: {[(AB)’C]’D}’
A (A’+B’)C+D’
B (A+B’)C’+D’
C A’+(B’+C’)D
D A’+B’+C’+D’
E A+B+C+D

POINTS TO FOCUS
Evolution of Networking:
1. ARPANET:In 1969, The US govt. formed an agency named ARPANET (Advanced Research Projects Agency NETwork) to connect computers at various universities and defense agencies. The main objective of ARPANET was to develop a network that could continue to function efficiently even in the event of a nuclear attack.
2. Internet (INTERconnection NETwork): The Internet is a worldwide network of computer networks. It is not owned by anybody.
3. Interspace:InterSpace is a client/server software program that allows multiple users to communicate online with real – time audio, video and text chat in dynamic 3D environments.
Switching Techniques:
1. Circuit Switching: In the Circuit Switching technique, first, the complete end-to-end transmission path between the source and the destination computers is established and then the message is transmitted through the path. The main advantage of this technique is guaranteed delivery of the message. Mostly used for voice communication.
2. Message Switching: In the Message switching technique, no physical path is established between sender and receiver in advance. This technique follows the store and forward mechanism.
3. Packet Switching:In this switching technique fixed size of packet can be transmitted across the network.
Comparison between the Various Switching Techniques:
Criteria Circuit Switching Message Switching Packet Switching
Path established in advance Yes No No
Store and forward technique No Yes Yes
Message follows multiple routes No Yes Yes
Data Communication terminologies:
1. Concept of Channel: – A data channel is the medium used to carry information or data from one point to another.
2. Baud: It is the unit to measure the data transmission speed. It is equivalent to bps (bits per second).
3. Bandwidth: – The maximum volume of data that can be transferred over any communication channel at a given point of time is known as the bandwidth. In analog systems, it is measured in hertz (Hz) and in digital systems; it is measured in bits per second (bps).
4. Data transfer rate: – The amount of data transferred per second by the communication channel from one point to another is known as the data transfer rate. It is measured in bits per second (bps), bytes per second (Bps).
1 kbps = 1024 bps ( bit per second) 1 Kbps = 1024 Bps ( Byte per second)
1 mbps = 1024 kbps 1 Mbps = 1024 Kbps
1 gbps = 1024 mbps 1 Gbps = 1024 Mbps
1 tbps = 1024 gbps 1 Tbps = 1024 Gbps
Transmission media:
1. Twisted pair cable: It consists of two identical 1 mm thick copper wires insulated and twisted together. The twisted pair cables are twisted in order to reduce crosstalk and electromagnetic induction.
Advantages:
(i) It is easy to install and maintain.
(ii) It is very inexpensive
Disadvantages:
(i) It is incapable to carry a signal over long distances without the use of repeaters.
(ii) Due to low bandwidth, these are unsuitable for broadband applications.
2. Co-axial Cables: It consists of a solid wire core surrounded by one or more foil or braided wire shields, each separated from the other by some kind of plastic insulator. It is mostly used in the cable wires.
Advantages:
(i) Data transmission rate is better than twisted pair cables.
(ii) It provides a cheap means of transporting multi-channel television signals around metropolitan areas.
Disadvantages:
(i) Expensive than twisted pair cables.
(ii) Difficult to manage and reconfigure.
3. Optical fiber: – An optical fiber consists of thin glass fibers that can carryinformation in the form of visible light.
Advantages:
(i) Transmit data over long distance with high security.
(ii) Data transmission speed is high
(iii) Provide better noise immunity
(iv) Bandwidth is up to 10 Gbps.
Disadvantages:
(i) Expensive as compared to other guided media.
(ii) Need special care while installation?
4. Infrared: – The infrared light transmits data through the air and can propagate throughout a room, but will not penetrate walls. It is a secure medium of signal transmission. The infrared transmission has become common in TV remotes, automotive garage doors, wireless speakers etc.
5. Radio Wave: – Radio Wave an electromagnetic wave with a wavelength between 0.5 cm and 30,000 m. The transmission making use of radio frequencies is termed as radio-wave transmission
Advantages:
(i) Radio wave transmission offers mobility.
(ii) It is cheaper than laying cables and fibers.
(iii)It offers ease of communication over difficult terrain.
Disadvantages:
(i) Radio wave communication is insecure communication.
(ii) Radio wave propagation is susceptible to weather effects like rains, thunder storms etc.
6. Microwave Wave: – The Microwave transmission is a line of sight transmission. Microwave signals travel at a higher frequency than radio waves and are popularly used for transmitting data over long distances.
Advantages:
(i) It is cheaper than laying cable or fiber.
(ii) It has the ability to communicate over oceans.
Disadvantages:
(i) Microwave communication is an insecure communication.
(ii) Signals from antenna may split up and transmitted in different way to different antenna which leads to reduce to signal strength.
(iii)Microwave propagation is susceptible to weather effects like rains, thunder storms etc.
(iv)Bandwidth allocation is extremely limited in case of microwaves.
7. Satellite link: – The satellite transmission is also a kind of line of sight transmission that is used to transmit signals throughout the world.
Advantages:
(i)Area covered is quite large.
(ii)No line of sight restrictions such as natural mountains, tall building, towers etc.
(iii)Earth station which receives the signals can be fixed position or relatively mobile.
Disadvantages:-
(i) Very expensive as compared to other transmission mediums.
(ii) Installation is extremely complex.
(iii)Signals sent to the stations can be tampered by external interference.
Network devices:
Modem:A MODEM (MOdulator DEModulator) is an electronic device that enables a computer to transmit data over telephone lines. There are two types of modems, namely, internal modem and external modem.
RJ45 connector: – The RJ-45(Registered Jack) connectors are the plug-indevices used in the networking and telecommunications applications. They are used primarily for connecting LANs, particularly Ethernet.
Ethernet Card: – It is a hardware device that helps in connection of nodeswithin a network.
Hub: A hub is a hardware device used to connect several computers together. Hubs can be either active or passive. Hubs usually can support 8, 12 or 24 RJ45 ports.
Switch:A switch (switching hub) is a network device which is used to interconnect computers or devices on a network. It filters and forwards data packets across a network. The main difference between hub and switch is that hub replicates what it receives on one port onto all the other ports while switch keeps a record of the MAC addresses of the devices attached to it.
Gateway: A gateway is a device that connects dissimilar networks.
Repeater: A repeater is a network device that amplifies and restores signals for long distance transmission.
Network Topologies and types:
The BUS Topology:The bus topology uses a common single cable to connect all the workstations. Each computer performs its task of sending messages without the help of the central server. However, only one workstation can transmit a message at a particular time in the bus topology.
Advantages:
(i) Easy to connect and install.
(ii) Involves a low cost of installation time.
(iii) Can be easily extended.
Disadvantages:
(i) The entire network shuts down if there is a failure in the central cable.
(ii) Only a single message can travel at a particular time.
(iii) Difficult to troubleshoot an error.
The STAR Topology: A STAR topology is based on a central node which acts as a hub. A STAR topology is common in homes networks where all the computers connect to the single central computer using it as a hub.

Advantages:
(i) Easy to troubleshoot
(ii) A single node failure does not affect the entire network.
(iii) Fault detection and removal of faulty parts is easier.
(iv) In case a workstation fails, the network is not affected.
Disadvantages:-
(i) Difficult to expand.
(ii) Longer cable is required.
(iii) The cost of the hub and the longer cables makes it expensive over others.
(iv) In case hub fails, the entire network fails.
The TREE Topology: The tree topology combines the characteristics of the linear bus and the star topologies. It consists of groups of star – configured workstations connected to a bus backbone cable.
Advantages:
(i) Eliminates network congestion.
(ii) The network can be easily extended.
(iii) Faulty nodes can easily be isolated from the rest of the network.
Disadvantages:
(i) Uses large cable length.
(ii) Requires a large amount of hardware components and hence is expensive.
(iii) Installation and reconfiguration is very difficult.

Types of Networks:
LAN (Local Area Network): A Local Area Network (LAN) is a network that isconfined to a relatively small area. It is generally limited to a geographic area such as writing lab, school or building. It is generally privately owned networks over a distance not more than 5 Km.
MAN (Metropolitan Area Network):MAN is the networks cover a group of nearby corporate offices or a city and might be either private or public.
WAN (Wide Area Network): These are the networks spread over large distances, say across countries or even continents through cabling or satellite uplinks are called WAN.
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:
 TCP/IP (Transmission Control Protocol / Internet Protocol)
 PPP (Point to Point Protocol)
 FTP (File Transfer Protocol )
 TELNET ( TErminal NETwork OR TELecommunication NETwork)
 GSM ( Global System for Mobile Communications)
 (vi)CDMA( Code Division Multiple Access)
 (vii)GPRS(General Packet Radio Service)
 WLL( Wireless Local Loop)
 SMTP(Simple Mail Transfer Protocol)
 POP3(Post Office Protocol 3)
 VoIP(Voice over Internet Protocol)
 Wi-Fi (Wireless Fidelity)
 WiMAX (Worldwide Interoperability for Microwave Access)
 1 G: 1 G stands for the first generation of wireless analog cellular.
 2 G: 2 G (Second Generation) is digital cellular comprising integrated voice and data communication.
3 G: Some of the advantages of 3 G are:-
(i) Broadband capabilities, greater power and capacity.
(ii) Higher data rate at lower cost than 2G.
(iii) High speed data transmission
(iv) Global roaming, wider coverage.

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 e-mail 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.
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:
(i) Client Side Scripts: – Client side scripts supports interaction within a webpage. E.g. VB Script, Java Script, PHP (PHP’S Hypertext Preprocessor).
(ii) Server Side Scripts: – Server side scripting supports execution at server – end. E.g. ASP, JSP, PHP

Open Source Concepts:
Open Source Software: – Software whose source code is available and which can be modified copied and redistributed. It may be free of cost or not.
Freeware: – The software that is free of cost and can be copied redistributed but can’t be modified because source code is not available.
Shareware: – Software for which license fee is payable after some time limit.
Proprietary Software: – Software that is neither free nor open.
Difference among OSS, Free Software and Freeware:-
S. No. OSS(Open Source Software) Free Software Freeware
1. May be free of cost or not Free of cost Free of cost
2. Source code available Source code available Source code not available
3. Modified, copied, redistributed Modified, copied, redistributed Copied, redistributed but can’t be modified.
FLOSS: – FLOSS refers to Free Libre and Open Source Software or to Free Livre and Open Source Software. The term FLOSS is used to refer to software which is both free software as well as open source software.
FOSS: – software which is free as well as open belongs to category FOSS (Free and Open Source Software).
GNU: – GNU is recursive acronym for GNU’S Not Unix. The GNU project was launched in 1984 to develop a complete UNIX like operating system which is free software. GNU project expanded and now it is not limited to an operating system but also includes application part.
FSF: – Free Software Foundation is a non- profit organization created for the purpose of supporting free software environment. It was founded by Richard Stallman in 1985 to support GNU Project and GNU licenses.
OSI: – Open Source Initiative is an organization dedicated to cause of promoting open source software. It was founded by Bruce Perens and Erics Raymond in Feb. 1998.
Network Design: – The aim of the network design is to minimize the load on the network backbone. The 80-20 rule helps to build a good network design. This rule states that in a LAN, 80 percent traffic should be local and 20 percent traffic should be allowed across the backbone.
Tips to solve Questions based on Networking
1. Where Server should be placed: Server should be placed in the building where the number of computers is maximum.
2. Suggest a suitable cable layout of connection: A suitable cable layout can be suggested in the following two ways:-
(i) On the Basis of Server: First the location of the Server is found out. Server is placed in that building where the number of computers are maximum (According to 80 – 20 rule). After finding the server position, each building distance is compared with the Server building directly or indirectly (taking other building in between). The shortest distance is counted whether it is through directly or indirectly.
(ii) On the Basis of Distance from each building: The distance between the each building is compared to all other buildings either directly or indirectly. The shortest distance is counted whether it is directly or through some other building.
3. Where the following devices be placed:
(i) MODEM:-
(ii) HUB / SWITCH:-
(iii) BRIDGE:
(iv) REPEATER: It is used if the distances higher than 70 m. It regenerates data and voice signals.
(v) ROUTER: When one LAN will be connected to the other LAN.

POINTS TO REMEMBER
 Terminology in data Communication
 Use of various transmission medias in data communication
 Various topologies
 LAN, Man, WAN
 Placing various networking devices in a network
 Network protocols, Security concepts, Web Server
 Open source terminologies
 Abbrivations
SOLVED PROBLEMS
Problem 1: Differentiate between Internet & Intranet.
Solution: The Internet is a world wide network of computer networks around the globe. Internet uses a set of protocols called TCP/IP. Internet is not owned by anybody.
On the other hand Intranet is network within one organisation, which is privately owned. Intranet also use some set of protocols as Internet.
Problem2: How is a Hacker different from a Cracker?
Solution: The Crackers are the malicious programmers who break into secure systems whereas Hackers are more interested is gaining knowledge about computer systems and possibly using this knowledge for playful pranks.
Problem3: Difference between LAN and WAN
Solution: LAN WAN
Diameter of not more than a few kilometers. Span entire contries.
A total data rate of at least several Mbps. Data rate less than 1 Mbps
Completely ownership by a single organization. Owned by multiple organization.
Very low error rates. Comparatively higher error rates.

Problem4 The cyber mind organisation has set up its new branch at Delhi for its office and web activities. It has 4 blocks of buildings as shown in diagram:

i) Suggest the most suitable place to house the server of this organisation with a suitable reason with justification.
ii) Suggest a most suitable cable layout of connections between the Wing and topology.
iii) Suggest the placement of the following device with justification:
• Repeater  Hub/Switch
ii) The organisation is planning to link its head office situated in the city in hilly region where cable connection is not feasible, suggest an economic way to connect it with reasonably high speed.
Solution: i) 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.
ii)a) Bus Topology
Total length of cable required:
40 + 70 + 60 = 170 mtrs

iii) In BusTopology only a Repeater required between Block A & Block C because the distance is large.In Star Topology Repeater required between Block A & Block C and that between Block B & Block C.
A Hub/Switch required to interconnect the different computers in each block.
iv) The most economic way to connect it with a reasonable high speed would be use radio wave transmission, as they are easy to install, can travel long distances, and penetrate buildings easily, so they are widely used for communication, both indoors and outdoors. Radio waves also have the advantage to being omni directional.

UNSOLVED PROBLEMS
Problem 1: What is the difference between Circuit Switching technique, Message Switching technique & Packet Switching technique?
Problem 2: Define the following switching techniques:
(i) Circuit Switching
(ii) Message Switching
(iii) Packet Switching
Problem 3: Define the term Bandwidth. Give unit of Bandwidth.
Problem 4: Write two advantages and two disadvantages of the following Transmission media:
(i) Twisted Pair
(ii) Co- axial
(iii) Optical Fiber
(iv) Radio Waves
(v) Microwave Waves
(vi) Satellite link
Problem 5: Define the following Network devices:
(i) MODEM
(ii) Hub
(iii) Switch
(iv) Gateway
Problem 6: Write two advantages and two disadvantages of the following Network Topologies:-
(i) STAR
(ii) BUS(iii) TREE
Problem 7: Define the following types of Network:
(i) LAN
(ii) MAN(iii) WAN
Problem 8: Define the following Network Security Concepts:
(i) Viruses
(ii) Worms
(iii) Trojan horse(iv) Spams
Problem 9: What do you understand by the terms Cookies and Firewall?
Problem 10: What is significance of Cyber Law?
Problem 11: How is a Hacker different from a Cracker?
Problem 12: Expand the following terms:
FLOSS, FOSS, GNU, FSF, OSI, HTML, XML, HTTP, URL, PHP, ASP, JSP, TCP / IP, FTP, PPP, GSM, CDMA, WLL, 3G, SMS, LAN, MAN, WAN, W3C, SMTP, POP, Wi-Fi
Problem 13: Compare and Contrast the following:-
(i) Free Software and Open Source Software
(ii) OSS and FLOSS
(iii) Freeware and Shareware
(iv) Freeware and Free software.
Problem 14: ABC Carporation has set up its new center at Delhi for its office and web based activities. It has 4 blocks of buildings as shown in the diagram below:
Center to center distances between various blocks
Black A to Block B 50 m
Block B to Block C 150 m
Block C to Block D 25 m
Block A to Block D 170 m
Block B to Block D 125 m
Block A to Block C 90 m

Number of Computers
Black A 25
Block B 50
Block C 125
Block D 10
a) Suggest a cable layout of connections between the blocks.
b) Suggest the most suitable place (i.e. block) to house the server of this
organization with a suitable reason.
c) Suggest the placement of the following devices with justification
(i) Repeater
(ii) Hub/Switch
d)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?

Problem 1: WHAT WIIL BE OUTPUT OF FOLLOWING PROGRAM?
#include
# include
void main()
{clrscr();
int sum(int(*)(int),int);
int square(int);
int cube(int);
cout<
void main( )
{ while(1)
{
cout<<”examination” } } Solution: Unless ^C is pressed ,program will print “examination” infinitely. Problem 3: What would be contents of following after array initialization? int A[5]={3,8 ,9} Solution: A 3 8 9 0 0 Problem 4: What is the difference between the constructor and normal function? Solution: Constructor Normal Function 1. Constructor has same name as class name. 1. A normal function can have any legal name but not class name. 2. Constructor can not have any return type value not even void. 2. A function should have any return type value. 3. Constructor is automatically called. 3. A function is explicitly called. 4. Constructor can not be static. 4. A Function can be static. Problem 5: What is the similarity between class and the constructor? Solution: The only similarity between constructor and is that constructor has same name as class name. Problem 6: Find the output of the following program? #include
#include
#include
class state
{ char *statename;
int size;
public:
state(){size=0;statename=new char[size+1];}
state (char *s)
{ size=strlen(s);statename=new char[size+1];
strcpy(statename,s);
}
void display()
{ cout<
class base
{ public:
void display()
{ cout<<"It is a base class "<=1500
And fare get reduced by 25% if distance is < 1500. - For Children For every child a fixed Rs. 50 is charged as fare. Public members:  A constructor which initialized initialize all data members with 0  Function EnterTour() to input the values of the data members tcode, adults, children and call to AssignFare function.  Function ShowTour() to print all the details of object of Travel type. Solution: class tour { int tcode,adults,children,distance; float totalfare; void assignfare() { float cfare=50, afare=1500; if(distance<1500) afare=afare-(afare*25/100); totalfare=(children*cfare)+(adults*afare); } public: travel() { tcode=adults=children=distance=totalfare=0; } void entertour() {do { cout<<"Enter tcode between 6-10 "; cin>>tcode;
if (tcode<6 || tcode>10)
cout<<"Invalid tcode "<10);
cout<<"Enter children, adults, distance"; cin>>children>>adults>>distance;
assignfare();
}
void showtour()
{ cout<<"tcode:"<>admn
if (admno<10 || admno>1500)
cout<<"Invalid admission no !"<1500);
cout<<"Enter name "; gets(name); cout<<"Enter class and fees "; cin>>cls>>fees;
}
void putdata()
{ cout<<"Admno :"< AE[mid] )
beg = mid +1;
else
end = mid-1;
}
return ((pos==-1)? 0:1);
}
Problem 15: Write a function in C++ to perform a PUSH operations on a dynamically allocated stack containing real number?
Solution: struct Node
{ float data;
Node * next;
};
void push (Node*Top, float num)
{ Node*nptr = new Node;
nptr -> data = num;
nptr -> next = NULL;
if(Top == NULL)
Top = nptr;
else
{ nptr -> next = Top;
Top = nptr;
}
}
Problem 16: Each node of a STACK containing the following information, in addition to required pointer field:
Roll no. of the student
Age of the student.
Give the structure of node for the linked stack in question.
TOP is a pointer to the topmost node of the STACK. Write the following function:
PUSH() – TO push a node in to the stack which is allocated dynamically.
POP() – Te remove a node from the stack and to release the memory.
Solution: struct STACK
{ int rollno, age;
STACK*next;
} *top, *nptr, *ptr;
void pop()
{ if (!pop) { cout << ”\nUnderflow!!” ; exit(1); } else {cout << ’\n’ << top -> rollno << ’\t’ << top -> age;
ptr = top;
top = top -> next;
delete ptr;
}
}
void push()
{ nptr = new stack; //allocate memory
cout << “\n Enter roll number and age to be inserted : “ ; cin >> nptr-> rollno >> nptr->age ;
nptr -> next = NULL;
if (!top) top = nptr;
else
{ ptr -> next = top;
top = nptr
}
}
Problem 17: Write a function in C++ which accepts a 2D array of integers and its size as arguments and displays the elements of the middle row and the elements of middle column.
Example if the array content is
3 5 4
7 6 9
2 1 8
Output through the function should be:
Middle row: 769 Middle column: 5 6 1
Solution: // Function to display the elements which lie on middle of row and column
#include
#include
#include
const M = 10;
const N = 10;
void display_RowCol(int Array[M][N], int r, int c)
{ int row = r / 2;
int col = c / 2;
// Finding the middle row
cout << "Middle Row : "; for(int j=0; j> r;
cout << "Enter total no. of columns: "; cin >> c;
if ((r == c) && ((r%2==1) && (c%2==1)))
{ cout << "Input steps"; cout << "\n\Enter the element in the array\n"; for(i=0; i> Array[i][j]; }
}
else
{ cout << "Input row and column not valid"; getch(); return; } display_RowCol(Array, r, c); } Problem 18: Define function stackpush( ) to insert nodes and stack pops ( ) to delete nodes for a linked list implemented stack having the following structure for each node struct Node { char name [ 20 ] int age ; node * link ; }; class stack { node * top ; public: stack ( ) { top = null ;} ; void stackpush ( ); void stack pop ( ) ; } Solution: void stack::stackpush() { int val; node *temp; temp = new node; cout << "Enter name : "; gets(temp->name);
cout << "Enter age : "; cin >> temp->age;
temp->link = NULL;
if(top ==NULL)
top = temp;
else
{ temp->link = top;
top = temp;
}
}
void stack::stackpop()
{ node *temp;
if (top == NULL)
{
cout << "Stack Empty "; } else { temp = top; top = top->link;
temp->link = NULL;
delete temp;
}
}
Problem 19: Assuming the class Vehicle as follows:
class vehicle
{ char vehicletype[10];
int no_of wheels;
public:
void getdetials()
{ gets(vehicletype);
cin>>no_of_wheels;
}
void showdetails()]
{ cout<<”Vehicle Type”<=65;
(iv) Select COUNT(distinct SUBDJECT) from GRADUATE;
Assume that there is one more table GUIDE in the database as shown below:
Table: GUIDE
MAINAREA ADVISOR
PHYSICS VINOD
COMPUTER SC ALOK
CHEMISTRY RAJAN
MATHEMATICS MAHESH

(f) What will be the output of the following query:
SELECT NAME, ADVISOR FROM GRADUATE,GUIDE WHERE SUBJECT= MAINAREA;
Solution: SELECT NAME FROM GRADUATE WHERE DIV=’I’ ORDER BY NAME;
(b) SELECT NAME, STIPEND, SUBJECT, STIPEND*12 STIPEND_YEAR FROM GRADUATE;
(c) SELECT SUBJECT, COUNT(NAME) FROM GRADUATE GROUPBY (SUBJECT) HAVING SUBJECT=’PHYSICS’ OR SUBJECT=’COMP. Sc.’;
(d) INSERT INTO GRADUATE VALUES(11,’KAJOL’,300,’COMP. Sc.’,75,1);
(e) (i) MIN(AVERAGE) 63
(ii) SUM(STIPEND) 800
(iii) AVG(STIPEND) 420
(iv) COUNT(DISTINCTSUBJECT) 4
(f) SELECT NAME, ADVISOR FROM GRADUATE, GUIDE WHERE SUBJECT=MAINAREA;
NAME ADVISOR
DIVYA RAJAN
SABINA RAJAN
KARAN VINOD
REKHA VINOD
JOHN VINOD
Problem 23: Prove that X.(X+Y)=X by algebraic method.
Solution: L.H.S.= X.(X+Y)=X .X + X .Y = X + X .Y = X .(1+Y) =X . 1 = X = R.H.S
Problem 24: What is the difference between baseband and broadband transmission?
Solution: Baseband is a bi-directional transmission while broadband is a unidirectional transmission.
No Frequency division multiplexing possible in base band but possible in broadband.
SNo Baseband Broadband
1 Entire bandwidth of the cable is consumed by a signal broadband transmission, signals are sent on multiple frequencies, allowing multiple signals to be sent simultaneously.
2 Digital signals Analog signals
3 bi-directional transmission unidirectional transmission
4 No Frequency division multiplexing possible Frequency division multiplexing possible
5 Uses for short distance Uses for long distance

Problem 25: What are the difference between domain and workgroup?
Solution: SNo Domain Workgroup
1. One or more computers are servers All Computers are peers.
2. If you have a user account on the domain, you can logon to any computer on the domain. Each computer has a set of accounts.
3. There can be 100+ computers Typically not more then 20-30 computers
4. The computers can be on different local network All computers must be on the same local netork.

Problem 26: What is protocol? How many types of protocols are there?
Solution: When computers communicate each other, there needs to be a common set of rules and instructions that each computer follows. A specific set of communication rules is called a protocol.Some protocol: PPP, HTTP, SLIP, FTP, TCP/IP
Problem 27: What is the difference between Networking and Remote Networking?
Solution: The main difference between Networking and Remote Networking, is the network which we use in offices or other places locally such LAN or INTERNET and remote networking is one which we use TERMINAL Services to communicate with the remote users such WAN.
Problem 28: What is point-to-point protocol?
Solution: A communication protocol used to connect computer to remote networking services include Internet Service Providers. In networking, the Point-to-Point protocol is commonly used to establish a direct connection between two nodes. Its primary use has been to connect computers using a phone line.
Problem 29: How gateway is different from router?
Solution: A gateway operates at the upper levels of the OSI model and translates information between two completely different network architectures. Routers allow different networks to communicate with each other. They forward packets from one network to another based on network layer information. A gateway can interpret and translate the different protocols that are used on two distinct networks. Unlike routers that successfully connect networks with protocols that are similar, a gateway perform an application layer conversion of information from one protocol stack to another.
Problem 30: What is the differences between POP3 and IMAP Mail Server?
Solution: IMAP is a standard protocol for accessing e-mail from a local server. A simpler e-mail protocol is Post Office Protocol 3 (POP3), which download mail to the computer and does not maintain the mail on the server.
IMAP, e-mails are stored on the server, while in POP3, the messages are transferred to the client’s computer when they are read.
Problem 31: How is Coaxial cable different from Optical Fiber?
Solution: Coaxial cable: It consist of a solid wire core surrounded by one or more foil or braided wire shields, each separated from the other by some kind of insulators. Coaxial cable transmit electrical signals.
Optical Fiber: It consists of thin strands of glass or glass-like material which are so constructed that they carry light from source at one end of the fiber to a detector at the other end. The main advantage of this cable is their complete immunity to noise.
Problem 32: What is the significance of Cyber Law?
Solution: Cyber Law is a generic term which refers to all the legal and regulatory aspects of Internet and the World Wide Web. In internet, the communication technology uses the means of transferring textual message, picture and many more. Each time there may be number of threats on either from the senders or receivers side which creates a bridge between networking communication. To short out these problems, the Internet Security Council made a number of precautions, i.e., rules. These predefined rules called Cyber Law.

Sample Paper -1
SUBJECT: COMPUTER SCIENCE (083)
Class: XII
Time Allowed: 3 hours Maximum Marks: 70
Instructions:
(i) All questions are compulsory.
(ii) Programming Language: C++

1. (a) What is the purpose of using a typedef command in C++? Explain with suitable example. 2
(b) Write the names of the header files to which the following belong:
(i) abs( )
(ii) gotoxy( ) 1
(c) Rewrite the following program after removing the syntactical errors (if any). Underline each correction.
include
include
class Candidate
{
int CandidateId=501;
char Name[20];
public
Candidate() { }
void Register() {cin>>CandidateId; gets(Name);}
void List() {cout<
void main()
{clrscr();
int A[] = {78,80,83,83};
int *p = A;
for(int J = 1; J <= 3; J++) {cout << *p << "#"; p++; } cout<
#include
#include
void Secret(char Msg[],int N);
void main()
{char SMS[] = “PreBoard”;
Secret(SMS,1);
cout<
#include
void main()
{
randomize();
int Num,GuessNum;
cin>>Num;
GuessNum = random(Num-10) + 41;
cout<
#include
class Product
{ char Category[20];
char Type[20];
int Quality;
float Price;
Product() //Function 1
{strcpy(Category, ”Computer”);
strcpy(Type, “Notebook”);
Quantity = 20;
Price = 35000;
}
public:
void display() //Function 2
{cout<
# include
int a=3;
void (int x,int y,int &z)
{ a + =x+y;
z=a+y;
y +=x;
cout<
# include
struct MyBox
{ int length,breadth,height;
};
void dimension(MyBox M)
{ cout<=65;
(viii)Select COUNT(distinct SUBDJECT) from GRADUATE;
Assume that there is one more table GUIDE in the database as shown below:
Table: GUIDE
MAINAREA ADVISOR
PHYSICS VINOD
COMPUTER SC ALOK
CHEMISTRY RAJAN
MATHEMATICS MAHESH

(ix) What will be the output of the following query:
SELECT NAME, ADVISOR FROM GRADUATE,GUIDE WHERE SUBJECT= MAINAREA; 7
6. (a) State Distributive law and verify the same using truth table. 2
(b) Write the equivalent Canonical Sum of Product expression for the followingProduct of Sum Expression F(X,Y,Z) =∏(1,3,6,7) 2
(c) Write the equivalent Boolean Expression for the following Logic Circuit.
2
(d) Reduce the following Boolean expression using K-Map
F(U,V,W,Z) = ∑(0, 1, 2, 3, 4, 10, 11) 2
7. (a) Differentiate between GSM and CDMA. 2
(b) Define the term Bandwidth. Give unit of Bandwidth. 2
(c) What is the significance of Cyber Law? 2
(d) Bhartiya Connectivity Association is planning to spread their office in four major cities in India to provide regional IT infrastructure support in the field of Education & Culture. The company has planned to setup their head office in New Delhi in three locations and have named their New Delhi offices as “FRONT OFFICE”, ”BACK OFFICE”, ”WORK OFFICE”. The company has three more regional offices namely “WEST OFFICE”, “SOUTH OFFICE”, “EAST OFFICE” Located in other three major cities of India. A rough layout of the same is as follow:

i) Suggest network type for connecting each of the following sets of their offices:
a. Back Office and Work Office
b. Back Office and South Office
ii)Which device you will suggest to be produced by the company for connecting all the computers within each of their offices out of the following devices?
Hub/Switch ModemTelephone
iii)Which of the following communication medium, you will suggest to be produced by the company for connecting their local offices in New Delhi for very effective and fast communication.
Telephone cable Optical FiberEthernet Cable
iv)Suggest the layout for connecting each office. 4

Sample Paper -1

1. (a) typedef defines an alias name for an existing type.
Example: typedef float Amount;
Amount principle, loan, balance;
(1 mark for purpose)
(1 mark for suitable example)
(b) (iii) math.h
(iv) conio.h
(1/2 marks for each correct header file)
(c) #include
#include
class Candidate
{
int CandidateId;
char Name[20];
public:
Candidate() { }
void Register() {cin>>CandidateId; gets(Name);}
void List() {cout<
# include
# include float sumfun(int x,int n)
{
float s=1,t=0,t1,t2;
int i,j=1;
for(i=2;i>x>>n;
float result=sumfun(x,n);
cout<<"RESULT="<> operator is use as insertion operator & also as right shift operator.
(e) The output is :
10 ×15× 6
11 × 6 × 6
10 ×16 ×11
(f) It is an internal pointer maintained by C++ as a self referential pointer to the class.It points to the current object being operated upon.
2. (a) The process of protecting data from direct access by the outsider function is called data hiding. In C++ it is implemented through private and protected keyword. The members declared under the section of private or protected are not directly accessible to the outsider function.
(b) exam ob1(80, “Info.Prac.”), ob2(ob1);
(ii) It is showing constructor overloading which implements polymorphism feature of Object Oriented Programming.
(c) class admission
{ int admno;
char name[20];
int cls;
float fees;
public:
admission()
{ admno=10;
strcpy(name,”NULL”);
cls=0;
fees=0;
}
void getdata()
{ do
{ cout<<"Enter admno between 10-1500 "; cin>>admno;
if (admno<10 || admno>1500)
cout<<"Invalid admission no !"<1500);
cout<<"Enter name "; gets(name); cout<<"Enter class and fees "; cin>>cls>>fees;
}
void putdata()
{cout<<"Admno :"< data = num ;
nptr ->next = NULL ;
If (top=NULL)
top = nptr ;
else
{ nptr-> next = top ;
top = nptr ;
}
}
(d) void digototal (int a [ ] [ ] , int n)
{ int sum = 0 ,i,j;
for (i =0 ; i < n ;i ++ ) sum + = a [i][i] ; for ( i =0 ; i< n ;i++) sum + = a [i] [(n-1)-i] ; cout ,<< “ diagonal sum = “ << sum ; } (e) Push 13 push 7 do '+' operation push 11 do '+' push 2 push 4 4 7 11 2 2 13 13 20 20 31 31 31 do '*' do '-' 8 31 23 4. (a) Statement 1: File.seekg(-1*sizeof(L),ios::cur); OR File.seekg(Rec*sizeof(L)); OR File.seekp(-1*sizeof(L),ios::cur); OR File.seekp(Rec*sizeof(L)); OR Any equivalent correct method of calculating size of the record in place of sizeof operator. Statement 2: File.write((char *) &L,sizeof(L)); OR Any equivalent correct method of calculating size of the record in place of sizeof operator. (½ Mark for each correct statement) (b) //Function to count the word in STORY.TXT file void thewordCount() { ifstream Fil(“STORY.TXT”); char String[20]; int C=0; while(!Fil.eof()) { Fil>>String;
if(strcmpi(String,”the”)==0)
C=C+1;
}
cout<>String;
if(strcmp(String,”the”)==0 || strcmp(String,”The”)==0)
C=C+1;
}
cout<=65;
AVG(STIPEND)
420
(viii) SELECT COUNT(DISTINCT SUBJECT) FROM GRADUATE;
COUNT(DISTINCTSUBJECT)
4
(ix)SELECT NAME, ADVISOR FROM GRADUATE, GUIDE WHERE
SUBJECT=MAINAREA;
NAME ADVISOR
DIVYA RAJAN
SABINA RAJAN
KARAN VINOD
REKHA VINOD
JOHN VINOD
6. (a) If X,Y,Z are Boolean Variables then
X . ( Y + Z ) = X . Y + X . Z
OR
X + Y . Z = (X + Y) . (X + Z)
X Y Z Y+Z X.(Y+Z) X.Y X.Z X.Y+X.Z
0 0 0 0 0 0 0 0
0 0 1 1 0 0 0 0
0 1 0 1 0 0 0 0
0 1 1 1 0 0 0 0
1 0 0 0 0 0 0 0
1 0 1 1 1 0 1 1
1 1 0 1 1 1 0 1
1 1 1 1 1 1 1 1
VERIFIED
(1 Mark for stating any one of the Distributive Law correctly)
(1 Mark for verification using Truth Table)
(b) F(X,Y,Z) =∑ (0,2,4,5)
= X’.Y’.Z’ + X’.Y.Z’ + X.Y’.Z’ + X.Y’.Z
(2 Marks for correct expression)
OR
(1 Mark, if a reduced non-canonical SOP expression is given)
(c) F = W.X’ + Y’.Z
(2 Marks for correct expression)
OR
( ½ Mark each for W.X’ and Y’.Z)
(d)
F = U’.V’+W.U+U’.W’.Z’
(½ Mark for drawing correct K-Map )
(½ Mark for plotting 1’s correctly)
(½ Mark for correct grouping)
(½ Mark for correct Answer)
7. (a) a) GSM (Global System for Mobile) communications is a technique that uses narrowband TDMA, which allows eight simultaneous calls on the same redio frequency. TDMA is short for Time Division Multiple Access. TDMA technology uses Time-Division Multiplexing (TDM) and divides a radio frequency into time slots and then allocates these slots to multiple calls thereby supporting multiple, simultaneous data channels.
(b) a) Bandwidth: It refers to the difference between the highest and lowest frequencies of a
transmission channel. This term is also sometimes used to refer to the amount of information travelling through a single channel at any one point of time.
Units: baud, bits per second(bps), kbps, Byte per second(Bps), Kbps, mbps, Mbps
(c) a) Cyber Law is a generic term which refers to all the legal and regulatory aspects of Internet and the World Wide Web. In internet, the communication technology uses the means of transferring textual message, picture and many more. Each time there may be number of threats on either from the senders or receivers side which creates a bridge between networking communication. To short out these problems, the Internet Security Council made a number of precautions, i.e., rules. These predefined rules called Cyber Law.
(d) a) i)
a. Back Office and Work Office – MAN
b. Back Office and South Office – WAN
ii) Hub/Switch required to connect computers of their offices
iii) Optical Fiber
iv) Cable Layout:

Practice Paper- 1
SUBJECT: COMPUTER SCIENCE (083)
Class: XII
Time Allowed: 3 hours Maximum Marks: 70
Instructions:
(i) All questions are compulsory.
(ii) Programming Language: C++

1. a) Write the names of the header files to which the following belong : 2
(i) random( ) (ii) fmod( ) (iii)floodfill() (iv) gotoxy()
b) Name the header files to execute the following program: 2
void main ()
{
char name[20];
char ch;
strcpy(name, “I Revision 2009”);
randomize();
clrscr();
ch = name[11+random(0)];
while (!isalpha(ch) )
{
if (isdigit (ch))
{
cout << setw(10) << int(ch); } ch = name[random(0)]; } getch(); } c) Rewrite the following program after removing syntactical error(s) if any. Underline each correction. 2 #include
#define SIZE =10
VOID Main()
{
int a[SIZE]={1,2,3,4,5};
float x=2;
SIZE=5;
for(int i=0;i>g1.x1<>Charge;}
void Show{cout<
struct PLAY
{ int Score, Bonus;};
void Calculate(PLAY &P, int N=10)
{
P.Score++;P.Bonus+=N;
}
void main()
{
PLAY PL={10,15};
Calculate(PL,5);
cout<
#include
void Encrypt(char T[])
{
for (int i=0;T[i]!=’\0′;i+=2)
if (T[i]==’A’ || T[i]==’E’) T[i]=’#’;
else if (islower(T[i])) T[i]=toupper(T[i]);
else T[i]=’@’;
}
void main()
{ char Text[]=”SaVE EArtH”;//The two words in the string Text
//are separated by single space
Encrypt(Text);
cout<
#include
void main()
{
int N,Guessme;
randomize();
cin>>N;
Guessme=random(N)+10;
cout<
class Item
{
int Ino;char Item[20];
public:
//Function to search and display the content from a particular //record number
void Search(int );
//Function to modify the content of a particular record number
void Modify(int);
};
void Item::Search(int RecNo)
{ fstream File;
File.open(“STOCK.DAT”,ios::binary|ios::in);
______________________ //Statement 1
File.read((char*)this,sizeof(Item));
cout<”<>Ino;cin.getline(Item,20);
______________________ //Statement 2
File.write((char*)this,sizeof(Item));
File.close();
}
(b) Write a function in C++ to count the number of lines present in a text file “STORY.TXT”.2
(c) Write a function in C++ to search for a BookNo from a binary file “BOOK.DAT”, assuming the binary file is containing the objects of the following class. 3
class BOOK
{ int Bno;
char Title[20];
public:
int RBno(){return Bno;}
void Enter(){cin>>Bno;gets(Title);}
void Display(){cout<
struct Pixels
{ int Color,Style;}
void ShowPoint(Pixels P)
{ cout<
void Changethecontent(int Arr[], int Count)
{
for (int C=1;C
struct Game
{
char Magic[20];int Score;
};
void main()
{
Game M={“Tiger”,500};
char *Choice;
Choice=M.Magic;
Choice[4]=’P’;
Choice[2]=’L’;
M.Score+=50;
cout<
#include
void main()
{
int N,Guessnum;
randomize();
cin>>N;
Guessnum=random(N)+5;
cout<
class Employee
{int Eno;char Ename[20];
public:
//Function to count the total number of records
int Countrec();
};
int Item::Countrec()
{
fstream File;
File.open(“EMP.DAT”,ios::binary|ios::in);
______________________ //Statement 1

int Bytes = ______________________ //Statement 2

int Count = Bytes / sizeof(Item);
File.close();
return Count;
}
(b) Write a function in C++ to count the number of alphabets present in a text file “NOTES.TXT”. 2
(c) 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. 3
class STUD
{
int Rno;
char Name[20];
public:
void Enter(){cin>>Rno;gets(Name);}
void Display(){cout<
void main()
{
int s1,s2,num;
s1 = s2 = 0;
for(x=0;x<11;x++) { cin< 0)
s1 += num;
else
s2 = / num;
}
cout<
#include
void ChangeContent(int Arr[], int Count)
{
for(int C=1 ; C
int modify(int temp = 2)
{
if(temp % 3 == 0)
temp = temp + 1;
else
temp = temp + 3;
return temp;
}

void doupdation(int m, int &n)
{
static int i;
i++;
m = n + i;
if(n > 10)
n = modify();
else
n = modify(n);
cout<>no_of_ppl;
}
void showdata()
{
cout<<”Colony Number : “; puts(c_no); cout<<”Colony Name : “; puts(c_name); cout<<” No. of peoples : “<=400;
vii). Select Book_Name, Author_Name from books where Publishers = ‘First’;
viii). Select min(Price) from books where type = ‘Text’;

6 (a) State Distributive Law and verify the same using truth table. 2
(b) Write the Product of Sums form of the function G(U,V,W), truth table representation of
G is as follows : 2
U V W G
0 0 0 1
0 0 1 1
0 1 0 0
0 1 1 0
1 0 0 1
1 0 1 1
1 1 0 0
1 1 1 0

(c) Write the equivalent Boolean Expression for the following Logic Circuit. 2

(d) Reduce the following Boolean Expression using K-Map 2
F(A,B,C,D) = ∑ ( 0 , 3 , 4 , 5 , 7 , 11 , 13 , 15)

7. (a) Write one advantage and disadvantage of Optical Fiber 1
(b) Expand the following terms with respect to Networking. 2
i). CDMA
ii). GSM
iii). SMTP
iv). FTP
(c) What is Website and what is Home Page? 1
(d) What do you mean by E-mail spam? 1
(e) What is India IT Act? 1
(f) PNC Private Ltd. Has four branches in Udaipur city named as “Head Office” , “Marketing Office” , “Clearance Office” and “Service Office”. PNC Company wants to establish the networking between all the four offices. 4
A rough layout of the same is as follows:

Approximate distances between these offices as per network survey team are as follows:
Place From Place To Distance
Head Office Marketing Office 20 m
Marketing Office Clearance Office 200 m
Clearance Office Service Office 40 m
Head Office Service Office 270 m
Marketing Office Service Office 80 m
Head Office Clearance Office 90 m
In continuation of the above, the company experts have planned to install the following number of computers in each of their offices:

Head Office 20
Marketing Office 100
Clearance Office 40
Service Office 60

i). Suggest cable layout(s) for connecting the offices.
ii). Marketing office is used for many critical operations. It is tried that each PC gets maximum possible bandwidth. Which network device should be used for this?
iii). Where would you suggest the placement of server?
iv). The company also has another office out of city but at a distant location about 50-55 km away. How can link be established with this office ( i.e. suggest the transmission medium)?

Practice Paper- 5
SUBJECT: COMPUTER SCIENCE (083)
Class: XII
Time Allowed: 3 hours Maximum Marks: 70
Instructions:
(i) All questions are compulsory.
(ii) Programming Language: C++

1. (a) Differentiate between Call-by-value & call-by-reference giving suitable example of each. 2
(b) Name the header file(s) that shall be needed for successful compilation of the following C++ code
void main ( )
{ char string [20];
gets (string);
strcat(String, “CBSE”);
puts (string);
}
1
(c) Rewrite the following program after removing all error(s) if any. Underline eachcorrection.
# include
#Include(conio.h)
void main ( )
{
int s=10,i;
int a[s];
CLRSCR();
for (I=0; i> Enter any no.;
cin<
void count(int n)
{ if(n>0) {
count(n-1);
}
cout<
void main()
{
int a[] = {3,2,1};
int * p;
p = a;
int i,j;
for(i=0;i<5;i++) { cout< 50)
P.Assignment(0)
else
P.Assignment(10)
______________________//statement 1
______________________//statement 2
Record++;
}
File.Close( );
}
};
If the function Allocate Marks( ) is supposed to allocate Marks for the records in the file MARKS.DAT based on their value of the member TimeTaken. Write C++ statements for the statement1 and statement2, where statement1 is required to position the file write pointer to an appropriate place in the file and statement2 is to perform the write operation with the modified record. 1
(b) Write a function in C++ to print the count of all the vovel in the file Data.txt.
For example, if the content of the file Data.txt is
This is the simple data file.
Answer is : – 9 2
(c) Assuming the given definition of class HOTELDATA, write functions in C++ to perform the following:
(i) Checkins() function to allow user to enter the data of customers (objects of class HOTELDATA) and write them to a binary file “HOTEL”.
(ii) Count() function to count the number of customers (number of objects of class HOTELDATA) present in the hotel.
class HOTELDATA
{
int room;
char nmae[20];
int duration;
public:
void enter();
void display();
};
Also complete the member function definitions. 3
5. (a) What do you understand by DOMAIN and TUPLE of a RELATION? 2
(b) Consider the following tables EMPLOY and DESIG. Write SQL commands for the statement (i) to (iii) and give outputs for SQL queries (iv) to (vi)
EMPLOY
W_ID FIRST NAME LAST NAME CITY
102 SAM TONES PARIS
105 SARAH ACKERMAN NEW YORK
144 MANILA SENGUPTA NEW DELHI
210 GEORGE SMITH HOWARD
255 MARY JONES HUSTON
300 ROBERT SAMUEL WASHINGTON
335 HENRY WILLIAMS BOSTON
400 RONNY LEE NEW YORK
451 PAT THOMPSON PARIS
DESIG
W_ID SALARY BENEFITS DESIGNATION
102 75000 15000 MANAGER
105 85000 25000 DIRECTOR
144 70000 15000 MANAGER
210 75000 12500 MANAGER
255 50000 12000 CLERK
300 45000 10000 CLERK
335 40000 10000 CLERK
400 32000 7500 SALESMAN
451 28000 7500 SALESMAN
(I) To display W_ID, firstname, city of all employees living in New York from the table EMPLOY.
(II) To display the content of EMPLOY table in ascending order of firstname.
(III) To display the firstname, total salary of all Managers from the tables EMPLOY and DESIG, where first name start with “S” (total salary=Salary+benefits).
(IV) SELECT FIRSTNAME,SALARY FROM EMPLOY,DESIG WHERE DESIGNATION=’MANAGER’ AND EMPLOY.W_ID=DESIG.W_ID;
(V) SELECT COUNT(DISTINCT DESIGNATION) FROM DESIG;
(VI) SELECT DESIGNATION,SUM(SALARY) FROM DESIG GROUP BY DESIGNATION HAVING COUNT(*) < 3; 6 6. (a) Prove (x+y)(x+z) = x+yz algebraically. 2 (b) Interpret the following logical circuit as Boolean expression : a b f c d 2 (c) Write the POS and the SOP form of a Boolean function F, which is represented in a truth table as follows: W X Y Z F 0 0 0 0 0 0 0 0 1 1 0 0 1 0 0 0 0 1 1 1 0 1 0 0 1 0 1 0 1 0 0 1 1 0 1 0 1 1 1 1 1 0 0 0 0 1 0 0 1 1 1 0 1 0 0 1 0 1 1 1 1 1 0 0 1 1 1 0 1 0 1 1 1 0 0 1 1 1 1 1 1 (d) Obtain the simplified form of a Boolean expression using K-Map. F(a,b,c,d)= ∏(0,1,2,3,4,7,11,12,14) 3 7. (a) What do your understand by Hackers and Cracker? 1 (b) Expand the following terminology (i) XML (ii) GSM (iii) CDMA (iv) TCP/IP 2 (c) Differentiate between message switching and packet switching 1 (d) What is difference between Virus and Worm? 1 (e) What do you mean by Cookies? 1 (f) Indian Industries has the following four buildings in Chennai. Distance between various wings are given below: Wing II1 to Wing II 3 70m Wing II1 to Wing II 2 20m Wing II 1 to Wing II 4 115m Wing II 3 to Wing II 4 30m Wing II 2 to Wing II3 25m Number of Computers Wing II 1 35 Wing II 2 25 Wing II 3 80 Wing II 4 60 i. Suggest suitable CABLE LAYOUTS FOR THESE BUILDINGS. ii. Name the wing where the Server is to be installed. Justify your answer. iii. Suggest the placement of Hub/Switch in the network. iv. Mention an economic technology to provide Internet accessibility to all wings. 4 Practice Paper- 6 SUBJECT: COMPUTER SCIENCE (083) Class: XII Time Allowed: 3 hours Maximum Marks: 70 Instructions: (i) All questions are compulsory. (ii) Programming Language: C++ 1 a. What is object oriented programming? How it is different from procedural programming?2 b. Name the header files to which the following built-in functions belong to? 1 (a) isalpha () (b) printf() c.Rewrite the following program after removing syntactical errors (if any) underline each correction 2 #include ;
void main
{ int j =99, a ;
float u=10.0 ;
cin (a) ;
int b= sqrt(a)
while a <=j { a+ =10 u = *b b= sqrt (a) } } d.Give the output for the following program segment: 2 void prnseries (void) { static int start =10; int i = 0; c ; for (;I ,3 ; I ++) { c = start/2; cout << “\n ” << start << ‘\t’ << c; start + =20; } } main( ) { int i = 3; for (int j = 0 ; j < i ; j++) prnseries( ); return 0; } e. Write the output of following program segment 3 int &max (int & x,int& y) { if (x > y)
{x ++ ; return x ;}
Else
{ y++ ;return y ; }
}
Void main ( )
{ int A =5, B=7;
max (A,B)= -1;
cout << “A=” <
Void main ()
{
Ifstream fin(“Text.txt”);
Char word[50];
While(————————) //#1
{
————————- ; //#2
Cout<>memno>>outamt;}
Void putit()
{cout<30.
(iii) SELECT SUM (Price*QTY) FROM MOV WHERE QTY<3. (iv)SELECT COUNT(DISTINCT TYPE) FROM MOV 6. (a) What do you understand by the terms Cardinality and Degree of arelation in relational database?2 (b)Given the following LAB table, write SQL command for the questions(i) to (iii) and give the output of (iv). 6 LAB No ItemName CostPerItem Quantity Dateofpurchase Warranty Operational 1 Computer 60000 9 21/5/96 2 7 2 Printer 15000 3 21/5/97 4 2 3 Scanner 18000 1 29/8/98 3 1 4 Camera 21000 2 13/10/96 1 1 5 Switch 8000 1 31/10/99 2 1 6 UPS 5000 5 21/5/96 1 4 7 Router 25000 2 11/1/2000 2 5 (i) To select the ItemName,which are within the Warranty period till present date. (ii) To display all the itemName whose name starts with “C”. (iii)To list the ItemName in ascending order of the date of purchase where quantity is more than 3. (iii) Give the output of the following SQL commands: (a) select min(DISTINCT Quantity) from LAB; (b) select max(Warranty) from LAB; (c) select sum(CostPerItem) from Lab; 7. (a) State and verify De-Morgan’s law in Boolean Algebra. 2 (b) Interpret the following logical circuit as Boolean expression. 2 f (c) Reduce the following Boolean expression using K-map. 3 F(A, B, C, D)= (0, 1, 2, 4, 5, 7, 8, 9, 10, 11, 14) (d) Prove that XY+YZ+YZ’=Y 1 8. (a) Explain function of hub and router. 1 (b) Expand the following terms: 2 (i) URL (ii) ISP (iii) DHTML (iv) CDMA (c) Differentiate between message switching and packet switching 1 (d) Indian Industries has the following four buildings in Chennai. Distance between various wings is given below: Wing II1 to Wing II 3 70m Wing II1 to Wing II 2 20m Wing II 1 to Wing II 4 115m Wing II 3 to Wing II 4 30m Wing II 2 to Wing II3 25m Number of Computers Wing II 1 35 Wing II 2 25 Wing II 3 80 Wing II 4 60 i. Suggest suitable CABLE LAYOUTS FOR THESE BUILDINGS. 1 ii. Name the wing where the Server is to be installed. Justify your answer. 1 iii. Suggest the placement of Hub/Switch in the network. 1 iv. Mention an economic technology to provide Internet accessibility to all wings. 1 Practice Paper- 7 SUBJECT: COMPUTER SCIENCE (083) Class: XII Time Allowed: 3 hours Maximum Marks: 70 Instructions: (i) All questions are compulsory. (ii) Programming Language: C++ Q. 1. (a) Name the Header file(s) that shall be needed for successful compilation of thefollowing C++ code void main() 1 { int a[10]; for(int i=0;i<10;i++) { cin>>a[i];
if(a[i]%2==0)
a[i]=pow(a[i],3);
else
a[i]=sqrt(a[i]);
if(a[i]>32767)
exit(0);
}
getch();
}
(b). Rewrite the following program after removing syntactical error(s) if any. Underline each correction. 2
#include
type def int integer;
struct number
{
integer a [5];
}
void main()
{
number x;
for(int i=0;i<5;i++) cin>>x[i].a;
getch();
}
(c). Find the output of the following program : 2
#include
#include
void main()
{
char *a[2]={”Amit”,”Sumit”};
for(int i=0;i<2;i++) { int l=strlen(a[i]); for(int j=0;j
class student
{
public:
student()
{
cout<<”\n Computer Science“; } ~student() { cout<<” subject”; } }st; void main() { cout<<” is my best“ } (e). In the following C++ program , what will the maximum and minimum value of r generated with the help of random function. 2 #include
#include
void main()
{
int r;

randomize();
r=random(20)+random(2);
cout<
Name :
Address :


Marks : <….subject 5 marks>
Percentage : Also create main() function which will invoke all the public member functions.
(d). Answer the questions (i) to (iv) based on the following code : 4
class Employee
{
int id;
protected :
char name[20];
char doj[20];
public :
Employee();
~Employee();
void get();
void show();
};
class Daily_wager : protected Employee
{
int wphour;

protected :
int nofhworked;
public :
void getd();
void showd();
};
class Payment : private Daily_wager
{
char date[10];
protected :
int amount;
public :
Payment();
~Payment();
void show();
};
i. Name the type of Inheritance depicted in the above example.
ii. Name the member functions accessible through the object of class Payment.
iii. From the following, Identify the member function(s) that can be called directly from the object of class Daily_wager class
show()
getd()
get()
iv. Name the base & derived class of Daily_wager class.
Q. 3. (a) Write a function in C++ which accepts a integer array and its size as an arguments and prints the output (using nested loops) in following format : 2
Example : if the array is having
1 2 4 5 9
Then the output should be
1
2 2
4 4 4 4
5 5 5 5 5
9 9 9 9 9 9
(b). An array A[10][20] is stored in the memory with each element occupying 2 bytes of storage. If the Base address of array in the memory is 800 , determine the location of A[9][10] when the array is stored as (i) Row Major (ii) column major. 3
(c). Write a function in C++ to delete a node containing names of student , from a dynamically allocated Queue of names implemented with the help
of following structure : 3
struct student
{
char name[20];
student *next;
}*front , *rear;
(d). Consider the following portion of a program , which implements a linkedstack for Library . Write the definition of function PUSH(),to insert a new node in the stack with required information 2
struct Library
{
int id;
char names[20];
};
class stack
{
Library *top;
public :
stack()
{
top=NULL;
}
void PUSH();
void POP();
};
(e). Convert the following infix expression into postfix. show the stack status after execution of each operation: 2
TRUE OR FALSE AND NOT FALSE OR FALSE
Q. 4. (a). Differentiate between ios::app and ios::ate file opening modes. 1
(b). Write a function in C++ which will print the size of a text file “story.txt” in the form of bytes.2
(c). Write a function in C++ which will increase the qty of a particular type of item from the file “stock.dat” . Assuming that the binary file is containing the records of following structure : 3
struct Products
{
int id;
char Iname[30];
int type;
int qty;
};
Accept the item type from user whose qty has to be increased .
Q. 5. (a). What do you understand by Primary Key 2
(b). Consider the following tables Employee and salary. Write SQL commandsfor the statements (i) to (iv) and give outputs for SQL queries (v) to (viii) 6
Table : Employee
Eid Name Deptid Qualification Sex
1 Deepali Gupta 101 MCA F
2 Rajat Tyagi 101 BCA M
3 Hari Mohan 102 B.A M
4 Harry 102 M.A M
5 Sumit Mittal 103 B.Tech M
6 Jyoti 101 M.Tech F
Table : Salary
Eid Basic DA HRA Bonus
1 6000 2000 2300 200
2 2000 300 300 30
3 1000 300 300 40
4 1500 390 490 30
5 8000 900 900 80
6 10000 300 490 89
a. To display the frequency of employees department wise.
b. To list the names of those employees only whose name starts with ‘H’
c. To add a new column in salary table . the column name is total_sal.
d. To store the corresponding values in the total_sal column.
e. Select name from employee where eid=(select eid from salary where basic= (select max(basic) from salary));
f. select max(basic) from salary where bonus >40;
g. Select count(*) from employee group by sex;
h. select Distinct deptid from Employee;
Q. 6. (a) State and prove the Distributive law algebraically. 2
(b). Write the equivalent POS expression of following SOP form 2
F (x,y,z)= ∑ (0,2,4,6)
(c). Draw the Logical circuit of the following expression with the help of NAND gate only 1
x+yz
(d). Obtain the simplified form of a Boolean expression using K-Map. 3
F(a,b,c,d)=∑(0,1,2,3,4,7,11,12,14)
Q. 7. (a). What do your understand by Hackers? 2
(b). Differentiate between Internet & Intranet 2
(c). Expand the following terminology : 1
1. SMS
2. FTP
(d). Define Repeater. 1
(e). A company in Reliance has 4 wings of buildings as shown in the diagram: 4

Center to center distances between various Buildings:
W3 to W1 50m
W1 to W2 60m
W2 to W4 25m
W4 to W3 170m
W3 to W2 125m
W1 to w4 90m
Number of computers in each of the wing:
W1 150
W2 15
W3 15
W4 25
Computers in each wing are networked but wings are not networked. The company has now decided to connect the wings also.
i. Suggest a most suitable cable layout & topology of the connection between the wings.
ii. The company wants internet accessibility in all the wings. Suggest an economic technology .
iii. Suggest the placement of the following devices with justification if the company wants minimized network traffic
a)Repeater
b)Hub
c)Switch
d)Bridge
iv. The company is planning to link its head office situated in India with the offices at Reliance. Suggest a way to connect it; the company does not want to compromise with the speed of connectivity. Justify your answer.

ACTION PLAN
To improve the quality and quantity of result of class XII in the subject Computer Science following points are to be followed:
Important tips to study/retain/answer:
(1) Cyclic test of each unit after the completion of that unit.
(2) After the completion of each unit, the questions asked in the previous year examinations should be solved.
(3) Definition of important terms of different units with examples.
(4) Intext questions and examples of book of each unit should be carefully solved.
(5) Practice again & again the error finding & correction questions
(6) Master cards of syntax of programming language should be prepared.
(7) Master cards of important header files, library function etc. should be prepared.
(8) Practice of last three years question papers of CBSE exam (three sets) of all India, Delhi & foreign set.
(9) Practice of 1st& 2nd unit test, 1st& 2nd pre board papers should be solved.
(10) Regular practice of sample papers.
(11) Regular interaction with parents to discuss the problems of child & steps should be taken to sort out the problem & improve the performance.
(12) Slow learners and Bright students must be identified, not only on the basis of tests but on the basis of their overall performance including that of class XI.
(13) Separate plan for slow learners and bright students.
(14) Full participation of all the students, specially of slow learners must be insured during teaching-learning process.
(15) Teacher should prepare a power point presentation on each chapter at completion and should present in front of the class as to revise the chapter and also for solving of any query remained in the class room.
(16) Group of students should also present the chapter in the class so that slow learners can have a better understanding.
(17) Group study / Co-operative learning should be implemented by students by making small group of 4-5 students having bright plus slow learner students in each group.
(18) Bright students should be provided with a chance to present topics of their interest in the class under the guidance of teacher.
(19) Teacher should provide master cards to the students.
(20) The improvement in the child status of learning should be regularly measured
(21) Class regularity of the students in class must be ensured.
(22) The communication gap between the teacher and students should be overcome.
(23) The teacher should ascertain that the class room transaction grabs attention of all the students.For this, he can use soft skills like asking questions from pertinent discussion.
(24) Drilling of important points should be done once in a week.
(25) Regular self study must be done and key points/ Short notes should be prepared by the student for further revision.
(26) Revision of the contents taught during the week on holidays.
(27) Discussion of problems with class mates and teachers.
(28) Ask student to prepare project or program to solve the problem of their surroundings by this way they learn how to apply the knowledge of computer language they are learning.
(29) Stick to minimum level of learning.
(30) Personal discussion with each student and try to find out the reason:-
 Why is he/she not performing well in test?
 Why does he/she secure low percentage?
 Why is he/she not serious about my subject?

For Bright Students:
(1) Bright students should be provided with a chance to present topics of their interest in the class under the guidance of teacher during revision
(2) Practice of HOTS of each unit.
(3) Conceptual question should be given for practice & solve their problem individually.
(4) Their questions of competitive level should be taken and discussed by giving conceptual view.
(5) Encourage them to search and read topics online.

Practical/ realistic plan for slow learners:

Identification of slow learners:

The area may be:
 home environment
 lack of confidence
 irregular in the class
 poor grasping power
 diversion towards other activities

Remedial actions / steps:

(1) Personal guidance & counseling.
(2) Moral boosting by asking simple question.
(3) Frequently motivating.
(4) A package of selected questions, with low difficulty level based on CBSE.
(5) Bright student should adopt a slow learner for improvement and guidance to encourage peer learning.
(6) Making the topic easy & interesting by relating with daily life.
(7) Ensure that they attend the classes regularly.
(8) Insist and encourage textbook reading
(9) Attitude should be unbiased.
(10) Encourage the child to get rid of phobias and fear for examination.
(11) Drilling & sufficient practice of important questions.
(12) Remedial classes during Recess, Games Period, WET period, Computer literacy period & arrangement periods.
(13) Easy & fundamental portion syllabus should be selected to get at least 50%-60% marks.

Day to Day Practice for slow learners:
(1) Affectionate and cooperative behaviour.
(2) Maximum questions should asked to them for their active participation in classroom.
(3) Each chapter should be divided into small topics & students should be asked to read it carefully & frame maximum number of question & answer them
(4) More focus on the simple topics catering their needs.
(5) Vigilant and continous follow up.
(6) Make them sit in front row.
(7) Check their C.W. And H.W. copy regularly with suggestive remarks and Special Attention given to those students always while in the class as well as in the Computer Lab.

Exam Oriented content – transaction:

(1) Stressing on the important points while teaching the lesson.
(2) Keynotes should be given after the lesson is completed.
(3) Frequent evaluation by small tests
(4) Designing and explaining hots questions during the classroom teachers
(5) Frequent revision & assessments.
(6) Well preparation of the content by the teacher
(7) Identification of the interesting questions related to the topic which attracts attention of the students and motivates them to learn the topic.
(8) Use of the attractive teaching aids like LCD and explain the topic by on line demonstration will encourage the student towards practice and by this way he learn the content.
(9) Solution of the questions asked in previous years.

STEPS FOR QUANTITATIVE &QUALITATIVE IMPROVEMENT OF THE RESULT

Steps For Quantitative Improvement Of The Result

 The poor performing students should be counseled and motivated in order to enhance their interest in Computer Science as well as to improve the quantitative result the subject.
 Separate remedial teaching should be done for poor performers in order to remove their learning difficulties.
 All poor performers should be asked to maintain a separate Practice Note book in which the student should practice the topics in the home, taught day by day in the classroom and discuss the difficulties, if any, with his teacher. This Practice book must be signed by the Parents daily. This practice should be maintained throughout the session
 At the fag end of the session, the students who are still unable to perform well, should be drilled with the important questions being frequently asked in Previous years’ Board exams in one form or the other.

Steps for qualitative improvement of the result:

To improve the result quality, special attention should be paid to Bright and Average students. For this, following actions may be taken:
 Class room Conferencing:- For this, the students of different Groups should be assigned the Topics turn by turn on which, they should come prepared to give a presentation in front of the class. Teacher as well as other students may ask the questions related to the topic. If needed, the teacher should intervene and clarify the concepts during the presentation.
 Frequent Class Tests: – After completion of every subsequent lesson, one of the groups should prepare a question paper from all the chapters up to that lesson including all type of question based on CBSE pattern and this question paper should be solved by entire class. For preparation of the question paper, the students may go through CBSE model papers, Model papers provided by KVS, as well as papers from other publishers. After the completion of the test, the teacher should discuss Marking scheme in detail. The other Group should evaluate the answer scripts .The task of preparing question papers and correcting answer scripts should be given to groups in alternate manner. In this manner, the last test so conducted will include entire syllabus.
 Higher Order thinking questions (HOTS) should include every topic’s classroom discussion and Bright students should be encouraged to go through more of them.
 Use of ICT (Information & Communication Technology) should be encouraged to promote visual learning and better comprehension of the Subject matter.
 Meaningful conduct of PTA meeting: In PTA meeting, a comprehensive discussion of students’ academic, Non academic and behavioral aspects should be done with the parents and based on it, a remedial course of action should be decided to be implemented subsequently.

DIFFICULTIES FACED BY TEACHERS & SUGGESTIONS

Difficulties faced by Teachers:

3. Lack of interest of students in programming.
4. Irregularity of students in school and mass absenting on mass P.T. day and week ends (CCA day).
5. Casual approach of Parents and students towards PTA meeting.
6. Lack of self study at home. Most of the students spend more time in coaching/Private tuition.
7. Over involvement in official and other ICT related works which gives less time to bring innovation in teaching.
8. Lack of infrastructure like unavailability of High power generators especially in areas where there is frequent power cut.
9. Lack of maintenance of computers as there is No facility of AMC of computers in most of the schools.
10. Softwares provided by KVS do not fulfill the syllabus requirement and ICT requirement of school.
11. Short duration of the period.

Suggested Solutions
Co-operation is solicited from the competent authorities to cope up with the problems mentioned above.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s