328
CHAPTER 1 REVIEW OF C++ FOREVIEW POINTS OF FOCUS SOLVED PROBLEMS POINTS TO REMEMBER 16

CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

  • Upload
    others

  • View
    8

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

CHAPTER 1

REVIEW OF C++

FOREVIEW

POINTS OF FOCUS

SOLVED PROBLEMS

POINTS TO REMEMBER

16

Page 2: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

FOREVIEW

Programming Paradigm: Organizing principle of a program

Procedural Programming: It is a paradigm that emphasis is on doing things rather than the data being used.

Object Oriented Programming: It is a paradigm where data and procedures both are given equal importance

Object: It is an identifiable entity with some characteristics and behaviour.

Class: A class represents a group of objects that share common properties.

Abstraction: It is the act representing essential features without including the background details.

Encapsulation: It is the binding up of data and functions into a single unit

Inheritance: Inheritance is the capability of one class of things to inherit capabilities or properties from another class

Polymorphism: Polymorphism is the ability for a message or data to be processed in more than one form.

Character set: Character set is a set of valid characters that a language can recognize

Keyword: Keyword is a special word that has a special meaning and purpose. Keywords are Reserved.

Identifier: Identifiers are the user-defined name given to a part of program.

Variables: Variables represent named storage locations whose values can be manipulated during program run.

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 and Derived data types.

Modifiers The keywords which appear before a data type, change its meaning, are modifiers.

Operators in C++: C++ provides six types of operators. They are I/O operators, Arithmetic operators, Increment/Decrement operator, Relational Operator, Logical operator, Conditional operators.

Flow of Control Statements: The three flow control statements are: sequence, selection ( if , switch), iteration(while loop, do while loop, for loop).

Console I/O Operators: It performs input from standard input device and out put to the standard output device of a system.

17

Page 3: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS OF FOCUS

1. Programming ParadigmOrganizing principle of a program. It is an approach to programming. Example: Procedural programming, Modular Programming , Structural Programming

2. Procedural ProgrammingProcedural programming paradigm aims more at procedures. The emphasis is on doing things rather than the data being used. In procedural programming paradigm, data are shared among all the functions participating thereby risking data safety and security.

3. Object Oriented ProgrammingObject Oriented Programming paradigm is based on the principles of data hiding, abstraction, inheritance, and polymorphism. It implements programs using classes and objects. In OOP paradigm, data and procedures, both are given equal importance. Data and functions are encapsulated to ensure data safety and security.

4. ObjectIt is an identifiable entity with some characteristics and behaviour. e.g: Orange is an object. Its characters are spherical shaped, color is orange etc. Its behaviour is It is juicy and tastes sweet sour.

5. ClassA class represents a group of objects that share common properties. “Bird” is a class and “parrot” is an object of the class

6. Abstraction It is the act representing essential features without including the background details.e.g.: While driving a car, We only know the essential features to drive a car like handling steering, applying break etc. we do not get into internal details like how the motor working. What is happening inside is hidden from us. This is called abstraction.

7. EncapsulationIt is the binding up of data and functions into a single unite.g.: In a company, each department’s employees and their work are encapsulated as a single unit

8. InheritanceInheritance is the capability of one class of things to inherit capabilities or properties from another class. e.g.: We inherit certain properties such as ability to speak, breath, eat, drink etc. from the class “Human”.

9. PolymorphismPolymorphism is the ability for a message or data to be processed in more than one form.e.g.: A working lady can behave in different way according to different situation. She can behave as mother at home and she can behave as an employee in office.

10. Character setCharacter set is a set of valid characters that a language can recognizeEg: Letters, Digits, Special characters, White spaces and other characters.

18

Page 4: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

11. Keyword Keyword is a special word that has a special meaning and purpose. Keywords are reserved. For example class, switch, else etc., are keywords.

12. IdentifierIdentifiers are the user-defined name given to a part of program. E.g. variable, object, function etc. Identifiers are not reserved. These are defined by the user but they can have letters, digits and a symbol underscore. They must begin with either a letter or underscore. For instance: _chk, chess, trial etc. are identifiers.

13. VariablesVariables 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.

14. Data typesData types are the means to identify the type of data and associated operations of handling it. C++ offers two types of data types:

10.1. 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.

10.2 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.

15. ModifiersThe 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.

16. setw() Manipulatorsetw() Manipulator is an operator that can be inserted directly into input output statements to give the space. For example.

cout<<setw(10) <<”RollNumber”<<setw(15)<<”Name;

17. setprecision( ) Manipulatorsetprecision( ) sets the total number of digits to be displayed when floating point numbers are printed.

e.g., 1. cout<<setprecision(5)<<123.456; OUT PUT = 123.46 (rounding the digits)

2. cout.setf(ios :: fixed) ; cout<<setprecision(5)<<12.345678; OUT PUT = 12.34567 (no rounding)

19

Page 5: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

18. Operators in C++C++ provides six types of operators. They are i) I/O operators (>>, <<)

ii) Arithmetic operators( +, -, * , / and %)iii) Increment/Decrement operator( ++,--) iv) Relational Operator (>,<,=,>=,<= , !=, ==) v) Logical operator( ! , ||, &)vi) Conditional operators. ( ? : )

19. Flow of Control StatementsThe three flow control statements are: sequence, selection( if , switch), iteration(while loop, do while loop, for loop).

19. 1. If statement:The if statement allows branching depending upon the result of logical expressionSyntax:

If (condition) or if (condition){ { statements; statements;} }

else{

statements;}

19.2. 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;

}

19.3 While statement:While loop allows programs to repeat a statement or series of statements as long as a certain test condition is true.

Syntax:

20

Page 6: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

while (test expn) { statements; }

19.4 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);

19.5 For statement:This statement in the loop repeat continuously a certain number of times.Syntax:

for(initialize; test- expn; update) { statements; }

20. 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;

21

Page 7: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

21. Console I/O Operations

Console I/O functions perform 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 Console I/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.

21.1 getchar() This function reads a character from the keyboard.char ch=getchar();

21.2 putchar()This function prints a character to the screen.putchar(ch);

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

21.3 gets(): This function accepts a string of characters entered by the keyboard.

21.4 puts(): This function writes a string of characters on the screen.

21.5 get(): The function get() fetches a single character and stores it in a character variable. char ch; cin.get(ch);

21.6 put():The put() function output a character to the standard output.cout.put(ch);

21.7 getline() :This function reads a line of text that ends with a new-line character. Syntax is cin.getline(line, size,);

e.g: char name[21]; getline(name,30);

22

Page 8: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

21.8 Write(): This function is invoked with cout stream object and displays a line of text on the screen. Syntax is cout.write(line,size);e. g: cout.write(name,3);

22. 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 are stdio.h string .h math.h stdlib.h iostream.h iomanip.h 22.1 string.h

The header file declares several string manipulation and memory manipulation routines . e.g: strlen strcmp strcpy strcat strupr

22.2 math .hThis header file declares prototypes for math functions. The routines in math.h perform mathematical calculations and conversions.

e.g: ceil() atan() cos() abs()

exp() floor() log() pow()

sqrt() sin() acos() asin()

22.3 iostream.hThis header file declares the basic C++ streams I/O Routines e.g: open() close() get() getline()

seekg() seekp() eof() flush()

read() write() tellp() tellg()

22.4 stdlib.hThis file declares commonly used routines like conversion routines, sort routines . e.g: atof() atoi() atol() ltoa()

malloc() calloc() abs() free()

22.5 ctype.h

23

Page 9: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

The functions included are

22.5.1 isalpha(ch): returns nonzero if the argument is a character otherwise returns zero.

22.5.2 isdigit(ch): returns nonzero if ch is a digit else zero returns.

22.5.3 islower(ch): returns nonzero if ch is a lowercase letter else zero returns.

22.5.4 isupper(ch): returns nonzero if the argument is a uppercase character otherwise returns

zero.

22.5.5 toupper(ch): returns uppercase equivalent of ch.

22.5.6 tolower(ch): returns lowercase equivalent of ch.

24

Page 10: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

SOLVED PROBLEMS

1) Reusability of classes is one of the major properties of OOP. How is it implemented in C++?Solution::

Inheritance is the capability of one class of things to inherit capabilities or properties from another class. In C++, a class inheriting its properties from another class, is known as, is known as the subclass or derived class. The class, whose properties are inherited, is known as base class or super class.

A sub class inherits properties from its base-class, thereby, reuses a class. Hence inheritance implements reusability in C++.

2) Write two major differences between Object Oriented Programming and Procedural Programming?

Solution::Procedural programming paradigm aims more at procedures. The emphasis is on doing things rather than the data being used. In procedural programming paradigm, data are shared among all the functions participating thereby risking data safety and security.

Object Oriented programming paradigm is based on the principles of data hiding, abstraction, inheritance, and polymorphism. It implements programs using classes and objects. In OOP paradigm, data and procedures, both are given equal importance. Data and functions are encapsulated to ensure data safety and security.

3) What is the difference between a keyword and an identifier?Solution::

Keyword is a special word that has a special meaning and purpose. Keywords are reserved and are a few. For example goto, switch, else etc., are keywords.

Identifiers are the user-defined name given to a part of program. E.g. variable, object, function etc. Identifiers are not reserved. These are defined by the user but they can have letters, digits and a symbol underscore. They must begin with either a letter or underscore. For instance _chk, chess, trial etc. are identifiers.

4) What is the difference between ‘a’ and “a” in C++?Solution::

Characters enclosed in single quotes are character constants in C++. Thus ‘a’ is a character constant.Characters enclosed in double quotes are string-literals which are array of characters. Thus “a” is a string. i.e., in memory “a” is represented as “a\0” where \0(null) character is the terminator of the string.The size of ‘a’ is 1 character whereas the size of “a” is 2 characters.

5) What are data types? What all are predefined data types in C++?Solution:

Datatypes are the means to identify the type of data and associated operations of handling it. C++ offers two types of data types:Fundamental datatypes: These are the datatypes that are not composed of any other data type. There are five fundamental data type: char, int, float, double and void.Derived datatypes: These are the datatypes that are composed of fundamental data types. These are array, function, pointer, reference, constant, class, structure, union and enumeration.

25

Page 11: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

6) What are data type modifiers? How do they affect a base data type?Solution:

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.

7) Differentiate setw( ) and setprecision( ) with example.Solution:

setw() Manipulator is an operator that can be inserted directly into input output statements to give the space. For example. cout<<setw(10) <<”RollNumber”<<setw(15)<<”Name;

setprecision( ):Sets the total number of digits to be displayed when floating point numbers are printed.

Sets the number of decimal places to be displayed. e.g., 1. cout<<setprecision(5)<<123.456; OUT PUT = 123.46 (rounding the digits)

2. cout.setf(ios :: fixed) ; cout<<setprecision(5)<<12.345678; OUT PUT = 12.34567 (no rounding)

8) Differentiate continue and break and explain the functioning of these statements in the iteration loop ?Solution:

break : Enables a program to skip over part of the code

while (test exprsn) { statement 1; if (val >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

26

Page 12: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

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;

9) Given the following code fragmentint ch = 20;cout<<ch <<++ch<<ch<<”\n”;i) What output does the above code fragment produce?ii) What is the effect of replacing ++ch with ch+1?

Solution:i ) 21 21 20

ii) ++ch not only replaces itself with value ch+1 i.e., 21 also increments the value of ch. i.e., after ++ch the value of ch is 21. Whereas ch + 1 will only print the incremented value. i.e., 20 +1 = 21, it will not increment the value of ch. Therefore, after replacing ++ch with ch +1, the output of the program, will be 20 21 20

10) Given the two following expression : (a) val = 3 (b) val = =3i) How are these two different?ii) What will be the result of the two if the value of val is 5 initially

Solution:i) The expression (a) is an assignment expression and the expression (b) is a relational expression that tests for equality.

ii) The result of (a) will be val having value 3 i.e., 3 and the result of (b) will be 0 (false) because 5 is not equal to 3

11) What will be the output of the following code fragment produce? int val, res, n = 1000; cin>>val; res = n + val > 1750 ? 400 : 200; cout<<res; i) if the input is 2000 ii) if the input is 1000 iii) if the input is 500.

Solution:i) 400, because the arithmetic operator + has higher precedence than? : operator thus

the condition before ? is taken as (n + val) and 1000+ 2000 > 1750 is true.ii) 400, the reason is the same as explained above(1000 + 1000) > 1750 is true).iii) 200, because (1000 + 500)1750 is false.

27

Page 13: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

12) Determine the output?(i) a = 2

b = ++a cout <<a;cout<<bcout<<a++cout <<++a

OUTPUT = 3 3 3 5

ii) a= 1; b = a++; cout<<a++; cout<<(b+a); cout<<++b;

OUT PUT = 2 4 2

13) Why main function is special? Give two reasons?Solution:

Whenever a C++ program is executed only the main() is executed i.e., execution of the program starts and ends at main ( ) is the driver function of the program. If it is not present in a program, no execution can take place.

14) Write the two advantages of using #include compiler directive.Solution:

The # include compiler directive lets us include desired header files in our program which enables us work with all declarations/definitions/macros inside the included header file(s).It supports modularity i.e., a bigger program can be decomposed in terms of header files and later included through this directive.

15) Name the header files to which the following functions belongs i)abs() ii)atoi()

Ans: i)math.h ii)stdlib.h

16) Name the header files that shall be needed for the successful compilation of the following C++ code.

void main()

{

char ch,string[20];

gets(string);

strcat(string,”Computer”);

puts(string);

}

Ans: stdio.h, string.h

17) Name the header file, to which the following built in functions belongs to:

i)gotoxy() ii)open() iii)ceil() iv)strcmp()Ans: i) conio.h ii) iostream.h, iii)math.h iv) string.h

28

Page 14: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

18) Name the header files that shall be needed for the successful compilation of the following C++ code.

void main()

{

char st1[20],st2[20];

cout<<”Enter the strings”;

cin.getline(st1,15);

cin.getline(st2,15);

if(strlen(str1)==strlen(str2))cout<<”Both strings contain equal number of characters”;}

Ans: iostream.h ,string.h

19) Name the header file , to which the following built in functions belongs to: i) pow() ii)malloc() iii)toupper() iv) log()

Ans: i) math.h ii)stdlib.h iii)ctype.h iv) math.h

29

Page 15: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS TO REMEMBER

1 Statements are the instructions given to the computer to perform any kind of action.

2 A compound statement in C++ is a sequence of statements enclosed by a pair of braces.

3 C++ provides two types of selection statements: if and switch.

4 The if - else statement can be nested.

5 C++ provides three loops: for, while and do – while

6 The loops can be nested.

7 A break statement can appear in any of the loops and a switch statement.

8 The continue statement abandons the current iteration of the loop by skipping over the rest of the statement on the loop- body.

9 The goto statement transfers the program control anywhere in the program.

10 The do – while executes at least once always as it evaluates the test expression at the end of the loop

11 The while loop evaluates a test-expression before allowing entry into the loop.

12 The for loop can have multiple initialization and update expressions separated by commas.

13 The loop – control elements in a for loop are optional.

30

Page 16: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

CHAPTER 2

STRUCTURES

FOREVIEW

POINTS OF FOCUS

SOLVED PROBLEMS

POINTS TO REMEMBER

31

Page 17: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

FOREVIEW

Structure: Structure is a collection of variables referenced under one name.

Nested Structure: A structure can be nested inside another structure (a structure inside another).

Arrays within structure: When a structure element happens to be an array, it is treated in the same way as arrays are treated.

Passing structure elements to functions: When an element of a structure is passed to a function,

you are actually passing the value of that element to the

function.

Passing entire structure to functions:

Call by value:When a structure is used as an argument to a function, the entire structure is passed

using the standard call-by-value method.

Call by reference: When a structure is passed by reference the called function declares a reference for the passed structure and refers to the original structure elements through its reference.

32

Page 18: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS OF FOCUS

1. Structures

Structures 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;

1.1 Differences between structures and classes

• Structures and classes are syntactically and functionally identical, except in the default accessibility of their members and their inheritance.

• By default, members of structures have public accessibility and public inheritance from their parent(s), while members of classes are private and inherit privately from their parent(s).

• Individual members' accessibility can be specified by using the public, protected and private keywords.

1.2 Declaration and usage

• C++ structures and classes have their own members. • These members include variables (including other structures and classes), functions (specific

identifiers or overloaded operators) known as methods, constructors and destructors. • Members are declared to be either publicly or privately accessible using the public: and

private: access specifiers respectively. • Any member encountered after a specifier will have the associated access until another

specifier is encountered. There is also inheritance between classes.

1.3 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

{ string name; int age; };

33

Page 19: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

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 <iostream>#include <string>struct person{ string name; 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 outputCalvin: 30Hobbes: 20

1.4 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

1.4 Nested Structures

• A structure can be nested inside another structure (a structure inside another).Eg. struct addr { int house_no; char area[26]; }; struct emp { int empno;

34

Outer Structure

Inner Structure

Page 20: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

char name[26]; addr address; }; emp worker; The structure emp has been defined having several elements including a structure address also.

1.5 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;

1.6 Properties

• The syntax of C++ tries to make every aspect of a structure look like that of the basic datatypes.

• Therefore, overloaded operators allow structures to be manipulated just like integers and floating-point numbers.

• Arrays of structures can be declared with the square-bracket syntax (some_structure variable_name[size]),and pointers to structures can be de-referenced in the same way as pointers to built-in datatypes.

Memory consumption • The memory consumption of a structure is at least the sum of the memory sizes of its

constituent variables. Take the two nums structure below as an example.• struct twonums { int a; int b; }; • The structure consists of two integers. In many current C++ compilers, integers are 32-bit

integers by default, so each of the member variables consume four bytes of memory. The entire variable, therefore, consumes at least (or exactly) eight bytes of memory.

1.7 Structures and Arrays

Arrays of structureSince an array can contain similar elements, the combination having structures within an array is known as array of structures.

Consider the above structure ‘addr’,to store addresses of 100 members of the council we can give the statement as

addr mem_addr[100]; Where mem_addr represents the structure variable of array type. To access a specific structure ,index the structure name. cout<<mem_addr[7].houseno; will print the house no of structure 8.

1.8 Arrays within structure

When a structure element happens to be an array, it is treated in the same way as arrays are treated.

35

Page 21: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

To access the element, its structure name followed by a ‘.’ and the array name is to be given.

struct student { int rollno; char name[21]; float marks[5]; }; student learner;

The above declared structure variable learner is structure type student that contains an element which is an array of 5 floats to store marks of 5 different subjects.To reference marks of 3rd subject of structure learner, we shall write. learner.marks[2];

1.9 Passing structures to functions

When a structure is local to a function and we want pass its values to another function. It can be achieved in two ways

1. by passing individual structure elements 2. by passing the entire structure.

1.9.1 Passing structure elements to functions

When an element of a structure is passed to a function, you are actually passing the value of that element to the function. It is just like passing simple variable.

For Eg:

struct date { short day;

short month; short year;}Bdate;

Individual elements of this structure can be passed as follows.func1(Bdate.day, Bdate.month, Bdate.year);

1.9.2 Passing entire structure to functions

The entire structure can be passed to the functions both ways by value and by reference.

Call by value

When a structure is used as an argument to a function ,the entire structure is passed using the standard call-by-value method. ie, any changes made to the contents of the structure inside the function to which it is passed do not affect the structure used as an argument.

36

Page 22: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Call by reference

When a structure is passed by reference the called function declares a reference for the passed structure and refers to the original structure elements through its reference.

1.9.3 Returning structures from functions

Functions can return structures also only the condition is that the return type of the function is the same that of the type of the structure returned.

SOLVED PROBLEMS

1. What is a structure?Ans: A structure is a collection of logically related variables referenced under one name.

2. Declare a structure ans contains the following members:I. An integer quantity called ians

II. A floating point quantity called fans.III. A character quantity called answer.

Ans: struct ans {

int ians;float fans;char answer[10];

};3. What is meant by nesting of structure?

Ans: A structure may consist of structure inside it which is known as a nested structure.

4. Do you pass structures by copy or by address?Ans: Yes, we can structure by copy or by address.

5. What are the individual elements of a structure called?Ans: The individual elements of a structure is called data members.

6. Give the output of the following program#include<iostream.h>struct Pixel{ int C,R;};void Display(Pixel P){ cout<<”Col”<<P.C<<”Row”<<P.R<<endl;}void main ()

37

Page 23: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

{ Pixel X={40,50},Y,Z; Z=X; X.C+=10; Y=Z Y.C+=10; Y.R+=20; Z.C=15; Display(X); Display(Y); Display(Z); }

Ans: The output is Col50Row50

Col50Row70 Col25Row50

7. Find out the error, if any, in the following program:main (){ struct student { char name[25]; int age; int roll; } student stud; strcpy(stud.name,”Haris”); age=17; cout<<name; cout<<stud.age;

}

Ans: i) The structure should end with semicolon. ii) age is the member of structure .So it should be written as follows

stud.age=17; iii) name is also the member of structure so it should be written as follows

cout<<stud.name;8. Differentiate between structure variable declarations and structure type declaration.?

Ans:The structure variable declarations are held with the name of the structure tag.

The structure type is defined with the name of the structure tag also.

9. Define a structure consisting of two integer members called hra and da?Ans: struct employee

{ int hra; int da;};

10. What will be the output of the following program:

38

Page 24: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

struct def{ int i; int f;};void main(){ def d; d.i=100; d.f=1.5; func(d); cout<<d.i<<” “<<d.f;}void func(def d){ d.f=2.5; cout<<d.i<<d.f;}

Ans: The output is as 1002100 1

11. What is the relationship between a member and a structure? Ans: A member is either a data member or a member function in a structure ,which is declared in the structure itself. Whereas the structure holds number of data members and member functions.

12. Write a structure that a video store can use in a program to track the video tape inventory.Make sure that the structure includes the tape’s title, the length of the tape (in minutes),the cost of the tape ,the rental price of the tape, and the date of the movie’s release.

Ans: #include<iostream.h> #include<string.h>

#include<conio.h> 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;

39

Page 25: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

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’);}

13. 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.

Ans: : #include<iostream.h> #include<string.h>

#include<conio.h> #include <stdio.h> const N =20;

struct student {

char name[20];int totmark;

} 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<N;i++){ cout<<”student”<<i+1<<endl; cout<<”Enter student’s name”; cin>>stud[i].name; cout<<”Enter student’s total mark”; cin>>stud[i].totmark;}for(i=0;i<N-1;i++){ for(j=i+1;j<N:j++){

if (stud(i).totmark>stud(j).totmark)

{temp = stud(i);

40

Page 26: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

stud(i) = stud[j];stud[j] = temp;

}}}

cout<<endl<<stud[N-1].name<<”Secures Highest mark”<<stud{N-1].totmark<<endl;cout<<endl<<stud[0].name<<”Secures HLowest mark”<<stud{0].totmark<<endl;getch();

}

POINTS TO REMEMBER

1. A structure is a collection of logically related variables referenced under one name.

2. In C++, a structure is actually a class ,declared with keyword ‘struct’. By default all members

are public in a structure, where as in class, these are private by default.

3. The individual structure elements are referenced using (.), the dot operator.

4. The structure elements of a structure can be initialized either separately, using separate

assignment statements or jointly, using the notation similar to array initialization.

5. A structure may consist of structure inside it which is known as a nested structure.

6. Array of structures are also be created.

7. Combination having structures within an array is known as array of structures

8. Arrays present inside the structure is treated in the same way as arrays are treated.

9. Structures can be passed to function either by passing its elements individually or by passing

the entire structure.

10. Structures can be passed by value as well as by reference.

11. Functions can also return structures or its references.

CHAPTER 3

41

Page 27: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

OBJECT ORIENTED PROGRAMMING

FORE VIEW

42

FORE VIEW

POINTS OF FOCUS

SOLVED PROBLEMS

POINTS TO REMEMBER

Page 28: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Programming Paradigms: A programming methodology defines the methodology of designing and implementing programs using the key features and other building blocks of a programming language.

Procedural Programming: Procedural programming is a programming paradigm that gives more emphasis to procedure than data.

Object based Programming: Object based programming is a programming paradigm that encloses data and associated meaningful functions in one single entity called a class.

Object oriented programming: Object oriented Programming is a programming paradigm that combines data and procedures in one single unit called object.

Object: Object is an identifiable entity with some characteristics and behaviour. Examples: Car, Apple, Chair etc.

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. Classes: A class is a group of similar objects. Examples: Vehicle, Fruits, Furniture.

Data Hiding: Data Hiding is a related concept of data abstraction. Unessential features or background details are hidden from the world.

Data Abstraction: It is the act of representing the essential features without including thebackground details and explanations.

Implementing Inheritance: Inheritance is implemented by specifying the name of the base class from which the class being defined (derived class) has to inherit from.

Abstract class: Abstract class is the one which defines an interface, but does not necessarily provide implementations for all its member functions.

Concrete class: A derived class that implements all the missing functionality is called a Concrete class. It is derived from an abstract class.

Polymorphism: The attribute that allows one interface to be used with different situation.Overloading: The term overloading means a name having two or more distinct meanings.

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.

43

Page 29: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS OF FOCUS

1. 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

1.1 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

1.2 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

1.3 Object oriented programmingDefinition : 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

44

Page 30: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

2. OOP Concepts:

The Important OOP concepts are: Data Abstraction Data Hiding Data Encapsulation Object inheritance Polymorphism

2.1 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.

2.2 Implementing Objects:The characteristics or states are maintained with the help of variables or data items.The behaviour is implemented through functions or methods.

2.3 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)ii) Encapsulation is used to hide unimportant implementation details from

other objects. iii) iii) Packaging an object’s variables within the protective custody of its

methods is called encapsulation & this task is accomplished through Classes.

2.4 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<class name> {

private ://hidden data members/methods here

protected ://(un important implementation details here

public ://exposed implementation details here

};

2.5 Data Hiding: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:

45

Page 31: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

PrivateProtected andPublicThe private & protected members remain hidden from outside world. Thus through private & protected members class enforces data hiding.

2.6 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.

2.7 Implementing Inheritance:

Inheritance is implemented by specifying the name of the base class from which the class being defined (derived class) has to inherit from.

class <class name> : <base class name> {

derived class own features }

2.8 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.

2.9 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.

2.10 Implementing Polymorphism:

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. 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.

2.11 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);

46

Page 32: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

SOLVED PROBLEMS

1. What are the OOP concepts? 2 marksAns: The Important OOP concepts are:

Data Abstraction Data Hiding Data Encapsulation Object inheritance Polymorphism

2. Explain the concept of data abstraction and its implementation in C++. 2 marksAns. 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.

3. Explain the concept of data encapsulation and its implementation in C++. 2 marksAns. 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.

4. Explain the concept of data hiding and its implementation in C++. 2 marksData 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:PrivateProtected andPublic

The private & protected members remain hidden from outside world. Thus through private & protected members class enforces data hiding.

5. Explain the benefits of data encapsulation. 1 markAns. Encapsulation is having the benefits of modularity and information hiding.

6. Explain the concept of object and its implementation in C++. 1 markAns. 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.

7. Explain the concept of polymorphism and its implementation in C++. 1 markAns. 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.

8. Differentiate between abstract and concrete classes 2 marksAns. 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

47

Page 33: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

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.

9. State the advantages of Object Oriented Programming. 2 MarksAns. i) Object oriented Programming enables re use of codeii) 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.

10. Differentiate between Object Oriented and Object Based Programming. 2 MarksAns. 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.

11. Give any 2 examples for Object Oriented Programming. 1 Marks Ans. C++, Java

12. A function printchar is defined as 2 marks

void printchar(char ch = ‘*’, int len = 40) {for(x = 0;x<len;x++)cout<<ch;cout<<endl;}How will you invoke the function for following output?

(i) to print ‘*’ 40 times(ii) to print ‘=’ 40 times

Ans. (i) printchar( ) (ii)printchar(‘=’)

POINTS TO REMEMBER

48

Page 34: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

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

Function overloading, its definition and declaration

Calling an overloaded function

Restrictions on creating overloaded function

Steps involved in finding the best match by compiler in function overloading.

CHAPTER 4

49

Page 35: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

CLASSES AND OBJECTS

50

FORE VIEW

POINTS OF FOCUS

SOLVED PROBLEMS

POINTS TO REMEMBER

Page 36: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

FOREVIEW

Need for classes

Classes are needed to represent real world entities, which not only have data type properties (their characteristics) but also associated operations (their behavior).

Declaration of Classes

The keyword - class, is used to declare a class.

Referencing Class Members

The members of a class are referenced using object of the class .

Arrays within a Class

A class can have an array as its member variable that can be private or public data member of the class.

Scope of Class and its Members

Scope of a class and its members are determined by the three access labels namely public,

private and protected.

Types of Class functions

Member functions of a class can be categorized into following three categories: (i) Accessor function (ii) MutatorFunction (iii) Manager Function

Functions in a Class

A class can contain three types of function declared inside it namely inline function, constant

member function and nested function.

Inline functions

A function definition such that each call to the function is, in effect, replaced by the

statements that define the function is called as an Inline function.

Constant Member Functions

If a member function of a class does not alter any data in the class, then, this member function may be declared as a constant member function using the keyword const

The Scope Resolution Operator

The scope resolution operator ::, is used to distinguish between class member names and

other names and when used with classname depicts the class member and when used with

variables depicts the global variable.

Using Objects

Objects are created to store data members of a class. The public members of a class are

accessed by using the objectname and dot operator.

51

Page 37: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Array of Objects

An array having class type elements is known as array of objects.

Objects as Function Arguments

An object may be passed to a function as an argument in two ways (i) Call By

value (ii) Call by Reference

Functions Returning Objects

The objects can be passed to as well as returned from functions.

Static Class Members

Class variables which are common for all objects of the class are known as Static

data members. They can be accessed only by a static member function.

52

Page 38: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS OF FOCUS

1. Introduction

A Structure can contain variables of different types or of the same type. The members inside a structure are easily accessible with out any restriction.

One of the major characteristics of OOP is data hiding. C++ being an Object Oriented language offers an important data type called - class to achieve the data hiding property.

NOTE: A class is a way to bind data and associated functions together. But a structure provides a way to group data elements.

2. Need for a Class If we want to represent -the details of students like: name , roll number, marks and Operations like : finding percentage, finding grade etc. , we need class to represent real world objects that have data type properties and associated operations.

NOTE: Classes are needed to represent real world entities, which not only have data type properties (their characteristics) but also associated operations (their behavior).

3. Classes A class is a user defined data type that binds data describing an entity and its associated

function together under a single unit. It has members which consist of the – Data members

Constructor function Destructor functions Member functions. The structure and behavior of similar objects are defined in their common class. A class is a collection of Objects. The objects belonging to a class are called instances of

the class.

3.1 Class Specification A class specification does not define any object of its type, rather it just defines the properties of a class. A class specification has two parts:

(1) Class declaration – It describes the component members (both data members and function members) of the class.

(2) Class method definition (member function definition) – It describes how certain class member functions are implemented.

3.1.1 Declaration of Classes: - The keyword - class, is used to declare a class.The general form of a class definition – class class_name { Access label1:

Variable declarations; Function declarations; Access label2:

53

Page 39: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Variable declarations; Function declarations;

Access label3: Variable declarations;

Function declarations;};

Declaration of classes involves declaration of its 4 associated attributes (1) Data members: They are the variables that are declared in a class. They describe the

characteristics of a class.(2) Member functions: They are the operations performed on data members of a class.(3) Program Access levels: control access to members from within the program. These access

levels are: private, protected or public.(4) Class_name (tag name): serves as a type specifier for the class using which objects of this

class type will be created.

3.1.2 The Class Method DefinitionProviding code for the member functions.Member functions can be defined in two places:

(i) Outside the class definition(ii) Inside the class definition.

(i) Outside the class definition:-The member function definition outside the class definition is much the same as that of function definitions, with only difference: the name of the function is the full name(Qualified name) of the function i.e. returntype class_name :: function_name (Parameter list){ function body;}

Where, class_name – indicates that the function specified by function _name is a member of the class specified by class_name:: - called scope reSolution: operator, specifies that the scope of the function is restricted to the class class_name.

(ii) Inside the class definition:- When a member function is defined inside a class, the function definition is just similar to the function definitions (i.e) no need to put membership label along with the function name.NOTE:

• Only small functions are usually defined inside the class definition.• A function defined inside a class is an inline function• Inline property is a hint to the compiler to insert the code for the body of the function

( declared inline) at the place where it is called, there by saving the overheads (i.e) time spent in loading and unloading of the called function) of a function call.

Example for outside class definition

class student

{ int rollno; // private by default float marks;

54

Page 40: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

public : void getdata(); void display();};

void student::getdata(){ cout<<“\n Enter roll number : “; cin>>rollno; cout<<“\n Enter marks : “; cin>>marks; }

void student::display(){ cout<<“\n Roll No. “<<rollno; cout<<“\n marks : “<<marks; }

Example for inside class definition

class student { int rollno; // private by default float marks; public : void getdata() { cout<<“\n Enter roll number : “; cin>>rollno; cout<<“\n Enter marks : “; cin>>marks; }

void display() { cout<<“\n Roll No. “<<rollno; cout<<“\n marks : “<<marks; }

};3.2 Referencing Class MembersThe members of a class are referenced using object of the class

The private data of a class can be accessed only through the member functions of that class. The public data member can be accessed by the non-member functions through the objects of

that class using the format : object_name . public data member

Eg: A1.Z( if Z is a public data member)(if Z is a private data member then the compiler will report an error.) The public member functions of a class are called by non – member functions using the objects. The general format for calling a public member function is : Object_name.publicfunction_name(actual_Arguments);Eg: A1.getdata(): A1.getdata(2,3);

3.3 Arrays Within a Class

55

Page 41: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

• A class can have an array as its member variable.• An array in a class can be private or public data member of the class.

[ If an array happens to be a private data member of the class , then only the member functions of the class can access it.

If an array is a public data member of the class, it can be accessed directly using objects of this class type.]

When a member function is called by another member function of the same class , it is known as nesting of member functions.

3.4 Scope of Class and Its Members:

Element Scope Description

Class    Global Global Scope This class type is globally available to all the

functions within a program. Therefore, the objects of this class type can be created from any function within the program.

Local Local Scope This class type is locally available to all the function in which the class definition occurs. The objects of this class type can be created only within the function that defines this class type.

object    Global Global Scope This object can be used anywhere in the program by

any functionLocal Local Scope This object can be used only within the function that

declares it.Class Members

   

private Class scope These members can be accessed only by the member functions of the class. These cannot be accessed directly by using objects

public Global for global objectsLocal for local objects

The scope of public members depends upon the referencing object. If the referencing object is local, the scope of public member is local. If the referencing object is global, the scope of public member is global.

3.5 Types of Class Functions

Member functions of a class can be categorized into following three categories:(i) Accessor functions : These are the member functions that allow us to access the data

members (field) of object. Accessor functions cannot /do not change the value of data members Accessor methods are used to read values of private data members of a class which are directly not accessible in non-member function. If we provide a public accessor function for that, the value of private data members becomes accessible yet being safe as accessor functions do not modify data.[If a user wants to know the current value of a private data member , get it through an accessor function.

56

Page 42: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

(ii)Mutator functions: These are member functions that allow us to change the data members of an

object.(iii) Manager functions : These are member functions with specific functions i.e constructors and

destructors that deal with initializing and destroying class instances.

NOTE:- Accessors and Mutators are sometimes called getters and setters.

By making everything public, data becomes unsafe and vulnerable defeating the very purpose of object orientation. Hence we use Acccessors and Mutators to make sure that data is edited in a desired manner through a mutator.Eg:-class student { int rollno; // private by default float marks; public : void getdata(); void display(); int getroll() // Accessor method

{ return rollno;}

void calcgrade()// Mutator method { if marks >=75 grade =‘A’; else if marks >=60 grade =‘B’; else if marks >=50 grade =‘C’;

else grade =‘F’; }};

void student::getdata(){ cout<<“\n Enter roll number: “; cin>>rollno; cout<<“\n Enter marks : “; cin>>marks; }void student::display(){ cout<<“\n Roll No. “<<rollno; cout<<“\n marks : “<<marks; }

3.6 Visibility of Class Members

Private members can be accessed only from within the class. They are hidden from the outside world. These members implement the OOP concept of data hiding. They can be used only by member functions and friends of the class in which it is declared. ( A friend of a class is a function that is not a member of the class but is permitted to use the private and protected members from the class.)

57

Page 43: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Public members can be accessed from anywhere outside the class where the class is visible. They can be directly accessed by any function i.e member function of the class or non-member functions. Hence the keyword public provides the class members the public interface.

Protected members are that can be used only by member functions and friends of the class in which it is declared and are inheritable.

NOTE:

If we declare the members of a class without specifying the access label the members are by default private.

Eg :

class student { int rollno; // private by default float marks; public : void getdata(); void display();};

We can also declare a class without member functions and data members. Such a class is called an empty class.

Class binds the data and associated functions together into a single type which is Encapsulation.

3.7 Functions in a Class

3.7.1 Inline Functions: - Inline function definition should be placed above all the functions that call it.Advantages:- The inline functions are designed to speed up programs. Inline functions run a little faster than the normal functions as function calling – overheads are saved.Drawback: There is a memory penalty [ i.e if 10 times an inline function is called, there will be 10 copies of the function inserted into the code]Difference between the normal functions and inline functions:The coding of normal functions and inline functions is similar except that inline functions definitions start with the keyword inline.The difference between normal function and inline function is in compilation process.

Eg: - inline void max(int a, int b){ cout<<(a>b:a:b);}

The inline function max( )would not be called during execution rather the code will be inserted into main( )and then compiled.

58

Page 44: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

3.7.2 Overheads Involved In Calling A Function:-

After writing the program, it is first compiled to get an executable code, which consists of a set of machine language instructions.When this executable code is executed, the operating system loads these instructions into the computer memory, so that each instruction is stored in a specific memory location. After loading the executable program in the computer memory, these instructions are executed step by step.Steps in executing a function:

(1) Save the address of instruction immediately following the function call, and loads the function being called into the memory.

(2) Copy argument values in Stack.( a memory area)(3) Jump to the memory location of the called function(4) Execute the instructions in the function(5) Store the returned value (of the function)(6) Jump back to earlier saved address of instructions that was saved just before executing the

called function. With inline functions, the compiler does not have to jump to another location to

execute the function, and then jump back as the code of the called function is already available to the calling program.

3.7.3 Points to note for making a function inlineA function can be inlined if –

- it is very small.- it is not recursive- it does not contain static variables- it does not contain any loop- it does not contain return statement.

3.7.4 The inlining does not work for following situations(1) For functions that return values and are having a loop or a switch or a goto(2) for functions not returning values , if a return statement exists(3) If functions contain static variable(s)

(4) If the function is recursive.

Member function of a class, if defined with in the class definition are inlined by default (Only small functions should be defined with in the class definition)

Member functions defined outside the class definition can be made explicitly inline by placing the keyword inline before their definition.

3.7.5 Constant Member Functions

If a member function of a class does not alter any data in the class, then, this member function may be declared as a constant member function using the keyword const

Eg:

int maxi( int , int ) const;

void prn( ) const;

NOTE:-

59

Page 45: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

The qualifier const appears both in member function declarations and definitions.Once a member function declared as const, it cannot alter the data values of the class. The compiler will generate an error message if such functions try to alter the data values.

3.8 Scope Resolution Operator (::) (1) :: - is used to distinguish between class member names and other names.

Eg: int X, Y;class A { int X;float Y;public : void readm( ) const; ………. };

(2) If a class defines a member with the same name as that of a global variable, then the global variable becomes hidden. To access the global variable, use the scope resolution operator :: before the global variable name.Eg: A::X refers to X of Class Aand :: X refers to the global variable.

NOTE:-File scope items (Global items in a file) are normally hidden when we use the same name for an item with in a block ( class block, function block, or any other block) , but we can uncover them with the :: operator.

3.9 Using ObjectsDeclaration of a class does not allocate any memory for storing data. Objects have to be declared for memory allocation. When an object is declared memory is allocated for storing of all data members.

The declaration of an object is similar to that of a variable of any basic type.

The syntax of defining the object is :

Class_name object_name;

Eg: student A1, A2, A3 ;Will create 3 objects A1, A2 and A3 of studentWhen we define a class, it does not create objects of that class, rather it only specifies what type of information the objects of this class type will be containing.Once a class has been defined, its objects (the variables of this class type, its instances) can be created (like any other variable), using the class name as type specifier. (i.e.) class_name objectlist(comma separated);Eg: class item { private:

int itemno; float price; public :

void getdata(int i, float j) { itemno = i;

60

Page 46: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

price=j; }

void putdata() { cout<<“Items ”<<itemno; cout<<“\nPrice”<<price; }};

item S1, S2;void main(){S1.getdata(1001,17.50);S2.getdata(1002,29.50);…..}

In the function main( ) the statements: S1.getdata(1001, 17.50); and S2.getdata(1002, 29.50);invokes the member function getdata( )for objects S1 and S2 respectively with data 1001 & 17.50 for S1 and 1002 & 29.50 for S2.

After these statements, the getdata( ) function (for S1&S2) stores given values in the object S1&S2.

NOTE:- Memory space for objects is allocated when they are declared and not when the class is

defined. When we call a member function , it uses the data members of the particular object used to

invoke the member function. Member functions are created and stored in the memory space only once when the class is

defined and this memory space (containing member functions) can be read by any of the objects of that class.

The memory space is allocated for objects, data members only when the objects are declared because the data members hold different values for different objects. No separate space is allocated for member functions when the objects are created.[ since all the objects belonging to a class use the same member functions, there is no point of allocating separate space for member functions for each object.

3.10 Array of Objects

An array having class type elements is known as array of objects. An array of objects is declared after the class definition is over and it is defined in the same way as any other type of array is defined.Syntax : class_name object_name[size];Eg: Item order[10]; - array order contains 10 objects of item type

61

Page 47: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

To access data member itemno of 3rd object in the array use :Order[2].itemno

Similarly to invoke putdata( ) for 7th object in the array use: Order[6].putdata( );

3.11 Objects as Function Arguments

An object may also be passed to a function as an argument. An object can be passed both ways.1. By value: - When an object is passed by value, the function creates its own copy of the object

and works with its own copy. Therefore any changes made to the object inside the function do not affect the original object.

2. By Reference: - When an object is passed by reference, its memory address is passed to the function so that the called function works directly on the original object used I the function call. Thus any changes made to the object inside the function are reflected in the original object as the function is making changes in the original object itself.

3.12 Functions Returning ObjectsObjects can not only be passed to functions but functions can also return an object.

#include <iostream.h> class Distance{int feet,inches;public :void getdata(int f,int i){feet=f; inches=i;}void printit(void){cout<<feet<<“feet”<<inches<<“inches”<<“\n”;}

Order[1]

Order[2]

Order[9]

Order[0]62

Page 48: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Distance sum(Distance d2);};

Distance Distance::sum(Distance d2){Distance d3;d3.feet=feet+d2.feet+(inches+d2.inches)/12;d3.inches=(inches+d2.inches)%12;return(d3);}

void main(){Distance length1,length2,total;length1.getdata(17,6);length2.getdata(13,8);total=length1.sum(length2);cout<<“length1:”;length1.printit();cout<<“length2:”;length2.printit();cout<<“Total Length:”;total.printit();}

Here the function sum ( ) returns an object of Distance type.

3.13 Static Class MembersThere may be static data members and static member functions in a class.

STATIC DATA MEMBER: It is like a global variable for its class (i.e) it is globally available for all the objects of that class type. It is usually maintained to store values common to the entire class. It is used to keep track of its number of existing objects.

NOTE:-Difference between static data member and ordinary data members of a class : -

(1) There is only one copy of static data member maintained for the entire class which is shared by all the objects of that class.

(2) Static data member is visible only within the class, its lifetime (the time for which it remains in the memory) is the entire program.

3.13.1 For Making A Data Member Static:-

1. Declaration within the class definition: - declaration of a static data member within the class definition is similar to any other variable declaration except that it starts with the keyword static.

Eg: class x { static int count;

…..};

2. Definition outside the class definition: - The definition of above declared static member count outside the class will be : int X :: count;

63

Page 49: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

A static data member can be given an initial value at time of its definition.Eg: int X::count =10;

REMEMBER:-1. A Static data member must be defined outside the class definition as these are stored separately rather than as a part of an object [ static member is not a part of object of a class ]2. Since a static data member are associated with the class itself rather than with any object, they are also known as class variables.3. We cannot have a static data member inside a local class i.e. in a class that has been defined inside a function.

3.13.2 Static Member FunctionA member function that accesses only the static members of a class is declared as static by using keyword static before the function declaration in the class definitionEg:

class X{ static int count; static void show() { cout<< count<<“\n”; }};

int X::count ;

Difference between Static Member Functions and Other Member Functions:-(1) A static member function can access only static members (functions or variables) of the same

class.(2) A static member function is invoked by using the class name instead of its objects as per the

syntax : Class_name:: function_nameEg: X::Show();

SOLVED PROBLEMS

Object 1 Object 2 Object 3

Static member being shared by all objects

64

Page 50: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

1. Which data member of the class is accessible to outside world?Ans. Public Data members

2. When will you make a function inline? Why?Ans. A function is made inline when it is very small and does not return any value.Also when it does not contain any loop and static variables.

3. What is the significance of access labels in a class?Ans. A class provides 3 access labels namely : private, protected and public.A member declared as private or protected remain hidden from outside world and it can only be accessed by the member function of the class.A member declared as public is made available to the outside world. It can be accessed by any function, any expression in the program but by using an object of the same class.Access labels enforce data hiding and abstraction OOP concepts.

4. What are the advantages and disadvantages of inline functions?Ans. ADVANTAGE:- It saves the time of the function call as the function is not invoked, rather its code is replaced in the program.DISADVANTAGE:- With more function calls memory is wasted because whenever the function is invoked the same function code is inserted into the program.

5. How is working of a member function different from a friend function and a non-member function?Ans. 1. Member and friend functions can both access the public and private members of the class while non member functions can access only the public members of the class.2. Member functions are defined within the class scope that is they are not visible outside the scope of a class. Friend and non member functions are also visible outside the scope of the class.

6. What is static data member?Ans. Static data members are initialized to Zero when the first object of its class is created. Only one copy of that member is created for the entire class and is shared by all the objects for that class, no matter how many objects are created.

7. What do you understand about a member function? How does a member function differ from an ordinary function?Ans. Member functions are functions defined within a class that act on the data members in the class. The use of member functions distinguishes a class from a struct. Where as an ordinary function can call in any function without an object, the member function can call only by using its object. The member function is a member of its own class but an ordinary function is not.

8. What is a scope resolution operator? How is it useful for defining the data member and member function of a class?Ans. :: is used where a global variable exists with the same name as a local variable.It is also used in a Class when the member functions are declared outside the class. To use the member functions outside the class the scope resolution operator is used.

9. What will be the output of the following program segment: class N{int a;

65

Page 51: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

float b;public:

void initval(){a=b=0;}

void getdata(int a1, int b1){a=a1;b=b1;}

void dispdata(){cout<<”\na=”<<a;cout<<”\nb=”<<b;}

};

void main(){N ob1,ob2;ob1.initval();ob2.initval();ob1.getdata(50,26.50);ob1.dispdata();ob2.dispdata();}Ans.a=50b=26.50a=0b=0

10. Define a class student with the following specifications:-private members of the class student:admno integersname 20 charactersEnglish,math,science floatTotal floatCtotal() A function to calculate English+math+science with float return typepublic members of the class student:Takedata() function to accept values for admno, sname, English,math,science and invoke ctotal() to calculate total.Showdata() function to display all the data members on the screen.Ans. class student

{

66

Page 52: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

int admno;char sname[20];float English,math,science;float Total;float Ctotal(){return(English+math+science);}public :void Takedata(){cout<<”\n Enter admission number”;cin>> admno;cout<< “\nEnter name:”gets(sname);cout<<”\n Enter English Marks”;cin>> English;cout<< “\nEnter Maths marks:”cin>> math;cout<< “\nEnter science marks:”cin>> science;Total=Ctotal();}void Showdata(){cout<<”\nAdmission number :”<<admno;cout<<”\nName :”<<sname;cout<<”\nEnglish marks:”<<English;cout<<”\nMaths marks:”<<math;cout<<”\nScience marks:”<<science;cout<<”\nTotal marks:”<<Total;}};

11. Define a class worker with the following specifications:-private members of the class worker:wno integerwname 25 charactershrwrk,wgrate float(hour worked and wage rate per hour)Totwage float(hrwrk*wgrate)calcwg() A function to find hrwrk * wgrate with float return typepublic members of the class worker:in_data() function to accept values for wno,wname, hrwrk,wgrate and invoke calcwg() to calculate total pay.out_data() function to display all the data members on the screen. You should give definitions of functions.Ans. class worker

{int wno;char wname[25];float hrwrk,wgrate,Totwage;float calcwg(){

67

Page 53: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

return(hrwrk*wgrate)}public :void in_data();void out_data();};

void worker::in_data(){cout<<”\n Enter Worker number”;cin>> wno;cout<< “\nEnter worker name:”cin>> wname;cout<<”\n Enter hours worked”;cin>> hrwrk;cout<< “\nEnter wage rate per hour:”cin>> wgrate;Totwage=calcwg();}

void worker::out_data(){cout<<”\nworker Number :”<<wno;cout<<”\nworker Name :”<<wname;cout<<”\nHours worked :”<<hrwrk;cout<<”\nwage rate per hour :”<<wgrate;cout<<”\nTotal wage:”<<Totwage;}

POINTS TO REMEMBER

1. A class is a way to bind data and associated functions together. But a structure provides a way to group data elements.2. Classes are needed to represent real world entities that not only have data type properties (their characteristics) but also associated operations (their behavior).3 If we declare the members of a class without specifying the access label the members are by default private.

The private data of a class can be accessed only through the member functions of that class. The public data member can be accessed by the non-member functions through the objects of

that class4. Only small functions are usually defined inside the class definition. A function defined inside a class is an inline function5. Inline property is a hint to the compiler to insert the code for the body of the function ( declared inline) at the place where it is called, there by saving the overheads (i.e) time spent in loading and unloading of the called function) of a function call.6. Declaration of a class does not allocate any memory for storing data. Objects have to be declared for memory allocation. When an object is declared memory is allocated for storing of all data members.7.

Memory space for objects is allocated when they are declared and not when the class is defined.

68

Page 54: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

When we call a member function , it uses the data members of the particular object used to invoke the member function.

Member functions are created and stored in the memory space only once when the class is defined and this memory space (containing member functions) can be read by any of the objects of that class.

The memory space is allocated for objects, data members only when the objects are declared because the data members hold different values for different objects. No separate space is allocated for member functions when the objects are created.[ since all the objects belonging to a class use the same member functions, there is no point of allocating separate space for member functions for each object.

8. An object may also be passed to a function as an argument. An object can be passed both ways.1. By value: - When an object is passed by value, the function creates its own copy of the object and works with its own copy. Therefore any changes made to the object inside the function do not affect the original object.2. By Reference :- When an object is passed by reference, its memory address is passed to the function so that the called function works directly on the original object used in the function call. Thus any changes made to the object inside the function are reflected in the original object as the function is making changes in the original object itself.

9. i. A Static data member must be defined outside the class definition as these are stored separately rather than as a part of an object [Static member is not a part of object of a class] ii. Since a static data member are associated with the class itself rather than with any object, they are also known as class variables.10. A member function that accesses only the static members of a class is declared as static by using keyword static before the function declaration in the class definition

69

Page 55: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

CHAPTER 5CONSTRUCTOR AND DESTRUCTOR

FOREVIEW

POINTS OF FOCUS

SOLVED PROBLEMS

POINTS TO REMEMBER

70

Page 56: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

FOREVIEW

1.Constructor: A member function with the same name as its class is called Constructor and it is used to initialize the objects of that class type with a legal initial value.

2. Default constructor: A constructor that accepts no parameter is called the default constructor. It simply allocates memory to data members of objects.

3. Parameterized constructor : A constructor that takes arguments are called parameterized constructors. The parameterized constructors allow to initialize the various data elements of different objects with different values when they are created.

4. Copy constructor : A Copy constructor is a constructor that defines and initializes an object with another object and it takes of the form classname(classname &). 5. Constructor Overloading : Constructor overloading refers to a class having multiple constructor definitions,each having a different signature.

6. Destructor :A destructor is also a member function whose name is the same as the class name but is preceded by tilde(~).A destructor is used to destroy the objects that have been created by a constructor.

71

Page 57: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS OF FOCUS

1 CONSTRUCTOR

A member function with the same name as its class is called Constructor and it is used to initialize the objects of that class type with a legal initial value.

1.1 Declaration and Definitionclass x { int i; public: int j,k; x() //constructor { i=j=k=0; } };

OR class x { int i; Public: int j,k; x(); } x::x() //constructor defined outside class { i=j=k=0; }1.2 Special characteristics of constructors

These are called automatically when the objects are created. .All objects of the class having a constructor are initialized before some use. These should be declared in the public section for availability to all the functions . Return type(not even void) cannot be specified for constructors . .These cannot be inherited,,but a derived class can call the base class constructor. These cannot be static. Default and copy constructors are generated by the compiler wherever required.generated constructors are public. These can have default arguments The address of a constructor cannot be taken. .An object of a class with a constructor cannot be used as a member of a union. A constructor can call member functions of its class.

Note:After declairing a constructor ,the initialization of the class objects becomes compulsory.

72

Page 58: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

2 Default Constructor A constructor that accepts no parameter is called the default constructor.It simply allocates memory to data members of objects.Eg:

class Travelplan{

int no_of_travellers; int no_of_buses; char place[40];

public: travelplan() ---------→default constructor { no_of_travellers=50; no_of_buses=2; strcpy(place,”Agra”); }};Note: If a class has no explicit constructor defined ,the compiler will supply a default constructor.Declaring a constructor with arguments hides the default constructor.A constructor with default argument is equivalent to a default constructor.

3 Parameterized Constructors

A constructor that takes arguments are called parameterized constructors..The parameterized constructors allow to initialize the various data elements of different objects with different values when they are created.

Eg:class xyz{

float a; public: int b; char c; xyz(float x,int y,char ch)-----parameterized constructor { a=x; b=y; c=ch; }

……………………//remaining members;};

Note:Once we have declared a parameterized constructor,we must give initial values as arguments.If we do not do so, the compiler reports an error.

Eg: xyz obj; //not valid For passing initial values while creating an object ,we can select any one of the two ways: i) call the constructor implicitly

eg:xyz obj(10.5,50,’A’);

ii) call the constructor explicitly

73

Page 59: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

eg:xyz obj = xyz(10.5,50,’A’);

A temporary instance or temporary object is created when we make an explicit call.A temporary object resides in the memory as long as the object is referenced and after that it dies. 4 Copy constructor

A Copy constructor is a constructor that defines and initializes an object with another object and it takes of the form classname(classname &). A copy constructor may be called in the following situations:

1. When an object is defined and initialized with other object of the same class.Eg:

sample s1;sample s2=s1;

2. When we pass an object by value.3. In case a function returns an object.

class fun{ float x,y;

public: fun(float a,float b) { x=a; y=b; }

fun(fun &f) { cout<<”\ncopy constructor at work\n”; x=f.x; y=f.y; }

void display(void) { cout<<x<<””<<y<<endl; }

};Note:-Initialization using a copy constructor is called copy initialization and is the task of the overloaded(=)assignment operator.A copy constructor takes references to an object of the same class as itself as a parameter.

4. Constructor OverloadingConstructor overloading refers to a class having multiple constructor definitions,each having a different signature. A constructor overloading is similar to function overloading as it can also be overloaded for various combinations of parameter types. The only difference is that the overloaded function can return a value while the overloaded constructor cannot return a value.

Eg:class x{

private:

74

Page 60: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

float a,b;public:

x() {

a=0,b=0; }

x(float r){

a=r;b=10.0;

}x(float s1,float s2){a=s1;b=s2;}};

5. Destructors A destructor is also a member function whose name is the same as the class name but is preceded by tilde(~).A destructor is used to destroy the objects that have been created by a constructor.

Note:Destructors should be declared in a program to release memory space for future utilization.

5.1 Declaration and definitionThe syntax for declaring the constructor is: ~ name_of _the_class() { .. } Eg:

class x{

private:float a,b;

public: x() {

a=0,b=0; }

x(float s1,float s2){a=s1;b=s2;}~x( ); // Destructor };

5.2 Special Characteristics of Destructors

1.Destructors are invoked automatically when the objects are destroyed.2.These de_initialize each object before the objects goes out of scope.

75

Page 61: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

3.No arguments and return type(even void) are permitted with destructors.4.Destructors follow the usual access rules as other member functions.5.These cannot be inherited.6.Static destructors are not allowed.7.Address of a destructor cannot be taken.8.A destructor can call member function of its class.9.An object of a clsss having a destructor cannot be a member of a union.

SOLVED PROBLEMS

1.Differentiate between constructor and destructor function in context of classes and objects using C++

Ans :

Constructor :

1. Name of the constructor functions is same as the name of the class.

2. No return type required for constructor functions.

3. Constructor functions are called automatically at the time of creation of the object.

4. Constructor can be overloaded.

5. constructor functions are defined in public.

Destructor :

1. Name of the destructor is same as the name of the class preceded by.

2. No return type required for destructor function.

3. Destructor functions are called automatically when the scope of the object gets over.

4. Destructor can not be overloaded.

5. Destructor function is defined in public.

2. What is a default constructor? How is it different from a destructor?

Ans. A constructor that accepts no parameters is called the default constructor.

A destructor is also a member function whose is name is the same as the class name but is preceded by tilde(~). A destructor destroys the objects that have been created by a constructor. It destroys the values of the objects being destroyed.

(2 marks question each part carrying 1 mark)1. Answer the questions (i) and (ii) after going through the following class :

class Maths

{

char chapter [20];

76

Page 62: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

int Marks [20];

public:

Maths ( )

{

strcpy (chapter, ``geometery’’);

Marks =10;

cout <<``chapter Intialised ”;

}

~Maths ( ) //member Function 2

{

cout<<`` chapter over ” ;

}

};(i) Name the specific features of class shown by member function1 and member function 2 in above example?

Ans : FUNTION 1: constructor OR default constructor

(ii)How would Member Function 1 and Member Function 2 get get executed?

Ans. Function 1 is executed or invoked automatically when an object of class Maths is created.

Function 2 is invoked automatically when the scope of an object of class Maths comes to an end.

OR

Example :

{

Maths S1;

…..

} //constructor is invoked

} //Destructor is invoked 2.Answer the questions(i) and(ii) after going through the following class:class exam{

int marks;char subject[20];Public:Exam() //function1

77

Page 63: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

{Marks=0;Strcpy(subject,”computer”);

}Exam (char s[]) //function2{Marks=0;strcpy(subject,”s”);}Exam(int m) //function3{Marks=m;strcpy(subject,”computer”);}Exam (char s[],int m) //function4{Marks=m;strcpy(subject,s);}};

i)Which statement in c++ that would execute function3 and function 4 of class exam.ii)Which feature of object oriented programming is demonstrated using function 1,function 2,function 3 and function 4 in the above class exam?

ANS: (i)exam E(“Computer science”,40) (ii)Constructor overloading3.Answer the questions(i) and (ii),after going through the following class:class test {

char paper[20];int marks;public:

test() //function1 { strcpy(paper,”computer”); marks=0; }

test (char p[]) //function 2{ strcpy(paper,p);

marks=0;}test(int M) //function 3{strcpy(paper,”computer”);marks=M;}

test (char p[],int M) //function 4{

strcpy(paper, P);marks=M;}

78

Page 64: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

};

(i)Which feature of object oriented programming is demonstrated using function1,function2,function3 and function4 in the above class test?(ii)Write statements in c++ that would execute function 4 in the above class test? Ans: (i) Constructor overloading (ii) test T(“IT”,98);

Previously asked problems1.class readbook{

Public:Readbook() //function-1{cout<<”open the book”<<endl;}void readchapter() //function-2 {cout<<”reading chapter-1”<<endl;}~readbook() //function-3{cout<<”close the book”}

};i)In object oriented programming,what is function-1reffered as and when does it get invoked?ii) In object oriented programming,what is function -3 reffered as and when does it get invoked? Ans: 1. Constructor, it is automatically invoked when an object is created 2. Destructor , it is automatically invoked when an object goes out of scope 2.Find the syntax errors if any.

class abc{int x=10;Float y;abc(){Y=5;}~(){}};void main(){abc a1,a2;}Ans: class abc

{int x;float y;public:abc(){y=5;x=10;}~abc(){}

};void main(){

79

Page 65: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

abc a1,a2;}

3.Consider the class:

class semester

{

int pages;

public:

semester() //function A

{

pages=60;

cout<<”semester contains pages:”;

}

void books() //function B

{

cout<<”/nbooks in the semester”;

}

semester (int n) //function C

{

pages=n;

cout<<”/n semester contains pages”;

}

~semester() //Function D

{

cout<<”end of semester”;

} };

(i) In OOPS,what does function D refers to as and when does it get invoked?

(ii) In OOPS,which concept is illustrated by the function A and function C together? Write the commands to call these functions.

Ans: i) Function D is invoked automatically when the scope of an object of class semester comes to an end.

ii)Constructor Overloading , Semester S; Semester S1(10);

80

Page 66: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Previously asked Theory questions1.Differentiate between a constructor and a destructor function.2.What do you understand by constructor and destructor functions used in classes ? How are these functions different from other member functions?3.What is copy constructor? What do you mean by constructor overloading?4.What is a constructor? What is its need? Explain with example.5.Why is a destructor function required in a class? Illustrate with the help of an example.6.What is the importance of constructor in object oriented programming? Explain with the help of an example.7.List some special characteristics of constructor function and destructor function.8.What is the order of a constructor and destructor invocation ?Explain giving a suitable example.9.What do you mean by copy constructor? Explain your answer in light of example

POINTS TO REMEMBER

Constructor: A member function with the same name as its class is called Constructor and it is used to initialize the objects of that class type with a legal initial value. Default constructor: A constructor that accepts no parameter is called the default constructor.It simply allocates memory to data members of objects.

Parameterized constructor:

A constructor that takes arguments are called parameterized constructors.Copy constructor: It is of the form classname(classname &)and used for the initialization of an object from another object of same type.Constructor Overloading: A constructor overloading is similar to function overloading as it can also be overloaded for various combinations of parameter types.The only difference is that the overloaded function can return a value while the overloaded constructor cannot return a value.

Destructor:

A destructor is used to destroy the objects that have been created by a constructor.

*****************************

81

Page 67: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

CHAPTER 6

INHERITANCE

FOREVIEW

POINTS OF FOCUS

SOLVED PROBLEMS

POINTS TO REMEMBER

82

Page 68: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

FORE VIEW

Inheritance is a technique which is use to acquire the properties and the working of a class in the newly created class.

Inheritance provides reusability. Inheritance provides extendibility. Inheritance facilitates step by step creation of project. In private visibility mode public and protected member of base class become the private

member of derived class. In protected visibility mode public and protected member of base class become the protected

member of derived class. In public visibility mode protected member of base class become protected member of

derived class and the public member of the base class become the public member of derived class.

Single inheritance have only one base and one derived class. Multilevel inheritance have chain of base and derived classes. Multiple inheritance have only one derived class and two or more than two base classes. Private member of base class is also inherited but they are not accessible directly from the

member of the derived class.

83

Page 69: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS OF FOCUS

CONCEPT :Inheritance (Extending Classes ): Concept Of Inheritance, Base Class, Derived Class, Defining Derived Classes, Single Level Inheritance, Multilevel Inheritance And Multiple Inheritance, Privately Derived Class , Publicly Derived And Protected Derived Class, Accessibility Of Members From Objects And Within Derived Class(es).

INHERITANCEInheritance is a way or technique or method which is use to acquire the properties and methods of old class in to newly created class. Inheritance is the process by which one object can acquire the properties and functionality of another object. This is important because it supports the concept of classification. If you think about it, most knowledge is made manageable by hierarchical classifications. Without the use of classifications, each object would have to define explicitly all of its characteristics. However, through the use of classifications, an object need only define those qualities that make it unique within its class. It is the inheritance mechanism that makes it possible for one object to be a specific instance of a more general case. As you will see, inheritance is an important aspect of object-oriented programming.

For example, a Red Delicious apple is part of the classification apple, which in turn is part of the fruit class, which is under the larger class food.

BASE CLASS : The class which is already available and which properties and functionality we want to use in new class is called a base class. For example food is a base class for fruit. It is also called parent class or super class.

DERIVED CLASS : The class which is created newly and which wanted to use or inherit the properties and functionality of any old class is called a derived class. For example fruit is a derived class of food. It is also called child class or sub class.

DEFINING DERIVE CLASS :

When a class inherits another, the members of the base class become members of thederived class. Class inheritance uses this general form:

class derived-class-name : access-mode base-class-name {// body of class

};

ACCESS MODE :Access mode is also called visibility mode or inheritance mode. They describe that which data member of base class should be inherited and in which part (private or public or protected ) they will go in derived class. There are 3 type of access mode :

1. Private2. Protected3. Public

84

Page 70: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

PRIVATE ACCESS MODE :

Private data member of base class are inheritable but they are not directly accessible from the member of the derived class. When we find out the size of the derive class object then its size includes the private member of the base class also. In inheritance if we use private access mode then all the public member of base class and the protected member of the base class become the private member of derived class.We can understand it by following figure :

Base class Derived Class

PROTECTED ACCESS MODE :

Private data member of base class are inheritable but they are not directly accessible from the member of the derived class. When we find out the size of the derive class object then its size includes the private member of the base class also. In inheritance if we use protected access mode then all the public member of base class and the protected member of the base class become the protected member of derived class.We can understand it by following figure :

Base class Derived Class

PUBLIC ACCESS MODE :

Private data member of base class are inheritable but they are not directly accessible from the member of the derived class. When we find out the size of the derive class object then its size includes the private member of the base class also. In inheritance if we use public access mode then all the public member of base class become the public member of derived and all the protected member of the base class become the protected member of derived class.We can understand it by following figure :

Private

Protected

Public

Private

Protected

Public

Private

Protected

Public

Private

Protected

Public

85

Page 71: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Base class Derived Class

We can summarize the different access mode according to who can access them in the following way

Access - mode

Public protected

Private access mode

Become Private

Become Private

Protected access mode

Become Protected

Become Protected

Public access mode

Become Public

Become Protected

TYPE OF INHERITANCE :There are 5 type of inheritance which are as below :

1. Single level inheritance2. Multilevel inheritance3. Multiple inheritance4. Hierarchical inheritance5. Hybrid inheritance

SINGLE LEVEL INHERITANCEWhen there is only one base class and only one derived class then it is called single level heritance. We can represent it by using following diagram :

Private

Protected

Public

Private

Protected

Public

Base Class

Derived Class

86

Page 72: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Example :

class A {int a;public:void geta();void showa();

}class B : public A{

int b;public:void getb();void showb();

}

MULTILEVEL INHERITANCEWhen one class is derived from other class and this other class is also derived from any other class means when there is a chain of inheritance then it is called multilevel inheritance. We can represent it by using following diagram

Example :

class A {int a;public:void geta();void showa();

}class B : public A{

Base Class

Derived Class

Derived Class

87

Page 73: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

int b;public:void getb();void showb();

}class C : public B{

int c;public:void getc();void showc();

}

MULTIPLE INHERITANCEWhen one Derive class is derived from two or more than two base classes then it is called multiple inheritance. We can represent it by using following diagram

Example :

class A {int a;public:void geta();void showa();

}class B {

int b;public:void getb();void showb();

}class C : public A, public B{

int c;public:void getc();void showc();

}

Base1 Class

Derived Class

Base2 Class

88

Page 74: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINT TO BE REMEMBER:

Inheritance is a technique which is use to acquire the properties and the working of a class in the newly created class.

Inheritance provides reusability. Inheritance provides extendibility. Inheritance facilitates step by step creation of project. In private visibility mode public and protected member of base class become the private

member of derived class. In protected visibility mode public and protected member of base class become the protected

member of derived class. In public visibility mode protected member of base class become protected member of

derived class and the public member of the base class become the public member of derived class.

Single inheritance has only one base and one derived class. Multilevel inheritance has chain of base and derived classes. Multiple inheritance have only one derived class and two or more than two base classes. Private member of base class is also inherited but they are not accessible directly from the

member of the derived class.

QUESTIONS :1. Identify the type of inheritance in below program.

class school { int a;

protected : int b, c;

public : void input(int); void output(); };class dept : protected school { int x, y;

protected : void in(int, int);

public : void out( ) ; };class teacher : public dept { int p; void display(void); public : void enter();

89

Page 75: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

};

Answer : Multilevel Inheritance

2. . Read the following program carefully and give the answer below it : class A { void anyval (); protected : int x, y; void procval (); public : void getvalA(); void putvalA(); };class B { int a, b; protected : int c , d; void getvalB (); public : void putvalB(); };class C : public A, public B { int p; protected : int q; void getval (); public : void showval (); };

(1) Identify the type of inheritance in below program.Answer : Multiple Inheritance

(2) Which member(s) are accessible from the object of class B?Answer : (i) void getvalB()

(ii) void getvalA();(iii) void putvalA();

(3) Which member(s) are accessible from the function of class B?Answer : (i) int a

(ii) int b(iii) int c(iv) int d(v) void getvalB()(vi) void putvalB()(vii) void getvalA();

90

Page 76: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

(viii) void putvalA();(ix) int x(x) int y

(4) if the class B inherite class A in private mode then which member(s) are accessible by object of class C?Answer : (i) void showval ();

(ii) void putvalB();

3. Read the following program carefully and give the answer below it :

class TableTennisPlayer{private: enum { LIM = 20}; char firstname[LIM];protected: char lastname[LIM]; bool hasTable; bool HasTable() const { return hasTable; } ; void ResetTable(bool v) { hasTable = v; };public: TableTennisPlayer (const char * fn = "none", const char * ln = "none", bool ht = false); void Name() const; };class RatedPlayer : public TableTennisPlayer{private: unsigned int rating;public: RatedPlayer (unsigned int r = 0, const char * fn = "none", const char * ln = "none", bool ht = false); RatedPlayer(unsigned int r, const TableTennisPlayer & tp); unsigned int Rating() { return rating; } void ResetRating (unsigned int r) { rating = r;}};

(1) Identify the type of Inheritance in above program :Answer : Single Inheritance

(2) Which member function(s) are accessible by the object of ratedPlayer class ?Answer : (i) RatedPlayer (unsigned int r = 0, const char * fn = "none", const char * ln = "none", bool ht = false);

(ii) RatedPlayer(unsigned int r, const TableTennisPlayer & tp);

91

Page 77: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

(iii) unsigned int Rating() { return rating; }(iv) void ResetRating (unsigned int r) { rating = r;}(v) TableTennisPlayer (const char * fn = "none",

const char * ln = "none", bool ht = false);(vi) void Name() const;

(3) Which member function(s) are accessible by the function of ratedPlayer class ?Answer : (i) RatedPlayer (unsigned int r = 0, const char * fn = "none", const char * ln = "none", bool ht = false);

(ii) RatedPlayer(unsigned int r, const TableTennisPlayer & tp);(iii) unsigned int Rating() { return rating; }(iv) void ResetRating (unsigned int r) { rating = r;}(v) TableTennisPlayer (const char * fn = "none",

const char * ln = "none", bool ht = false);(vi) void Name() const;(vii) bool HasTable() const { return hasTable; } ;(viii) void ResetTable(bool v) { hasTable = v; };

(4) Which member(s) are accessible by the function of ratedPlayer class ?Answer : (i) RatedPlayer (unsigned int r = 0, const char * fn = "none", const char * ln = "none", bool ht = false);

(ii) RatedPlayer(unsigned int r, const TableTennisPlayer & tp);(iii) unsigned int Rating() { return rating; }(iv) void ResetRating (unsigned int r) { rating = r;}(v) TableTennisPlayer (const char * fn = "none",

const char * ln = "none", bool ht = false);(vi) void Name() const;(vii) bool HasTable() const { return hasTable; } ;(viii) void ResetTable(bool v) { hasTable = v; };(ix) unsigned int rating; (x) char lastname[LIM];(xi) bool hasTable;

4. Read the following program carefully and give the answer below it :

class Vehicle { protected : void setweight(int wt);

public: Vehicle(); Vehicle(int wt); int getweight();

private: int weight; };

92

Page 78: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

class Land: public Vehicle {

protected: int getspeed();

public: Land(); Land(int wt, int sp); void setspeed(int sp);

private: int speed; };class Auto: public Land { public: Auto(); Auto(int wt, int sp, char const *nm); Auto(Auto const &other); ~Auto(); void setname(char const *nm);

private: char const *name; };

(1) What type of inheritance is depicted by the above example?

Answer : Multilevel Inheritance

(2) Identify the member function(s) that cannot be called directly accessible from the objects of class Land.

Answer : (a) void setweight(int wt); (b)int getspeed();

(3) Write name of all the member(s) accessible from member functions of class Auto.

Answer : (a) char const *name;(b) Auto();(c) Auto(int wt, int sp, char const *nm);(d) Auto(Auto const &other);(e) ~Auto();(f)Land()(g) Land(int wt,int sp)(h) void setspeed(int sp)(i) int getspeed()(j) void setweight(int wt)(k) int getweight(int wt)(l) void setname(char const *nm);

93

Page 79: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

(4) If class Land is privately derived from the class Vehicle , then, name the member(s) which that could be accessed from the member function of class Auto.

Answer : (a) char const *name;(b) Auto();(c) Auto(int wt, int sp, char const *nm);(d) Auto(Auto const &other);(e) ~Auto();(f)Land()(g) Land(int wt,int sp)(h) void setspeed(int sp)(i) int getspeed()(j) void setname(char const *nm);

94

Page 80: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

CHAPTER 7

DATA FILE HANDLING IN C++

FORE VIEW

POINTS OF FOCUS

SOLVED EXAMPLES

POINTS TO REMEMBER

95

Page 81: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

FOREVIEW

1. File: In simple words, a file is a collection of useful data or information related to an entity, object or a system.

2. Stream: It is a sequence of bytes.

3. Text file: Stores information text by text in ASCII where each line of text is terminated with a special character known as EOL.

4. Binary file: Contains information in the same format in which the information is held in memory.

5. get(): It is a byte oriented function. It will read a byte of data. It reads a single character from the associated stream and puts that value in a character variable.

6. put():It is also a byte oriented function. It will read a byte of data. It reads a single character from the associated stream and puts that value in a character variable.

7.getline(): It reads a line of text and puts them in an array. Example: ifstream FILE(“STORY.TXT”); char LINE[80];while (FILE.getline (LINE,80)). (Refer to Solved examples at the end.)

8. seekg():While reading a file, it positions the file pointer n bytes(size) away from the reference, where reference may be beginning(ios::beg), end(ios::end) or current location(ios::cur) in the file.

9. seekp():While writing, it positions the file pointer n bytes away from the reference, where reference may be beginning(ios::beg), end(ios::end) or current location(ios::cur) in the file.

10. tellg( ): Returns the current position of file pointer while reading a file.

11. tellp( ):Returns the current position of file pointer while writing in a file.

12. eof( ): Determines the end of file by returning true for end of file otherwise false.

13. ifstream:It is a stream class derived from istream class to associate a file with an input buffer so that the file can be read from.

14. ofstream:It is a stream class derived from ostream class to associate a file with an output buffer so that the file can be written onto.

15. fstream: It is a stream class derived from iostream class to associate a file with an buffer so that the file can be read from, or written onto.

96

Page 82: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS OF FOCUS

1. Concept of file:

1.1 What is File?In simple words, a file is a collection of useful data or information related to an entity, object, or a system.

For example, for a student, class work copy of English is a file, as it contains information in the form of chapter’s questions, answers, of the subject English(Entity).

Similarly, a class teacher carries a file known as attendance register containing information of his/her students. In terms of computers and with reference to C++, a file, at its lowest level, is considered as a sequence of bytes. Here, the sequence of bytes is also known as bytes stream.

We shall take up the two types of files in the chapter ahead to make their concept more clear and applicable in programming.

1.2 Concept of File Handling means:

Opening existing file.

Creating new file.

Writing data/records in a file.

Reading data/records from existing file.

Search records.

Modifying records.

Deleting records and handling file errors.

We shall take up all above tasks in the topics ahead.

1.3 Types of Files:Basically there are two types of files that we shall work with in C++.i. Text File: A file which stores or manipulates data character by character. We write one

character data at a time and similarly, we read data from file character by character.

ii. Binary File: A file in which we can write records in the form of objects using structures or class. We can call it as random file also as we are able to process(Write, access) records or data randomly.

For example, Attendance register contains records of students wherein, each record denotes an object, i.e. student, or more precisely, information about students. The basic difference between text and Binary file is that text file is structure-less where as Binary file is structured.

97

Page 83: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

2. Classes and streams for file manipulation:

2.1 Stream classes hierarchy-

As mentioned before, a file is stream of bytes (In text File) or blocks of bytes, i.e records

(In Binary file), and in order to perform tasks of writing, reading, modifying or deleting data from it, we need the help of following stream classes:

Out of above mentioned classes, the most commonly used classes are ifstream, ofstream, and fstream.

Note that the stream classes encircled are defined in iostream.h header file and those enclosed in rectangle are defined in the header file fstream.h

2.2 The most commonly used file stream classes: As visible in previous figure of classes hierarchy, the most commonly used classes are iftream,

ofstream, and fstream.

2.2.1 The ifstream class:Basically it contains the read( ) function to read data from a file. Being an input file stream class, it inherits the functions get( ), getline( ), read( ), seekg( ), and tellg( ) from istream class defined inside iostream.h. Hence, an object of this class is able to call the read( ) function in order to read data from a file.

ios

streambuf

iostream

fstream

fstreambase

istream ostream

ifstream ofstream filebuf

98

fstream.h file

iostream.h file

Page 84: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

2.2.2 The ofstream class:Basically it contains the write( ) function to write data in a file. Hence, an object of this class is able to call the write( ) function in order to write or store data in file.

2.2.3 The ifstream class:Basically it contains both the read( ) and write( ) functions. Hence, an object of this class

enables us to read data from file as well as write data to a file.

3.File handling header file The header file fstream.h contains the prototypes and codes of all the necessary file handling

functions like, open( ), close( ), read( ) , write( ), seekg( ), seekp( ), tellg( ), tellp( ) etc. and other necessary information for file handling. This file must be included in your program in order to perform file handling.

Including fstream.h in your program makes inclusion of iostream.h header file optional because fstream.h is derived from iostream.h.

4.File handling functions: As mentioned, we need to call the predefined file handling functions by file object 1 of suitable

class( ifstream, ofstream, or fstream) in suitable file mode. Let us take up these functions and file modes one by one.

4.1 The open( ) function- It open existing file. If the file does not already exist, it automatically creates and opens the file in

memory. A file can be opened in following two ways:

1) Using the constructor function of the stream class-Syntax: class fileobject(“File name”);Where fileobject is an object of suitable class (ifstream or ofstream or fstream)

Example: ifstream rf(“emp.dat”);

The advantage of this method is that we need not call open( ) function.

2) Using the function open( )-Syntax: fileobject.open(“File name”,filemode constants);

Where fileobject is an object of suitable class (ifstream or ofstream or fstream) and filemode denotes the purpose for which the file has been opened viz. writing to or reading from file. (Refer to the table of file mode constants ahead).

Example: ifstream rf;//an object to call read( ) has been created. rf.open(“emp.dat”,ios::in);

Note: If open( ) is not able to open the specified file(due to a number of reasons), it returns NULL or 0 to the file object or the stream object which has invoked the function read().

File Object1: An object of either of the classes ifstream, ofstream or fstream by which a file has been opened for processing.

99

Page 85: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

File Mode constants

S.NO Constant Meaning Stream TypeI) ios::in This specifies that file is capable of input. It

opens for readingifstream

II) ios::out This is capable of output, it opens file for writing but erases the existing data in file,if any, with the newly written data.

ofstream

III) ios::ate This seeks to end of file upon opening of the file. I/O operation can still occur anywhere within the file.

ofstream, ifstream

IV) ios::app This enables us to write as many records as we want in file.(Recods to be appended at the end).

ofstream

V) ios::trunc This causes the contents of preexisting file by the same name to be destroyed and truncates the file to zero length.

ofstream

VI) ios::nocreate This causes the open( ) function to fail if the file does not already exists. It will not create a new file with that name.

ofstream

VII) ios::noreplace This causes the open( ) function to fail if the file already exists.

ofstream

VIII) ios::binary This file opens the file in binary mode. By default, files are opened in text mode.

ifstream, ostream

Most frequently used file opening mode:Open file with ios::app mode if you have to write multiple records in a binary file.Open file with ios::out mode if you have to over-write existing records of the binary file.Open file with ios::in mode if you have to read records from a binary file.

4.2The close ( ) function-It closes a file. Technically, it flushes the buffer before terminating the connection of the file.

Referring to above open( ) example, we can close the file by writing following statement- rf.close( );

It is must that a file is closed by the same file object which had opened it.It is a good practice to close a file after it’s use because further opening of the file in the same program shall ensure that the file pointer is automatically positioned at the beginning of the file.

4.3The write( ) function-It writes an object or block of data(bytes) at a time in a file. The file produced by writing data using this function is by default in binary format.

100

Page 86: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Syntax->oistream & write ( (char * ) & buf, int sizeof (buf) );

-It takes two arguments. The first is the address of variable buf and the second is the length of that variable in bytes. The address of the variable must be type casted to type char * ( that is pointer to character type).

More simple syntax- fileobject.write((char*)&object,sizeof(object));

Where fileobject is an object of suitable class i.e. either ofstream or fstream , (char *) typecasts all the data of different types of the object into stream of characters or bytes whose size is passed as parameter using the operator sizeof( ).

4.4 The read( ) function-It reads an object or block of data(bytes) at a time from a file. This function reads a binary file. In other words, a file created by write( ) function should be read by read( ) function only.

Syntax:-istream & read ( (char * ) & buf, int sizeof (buf));-It takes two arguments. The first is the address of variable buf and the second is the length of that variable in bytes. The address of the variable must be type cast to type char * ( that is pointer to character type).

More simple syntax:-fileobject.read((char*)&object,sizeof(object));

Where fileobject is an object of suitable class i.e. either iftream or fstream , (char *) typecasts all the data of different types of the object into stream of characters or bytes whose size is passed as parameter using the operator sizeof( ).

5. Functions of file stream classes

Functions of File Stream Classes:

Class Purpose/Functionfilebuf It sets the file buffers to read and write. It contains close( ) and open() member

functions in it.fstreambase This is the base class for fstream, ifstream and ofstream classes. Therefore, it

provides operations common to these file streams. It also contains open() and close( ) functions.

ifstream It provides input operations for file. It inherits the functions get( ), getline(), read( ) and functions supporting random access( seekg( ) and tellg( ) ) from istream class defined inside iostream.h file.

ofstream It provides output operations for file. It inherits the functions put( ) and write( ) functions supporting random access( seekp( ) and tellp( ) ) from istream class defined inside iostream.h file.

fstream It is an input-output file stream class. It provides support for simultaneous input

101

Page 87: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

and output operations. It inherits all the functions from istream and ostream classes through iostream class defined inside iostream.h file.

6. File Pointer and Random Access Functions-

When we read from or write to a file, an implicit pointer, known as file pointer keeps on moving in

the file. We can control this file pointer as explained below:

seekg ( ) -

-

istream & seekg(long);

istream & seekg(long, seek_dir);

-seek_dir takes the definition from enum seek_dir {beg, cur, end}

-Simplified syntax: fileobject.seekg(size,reference)

-While reading a file, it positions the file pointer n bytes(size) away from the

reference, where reference may be beginning(ios::beg), end(ios::end) or

current location(ios::cur) in the file.

seekp ( ) -Syntax:

ostream & seekp(long);

ostream & seekp(long, seek_dir);

-seek_dir takes the definition from enum seek_dir1 {beg, cur, end}

-Simplified syntax: fileobject.seekp(size,reference)

-It positions the file pointer n bytes away from the reference, where reference

may be beginning (ios::beg), end(ios::end) or current location(ios::cur) in the

file.

tellg( ) long tellg( )

-Returns the current position of file pointer while reading a file.

tellp( ) long tellp( )

-Returns the current position of file pointer while writing in a file.

7.1Working with Binary file:

let us understand the working with Binary file through a very simplified and documented program

which performs almost all basic operations on a binary file. This program explains the usage

of open( ), close( ), write( ), read( ).

/*PROGRAM BASED ON FILE HANDLING HAVING THE FOLLOWING OPTIONS:

1.WRITE A RECORD.

102

Page 88: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

2.READ ALL RECORD.

3.READ RECORDS BASED ON ROLL NO.

4.DELETE A RECORD

5.QUIT */

#include<fstream.h>//for all file handling functions as well as cin & cout.

#include<conio.h>//for getch()

#include<stdio.h>//for gets()

#include<dos.h>//for delay()

class student

{

private:

int roll; char name[21];

public:

void get()

{

cout<<"\nEnter roll number:";

cin>>roll;

cout<<"\nEnter name:"; gets(name);

}

void show()

{

cout<<"\nRoll number is :"<<roll;

cout<<"\nName is :"<<name;

}

int find_rec()//It shall return the roll of the calling object which has invoked it.

{

return roll;

}

};//End of class

void main()

{

student s;//an object of the class through which we shall write to or read from file

int choice;

103

Page 89: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

while(4!=5)//Infinite loop so as to display main menu as long as user wants.

{

ofstream wf;//A file object to open file for writing records in it.

ifstream rf;//A file object to open file for reading records from it.

cout<<”1.WRITE A RECORD: \n 2.READ ALL RECORD:”;

cout<<”\n3.READ RECORDS BASED ON ROLL NO:”;

cout<<endl<<”4.DELETE A RECORD:”;

cout<<endl<<” 5.QUIT:”;

cin>>choice;

char cont=’y’;

if(choice==1)

{

wf.open("stud.txt",ios::app);//open file in append mode

while(toupper(cont)=='Y')//as long as user continues to write records.

{

s.get();//input a record in object s

wf.write((char*)&s,sizeof(student));//writes the record stored in s in file //stud.txt using

file object wf.

cout<<"\nPress y to write more records:"; cin>>cont;

}

wf.close();

}

else if(choice==2)

{

rf.open("stud.txt",ios::in); //opens the file stud.txt for reading.

rf.read((char*)&s,sizeof(student)); //reads a record (from file) whose size is same as //size of the

class student and stores it in the class object s.

while(rf) //Loop runs as long as end of file is not reached.

{

p.show();

delay(100);//To pause the execution of next statement by 100 millisecond.

rf.read((char*)&p,sizeof(person));

104

Page 90: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

}

rf.close();

}

else if(choice==3)

{

rf.open("stud.txt",ios::in);

rf.read((char*)&p,sizeof(person));

int r; cout<<"\nEnter the roll number whose record has to be shown:";

cin>>r;

while(rf)

{

if(r == p.find_rec())

{

p.show();

delay(100);

break;

}

rf.read((char*)&p,sizeof(person));

}

rf.close();

}

else if(choice==4)

{

rf.open("stud.txt",ios::in);

ifstream temp;

int r,flag=0;

temp.open("temp.txt",ios::out|ios::app);

cout<<"Enter the roll number whose record is to be deleted";

cin>>r;

rf.read((char *)&p,sizeof(p));

while(rf)

{

if(r=!p.find_re())

{

105

Page 91: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

temp.write((char *)&p,sizeof(p));

}

else

{

cout<<"\nRecord found!!!";

cout<<"\nRecord deleted";

flag=1;

}

rf.read((char*)&p,sizeof(p));

}

remove("stud.txt");

rename("temp.txt","stud.txt");

rf.close(); temp.close();

}

else if(choice==5)

{

break;

}

}//end of infinite loop so as to stop the program

}//end of main

7.2 Demonstrating usage of seekg( ), seekp( ), tellg( ), and tellp( ) in program.

Let us write a program which shall:

-Display byte position of starting of each record while writing to a binary file.

-Display records at alternate positions in the file along with the record position.

#include<fstream.h>//for all file handling functions as well as cin & cout.

#include<conio.h>//for getch()

#include<stdio.h>//for gets()

#include<dos.h>//for delay()

class student

{

private:

106

Page 92: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

int roll; char name[21];

public:

void get()

{

cout<<"\nEnter roll number:";

cin>>roll;

cout<<"\nEnter name:"; gets(name);

}

void show()

{

cout<<"\nRoll number is :"<<roll;

cout<<"\nName is :"<<name;

}

};//End of class

void main()

{

student s;//an object of the class through which we shall write to or read from file

int choice;

while(4!=5)//Infinite loop so as to display main menu as long as user wants.

{

ofstream wf;//A file object to open file for writing records in it.

ifstream rf;//A file object to open file for reading records from it.

cout<<”1.WRITE A RECORD.: \n 2.READ ALTERNATE RECORDS:”;

cout<<endl<<” 3.QUIT:”;

cin>>choice;

char cont=’y’;int rec_pos;//To store record position(byte number of beginning of a //record.

if(choice==1)

{

wf.open("stud.txt",ios::app);//open file in append mode

while(toupper(cont)=='Y')//as long as user continues to write records.

{

rec_pos=wf.tellg( );

cout<<”\nYou are writing this record at byte number“<<rec_pos<<” in the file”<<endl;

107

Page 93: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

s.get();//input a record in object s

wf.write((char*)&s,sizeof(student));//writes the record stored in s in file //stud.txt using

file object wf.

cout<<"\nPress y to write more records:"; cin>>cont;

}

wf.close();

}

else if(choice==2)

{

rf.open("stud.txt",ios::in); //opens the file stud.txt for reading.

rec_pos=tellg();

cout<<<<”\nThis record is at byte number“<<rec_pos<<” in the file”<<endl;

rf.seekg(sizeof(student),ios::cur);//Make file pointer jump by size of one record from //current

position so as to position file pointer at the beginning of alternate record.

rf.read((char*)&s,sizeof(student)); //reads a record (from file) whose size is same as //size of the

class student and stores it in the class object s.

while(rf) //Loop runs as long as end of file is not reached.

{

p.show();

rf.seekg(sizeof(student),ios::cur);//Make file pointer jump by size of one record from //current

position so as to position file pointer at the beginning of alternate record.

delay(100);//To pause the execution of next statement by 100 millisecond.

rf.read((char*)&p,sizeof(person));

}

rf.close();

}

else if(choice==3)

{

break; //breaks the infinite loop at the top. The program stops.

}

}//end of infinite loop so as to stop the program

}//end of main

108

Page 94: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Note: The above program does not include usage of seekp( ) as we wanted to write records in the file

in continuity. However, we can use it in the same way we have used seekg( ) while writing in a file.

Activity: Open above file and using seekp( ), overwrite records at alternate positions with new

records. Now display the modified file.

8. Error handling during File I/O

Some errors may occur while opening or performing I/O operation on a file. The reasons can be

fatal(Very serious) or non-fatal(Recoverable). For example, the file you are trying to open is already

open, or the insufficient memory to open the file etc. Following Error handling flags and functions

may help you in such situation:

Error Handling Flags/Bits

Name Meaning

Eofbit If 1, means end of file has been encountered, otherwise 0.

Failbit If 1, means some non-fatal error has occurred, 0 means some fatal error.

Badbit If 1, means some fatal I/O error has occurred, 0 means some non-fatal error.

Goodbit If 0, means no problem.

Error Handling Functions

Function Meaning

int bad( ) Non-zero(True) return value means some invalid operation is attempted or some

unrecoverable(Fatal) error has occurred. Return value 0(false) means some

recoverable error has occurred.

int eof( ) Returns non-zero(false) value if end of file has been reached while processing the

file; Otherwise returns zero.

int fail( ) Returns non-zero(False) value if an input or output operation has failed.

int good( ) Returns a nonzero(true) value if no error has occurred. This means that all the

above functions have returned false. If it returns zero, no further operation is

109

Page 95: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

possible.110

Page 96: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

SOLVED EXAMPLES:

A. Very Short Answer Type Questions: (1 Mark)

1. How are binary files different from text files in C++?

Ans: When the file is opened in text mode various transactions may take place such as the conversion of carriage return and line feed sequences into new lines. However no such character transalations occurs in files opened in binary mode. Any file can be opened in either text or binary mode. The only difference is the occurance of character transalations in text mode.

In text mode, all the processing is done in text oriented data, while in binary mode data is handled in binary.

2. What are the two ways to open data files?

Ans: The two ways to open data files are :

(i) Sequentially

(ii) Randomly

OR using constructor, using open( ) function.

3. observe the program segment given below carefully, and answer the question that follows:

class labrecord

{

int Expno;

char Experiment[20];

char checked;

int Marks;

public :

// function to enter Experiment details

void EnterExp ( );

// function to display Experiment details

void ShowExp( );

// function to return Expno

char RChecked ( ) { return checked; }

111

Page 97: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

// function to assign marks

void Assignments ( int M )

{ Marks = M ; }

};

void ModifyMarks ( )

{ fstream file;

file.open( “ Marks.Dat”, ios : : binary | ios:: in | ios ::out );

labrecord L ;

int Rec = 0;

while( file.read (( char * ) &L, sizeof( L ))

{ if(L.Rchecked ( ) = = ‘N’ )

L.Assignments ( 0)

else

L.Assignments ( 10)

_______________ // Statement 1

_______________ // Statement 2

Rec ++ ;

}

file.close( );

}

If the function ModifyMarks ( ) is supposed to modify Marks for the records in the file MARKS.DAT based on their status of the member checked ( containing value either ‘ Y’ or ‘N’), 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 statement is to perform the write operation with the modified record.

Ans: File.write((char *)&L, sizeof (L)) // Statement 1

File.seekp(-sizeof(Marks)),ios::curr); // Statement 2

4. Observe the program segment given below carefully and fill the blanks marked as Statement 1 and Statement 2 using seekg( ) and tellg( ) functions for performing the required task:

112

Page 98: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

# include < fstream.h>

class Employee

{

int Eno;

char Ename[20];

public:

// Function to count the total number of records.

int Countrec( );

};

int Employee :: Countrec( )

{ fstream File ;

File.open(“EMP.DAT” , ios::binary | ios::in) ;

___________________ // Statement 1

int bytes = ______________ // Statement 2

int count = bytes / sizeof (Employee);

File.close( );

Return Count;

}

Ans: File.seekg(0,ios::end); //statement1

File.tellg( ) //statement 2

B. Short Answer Type Questions: (2 Marks)

1. Write a function in C++ to count and display the number of lines starting withalphabet ‘A’ present in a text file “LINES.TXT”. Example:If the file “LINES.TXT” contains the following lines,A boy is playing there.There is a playground.An aeroplane is in the sky.Alphabets and numbers are allowed in the password.

113

Page 99: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

The function should display the output as 3 Ans: void counter( )

{char Aline[80];int Count=0;ifstream Fin (“LINES.TXT”);while(Fin.getline(Aline,80, ‘\n’))if (Aline[0]== ‘A’)Count++;Fin.close( );cout<<Count<<endl;}

2. Write a function in C++ to count and display the number of lines not starting withalphabet ‘A’ present in a text file ‘STORY.TXT”. Example :If the file “STORY.TXT” contains the following lines,The rose is red.A girl is playing there.There is a playground.An aeroplane is in the sky.Numbers are not allowed in the password.The function should display the output as 3

Ans: void COUNTALINES() //Ignore{ifstream FILE(“STORY.TXT”);int CA=0;char LINE[80];while (FILE.getline (LINE,80))if (LINE[0]!=’A’)CA++;cout<<”Not Starting with A counts to “<<CA<<endl;FILE.close(); //Ignore}

C. Short Answer Type Questions: (3 Marks)

1. Given a binary file STUDENT.DAT, containing records of the following class Student type.

class Student{char S_Admno[lO]; //Admission number of studentchar S_Name[30]; //Name of studentint Percentage; //Marks Percentage of studentpublic:void EnterData(){gets(S_Admno);gets(S_Name);cin>>Percentage;}void DisplayData(){cout<<setw(12)<<S_Admno;cout<<setw(32)<<S_Name;

114

Page 100: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

cout<<setw(3)<<Percentage<<endl;}int ReturnPercentage(){return Percentage;}};Write a function in C++, that would read contents of file STUDENT.DAT and displaythe details of those Students whose Percentage is above 75. Ans: void Distinction(){Student S;fstream Fin;Fin.open(“STUDENT.DAT”, ios::binary|ios::in);while(Fin.read((char*)&S, sizeof(Student))if (S.ReturnPercentage()>75)S.DisplayData();Fin.close();}

2. Given a binary file APPLY.DAT, containing records of the following class Applicant type class Applicant{char A_Rno[10]; //Roll number of applicantchar A_Name[30]; //Name of applicantint A_Score; //Score of applicantpublic:void Enrol(){gets(A_Rno); gets(A_Name) ; cin>>A_Score;}void Status(){cout<<setw(12)<<A_Admno;cout<<setw(32)<<A_Name;cout<<setw(3)<<A_Score<<endl;}int ReturnScore(){return A_Score;}};Write a function in C++, that would read contents of file APPLY.DAT and display thedetails of those Students whose A_ Score is below 70.

Ans: void READAPPLY() //Ignore{fstream FILE;FILE.open(“APPLY.DAT”,ios::binary|ios::in);Applicant A;while (FILE.read((char*)&A,sizeof(A)))if (A.ReturnScore()<70)A.Status();FILE.close(); //Ignore}

3. Given a binary file SPORTS.DAT, containing records of the following structure type :struct Sports

115

Page 101: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

{char Event[20];char Participant[10][30];};Write a function in C++ that would read contents from the file SPORTS.DAT and creates a file named ATHLETIC.DAT copying only those records from SPORTS.DAT where the event name is “Athletics”.

Ans: //Function to copy records from SPORTS.DAT to ATHELETIC.DAT void SP2AT(){fstream IS,OA;Sports S;IS.open(“SPORTS.DAT”,ios::binary|ios::in);OA.open(“ATHLETIC.DAT”,ios::binary|ios::out);while(IS.read((char*) &S,sizeof(S))){if(strcmp(S.Event,”Athletics”)==0)OA.write((char *)&S,sizeof(S));}IS.close();OA.close();}

4. Given a binary file GAME.DAT, containing records of the following structure type struct Game{char GameName [20];char Participant [10] [30];};Write a function in C++ that would read contents from the file GAME.DAT and creates a file named BASKET.DAT copying only those records from GAME.DAT where the game name is “Basket Ball”

Ans: void CopyBasket(){Game G;ifstream fin;fin.open(“GAME.DAT”, ios::binary);ofstream fout;fout.open(“BASKET.DAT”, ios::binary);while(fin.read((char*)&G, sizeof(G))){if(strcmp(G.GameName, “Basket Ball”)==0)fout.write((char*)&G,sizeof(G));}fin.close(); //ignorefout.close(); //ignore}

116

Page 102: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

PRACTICE QUESTIONS:

One Mark Each:

1. Name two member functions of ofstream class.2. Differentiate between ifstream class and ofstream class.3. Distinguish between ios::out and ios:: app.4. Find the error in the following:

(i) ifstream afile;infile.open(“dos.txt”,ios::app);

(ii) ofstream afile;infile.close(“dos.txt”z);

Two Marks Each:

1. Assuming a binary file JOKES.DAT is containing objects belonging to a class JOKE ( as defined below). Write a user defined function in C++ to add more objects belonging to class JOKE at the bottom of it.class JOKE{

int Jokeid; char Type[5]; char Jokesdesc[25];public:

void Newjokeentry( ){ cin>> Jokeid; gets(Type); gets(Jokedesc); }void Showjoke( ){ cout<<Jokeid<< “ : “ << Type<< endl<<Jokedesc<< endl ;}

2. Assuming that a text file named FIRST.TXT contains some text written into it, write a function named vowelwords, that reads the file FIRST.TXT and creates a new file named SECOND.TXT , to contain only those words from the file FIRST.TXT which starts with a lowercase vowel(i.e ., with ‘ a’ , ‘e’ , ‘i’, ‘o’,’u’) For example if the file FIRST.TXT contains

Carry umbrella and overcoat when it rains.Then the file SECOND.TXT shall contain

Umbrella and overcoat it.3. Assuming the class Computer as follows:

class Computer{

char chiptype[10];int speed;public:

void getdata( ){

gets(chiptype); cin>> speed;}void showdetails( ){

cout<<” Chip”<<chiptype<< “Speed = “ << speed ; }};

117

Page 103: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

write a function showfile( ) to read all the records present in an already existing binary file “COMP.DAT” and display them on the screen, also count the no. of records present in the file.

4/5 Marks Each:

1. Declare a structure in C++ telerec, containing name(20 characters) and telephone numbers. A binary data “TELE.DAT” stores data of the type telerec. Write functions in C++ to do the following:

(i) To append records in the file(ii) To display the names for a given telephone no. If the telephone number does not

exist the displays error message: “ Record not found ”.2. Consider the class declaration:

class BUS{

int busno; char destination[20]; float distance;public:

void read ( ); // To read an object from the keyboardvoid write( ); //To write an object into a file.void show( ); //To display the file contents.

}Complete the member function definition.

3. Assuming the class HEAVY_VEHICLE given below, write functions in C++ to perform following:

(i) Write the objects of HEAVY_VEHICLE to a binary file.(ii) Read the objects of HEAVY_VEHICLE from binary file and display them.class HEAVY_VEHICLE{

int petrol,load;public:

void getdata( ){ cin >>petrol; gets( load); }void showdata( ) { cout <<petrol << “ “ << load<< endl;}

}4. Write a program reading the contents of one file, converting the uppercase characters to

lowercase character and copying the new contents to another file.

5.Write a function to read a text file and count the words starting with a capital vowel.

6.Write a function which reads a text file and replaces all the spaces with a character passed as a parameter.

7. Assume that a binary file emp.dat already contains records represented by a class EMP having empno, name and salary of suitable data type. The class contains suitable methods to input, and display records along with another member function which returns empno of a record when invoked. Write a function which increases salary by an amount. The function receives empno, and increment amount as parameters and updates the record.

118

Page 104: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS TO REMEMBER

A file is a bunch of bytes stored on some storage device.

The file mode describes how a file is to be used. Different file modes are ios::in, ios::out, ios::

ate, ios::trunc, ios:: nocreate, ios::noreplace, ios:: binary.

Inorder to process files follow these steps: 1) Determine the type of link, 2)Declare a stream,

3)Link file with the stream, 4) Process as required and 5) Delink the file with the stream.

The function tellg( ) and tellp( ) return the position of get-pointer and put-pointer in a file

stream.

The function eof( ) determines the end of file by returning true for end of file otherwise false.

Including fstream.h makes iostream.h header file optional in a file handling program as

fstream.h is derived from iostream.h.

Learn file opening mode constants.

Learn File error handling functions.

119

Page 105: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

CHAPTER 8

POINTERS

120

FOREVIEW

POINTS OF FOCUS

SOLVED PROBLEMS

POINTS TO REMEMBER

Page 106: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

FOREVIEW

Pointer: A pointer is a variable that holds a memory address

Base Address: A pointer that holds the address of the very first byte of the memory location where it is pointing to

Static memory Allocation: When the amount of memory to be allocated is known beforehand and the memory is allocated during compilation

Dynamic memory allocation: When the amount of memory to be allocated is not known beforehand and the memory is allocated during run time

Free store: It is a pool of unallocated heap memory given to a program that is used by the program for dynamic allocation during execution

Dereferencing: It refers to changing/accessing state of the pointer

New: This operator is used to allocate memory during run time

Delete: This operator is used to deallocate memory during run time

Constant pointer:It is the pointer which will always point to the same address.Its address can not be modified.

Reference: A reference is an alias name for a variable.

Pointer to a constant: It is a pointer which is pointing to a symbolic constant ie the constant value can not be modified.

Self Referential Structure : A structure having a member element that refers to the structure itself is known as self referential structure.

121

Page 107: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

FOCUS ON CONCEPTS

1. Pointer Definition:

A variable storing a memory address is called a pointer. It points to a specific memory location whose address it is storing under its name.

2. Use of a Pointer:

Pointers provide the means through which the memory location of a variable can be directly accessed and hence helps in efficient manipulation.

Pointers support C++’s dynamic allocation i.e. allocate memory as and when required during runtime.

Pointers can improve the efficiency of a routine, like increasing the execution speed of a program.

3. Declaration & Initialization of Pointers:

Syntax for declaration:type *var-name;Eg: int *ip;

Syntax for initialization:type *var-ptr = &var ;Eg: int *ip = &x;

Eg: int *ip, num=25;ip = &num;

Example to illustrate the declaration and initialization of pointers.#include<iostream.h>void main(){

int *ip, num; num=25;ip=&num;cout<<”\n Value of num=”<<num;cout<<”\n Address of num=”<<&num;cout<<”\n Value at address=”<<&num<<”=”<<*ip;getch();

}Output:Value of num=25Address of num=1050Value at Address 1050 = 25

122

Page 108: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

4. & and * Operators:

& (address of) is a unary operator that returns the memory address of its operand.Ex: &i where i is the operand.

*(value at address) is a unary operator that returns the value of the variable located at the address following it. Eg: *ip

Note: Both pointer operators have a higher precedence than all other arithmetic operators except the unary minus with which they have equal precedence.

5. Pointer Arithmetic: Only addition and subtraction is possible on pointers. Each time a pointer is incremented by 1, it points to the memory location of the next

elements of its base type.Ex: int *ip, ip = &i; ip++;

Example to illustrate the declaration and initialization of pointer arithmetic.

#include<iostream.h>void main(){

int i, *ip=&i;float f, *fp=&f;double d, *dp=&d;char c, *cp=&c;i=3; f=5.2;d=10.2;c=’A’;cout<<i<<f<<d<<c; endl;cout<<*ip<<*fp<<*dp<<*cp;endl;cout<<ip++<<fp++<<dp++<<dp++;endl;cout<<ip<<fp<<dp<<dp;

}Output:3 5.2 10.2 A3 5.2 10.2 A1000 2000 3000 40001002 2004 3004 4001

6. Dynamic Allocation/Deallocation Operators: Dynamic allocation is the means by which a program can obtain memory during runtime. ‘new’ operator is used to allocate memory. ‘delete’ operator is used to deallocate the memory. They are also called ‘free store operators’. The ‘new’ operator can be used to create objects of all types, including a class name

Syntaxptr-var = new data-type (value);

Eg: ip = new int; OR int ip = new int; *ip=10; OR int ip=new int(10);

This will allocate a memory location and make ip to point it.

123

Page 109: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

7. Creating Dynamic Array:

Syntaxptr-var = new data-type [size];Eg: int *value = new int[10];

Here, value[0] will refer to first element. value[1] will refer to second element.

Note: The lifetime of an object created by ‘new’ is not restricted to the scope in which it is created. It lives in the memory until explicitly deleted using the delete operator.

Syntax:delete [size] ptr-var;Eg: delete ip;

delete [10] ip;delete [ ] ip;

8. Pointers & Arrays:

In C++ name of the array is treated as a pointer i.e. if int age[10], then ‘age’ stores the address of age[0].

Ex: int *a, age[10]; a = age;

then *a and *age will give same value. age[3] can be represented as *(age+3).

9. 2-Dimensional:

age[0][0] = *(S[0]+0) = *(*(S+0))age[0][0] = *(S[1]+2) = *(*(S+1)+2)

Example to accept data in array and display it using pointers.#include<iostream.h>void main(){

int x[10];for(int i=0;i<10;i++)cin>>*(x+i);for(i=0;i<10;i++)cout<<*(x+i);

}

10. Array of Pointers:

1. As the normal variable we can also make array of pointers.2. Each element of the array pointer will point to different variables of the same type of that

of the pointer.3. Eg: int amt, rate, *ip[10];

ip[3] = &amt; ip[2] = &rate;then, *ip[3] and *ip[2] will point to the amt and rate variable respectively.

Example: A program illustrating array of pointers.

124

Page 110: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

#include<iostream.h>void main(){

int *ip[5];int a=12, b=23, c=14, d=31, e=29;cout<<ip<<”\n”<<*ip<<”\n”<<*(*ip)<<”\n”<<**(ip+3);

}Output:200110001231

11. Pointers & Strings: C++ also support declaration and manipulation of strings using pointers.Char st[20]; declare a string st of 20 characters including the null character.Same can be achieved in this way also char *st. Here st is the pointer to a character and hence equivalent to an array of characters.Eg: void main()

{char *s = “I Love India”;for( ;*s!=‘\0’;s++)cout<<*s;

}

Output:I Love India

12. Pointers & Functions: Call by invoking method can itself be used in two ways: By passing the reference By passing the pointers

Difference between the two is, in the former, variable and its reference refer to same memory area and in the later, the pointer to a variable stores the memory address of the area where it is stored.We can return more than one value at a time using the both concept.

Example to swap two numbers using the pointer concept.#include<iostream.h>void main(){

void swap(int *x, int *y); //function prototypeint a=7,b=4;swap(&a, &b); //function call

}void swap(int *x, int *y) //function definition{

int temp; //temporary location temp=*x; *x=*y; *y=temp;

}13. Function Returning Pointers:

125

Page 111: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Functions can have a pointer as its returning type.Syntax

type * funct-name (arg list);

Example of a function returning pointer variable.

#include<iostream.h>int *big(int &, int &);void main(){

int a,b,*c;cin>>a>>b;c=big(a,b);cout<<c;

}int *big(int &x, int &y){

if(x>y) return (*x);else return(*y);

}14. Pointers & Structures:

A pointer to structures is known as structure pointers.Syntax:

struct-name *struct-ptr; Eg: struct date { int d,m,y;} ; date *dtp;

Using structure pointers, the members of structures are accessed using arrow operator “->”.Syntax

struct-ptr -> struct-member; Eg: dtp -> y; dtp -> d;

Example to illustrate the use of pointers in structures.

#include<iostream.h>void main(){

struct date{ int dd,mm,yy} joint={19,12,2006};date *dtp;dtp=&joint;cout<<joint.dd<<joint.mm<<joint.yy;cout<<dtp->dd<<dtp->mm<<dtp->yy;

}

Output:9 12 20069 12 2006

126

Page 112: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

15. Self Referencial Structures:

A structure having a member element that refers to the structure itself is known as self-referencial structure.

Eg: struct date { int dd, mm, yy;date *next;

};

16. Objects & Pointers:

The pointers pointing to objects are referred to as Object pointers.

Syntax: class-name *object-ptr;

Eg: time *tptr; where time is the class.

The member data and member functions are accessed using arrow operator “”.

Example of use of pointers and object concept.#include<iostream.h>class time {

int hh, mm, ss;public:void getdata(int i, int j, int k){ hh=i; mm=j; ss=k; }void print(){ cout<<hh<<”:”<<mm<<”:”<<ss<< endl; }

};void main(){

time t1, *tp;t1.getdata(10,20,10);t1.print();tp=&t1;tp->getdata(12,10,45);tp->print();

}

Output:

10:20:1012:10:45

Solved Problems

127

Page 113: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Q. Rewrite the following program after removing the syntactical error(s) if any. Underline each correction.

(a)#include<iostream.h>#include<conio.h>main(){

int *c; c= fun(10, 20); cout<<*c; return 0;}int fun (int i, int j){ int *p, *q; p= &i; q= &j; if (i>=50) return p; else return q;}Solution: #include<iostream.h>

#include<conio.h> main() { int* fun (int i, int j);

int *c; c= fun(10, 20);

cout<<*c; return 0; } int* fun (int i, int j) { int *p, *q; p= &i; q= &j; if (i>=50) return p; else return q; }

128

Page 114: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

(b) Identify the errors if any #include<iostream.h>

void main() {

const int i=20;const int * ptr=&i;(*ptr)++;int j=15;ptr =&j;

}Solution #include<iostream.h>

void main() {

const int i=20; int * ptr=&i;//(*ptr)++; //can not modify a const objectint j=15;ptr =&j;// can not modify const pointer

}

c) Identify errors on the following code segmentfloat c[ ] ={ 1.2,2.2,3.2,56.2};float *k,*g;k=c;g=k+4;k=k*2;g=g/2;cout<<”*k=”<<*k<<”*g=”<<*g;

.Solution : The error statements are

k=k*2; g=g/2; as pointer multiplication and division is not possible.

129

Page 115: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS TO REMEMBER

Pointer variables are variable that contain address value in memory

A pointer variable can be defined as a memory location that can store the address of another memory location

Memory location is a container that can store a binary number

Address is a unique binary number assigned to every memory location

Arrays can also be stored and manipulated dynamically using new and delete operators and such arrays are called dynamic arrays

A reference is an alias for a pointer that does not require de-referencing to use

The ‘&’ is called address operator and ‘*’ is called indirection operator

The ‘&’ operator returns the address of the operand.

The ‘*’ operator referred to as indirection or deferencing operator, returns a synonym, alias or nickname for the name of the object that its operand points to in memory

An array name always points to the first element in the array, but a pointer can point to any address in memory

The ‘new’ & ‘delete’ operator are used for dynamic allocation and deallocation of memory respectively

A function may return a reference or a pointer variable also

C++ allows structures to pointer also

‘’ operator(arrow) is used to refer to the public member of the class with a pointer to an object

An object pointer can point to only public members of the class

‘This’ pointer is used to store the address of the object that is currently invoking the member function

A pool of unallocated heap memory given to a program for dynamic allocation during allocation is called ‘free store’

The allocated memory with ‘new’ operator left used without ‘delete ‘ is called memory leak

130

Page 116: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Chapter 9

Arrays

FOREVIEW

POINTS OF FOCUS

SOLVED PROBLEMS

POINTS TO REMEMBER

131

Page 117: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Fore View

I) Introduction to arrays

II) One Dimensional Arraysa. Accessing an arrayb. Passing array to a functionc. Basic operations on arrays (Searching, Insertion, Deletion, Sorting, Traversal,

Merging, Splitting.d. Sorting techniques (Selection sort, Bubble sort, Insertion sort)

III) Two dimensional Arraysa. Address calculation (Row major, Column major)b. Implementation of 2 dimensional arrays.

132

Page 118: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS OF FOCUS

1-D array: Traversal, Searching (Linear, Binary), Insertion of an element in an array, deletion of an element from an array, Sorting (Insertion, Selection, Bubble), concatenation of two linear arrays, merging to two sorted arrays.

2-D array: Traversal, Finding sum/difference of two N x M arrays contains numeric values, Interchanging Row and column elements in a 2 – D array.

I) Important Points An array is a (linear data structure) collection of variables of the same type that are

referenced by a common name. Array consists of contiguous memory locations. Lowest address corresponds to the 1st element and highest address to the last element. Syntax: data type array_name[size];

size from 0 to n – 1 can be accessed. Size defined how many elements the array will hold. Arrays are given a name and its elements are referenced to by their index/subscripts. Array size (length)=UB-LB+1 UB : Upper Bound, LB : Lower Bound The index numbering starts with 0 and ends with size-1 in C++ ie. UB=size-1 and LB=0. Array must be defined before its usage. The data type of array element is known as the base type of the array Eg: int sal[5];

sal[0], sal[1], sal [2], sal [3], sal [4].

In the example, the employee salaries are listed. We have used only one variable name called sal. The name from 1 50 5 is used just to display the position of the values in the array sal. However, in memory, the array variables are stored from 0 through 4. sal[4] indicates the value of the salary of the fifth employee.

Arrays are of different types: One Dimensional Array Multi Dimensional Array

Initializing an arrayfloat a[]={22.3, 55.6,22.7};here the size of a is 3 and the elements are a[0], a[1]. a[2].

II. a) C++ Program to access an arrayvoid main() { int AR[5], i; for(i=0;i<5;i++) cin>>AR[i]; // all the processing can be done here for(i=0;i<5;i++) cout<<AR[i];

133

Page 119: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

}

II. b) Passing array to a function (One dimension)

int sum(int [ ],int); //prototypeint main(){ int a[15], size, i; cout<<“Enter the number of elements”; // int size=sizeof(a)/sizeof(int); cin>>size; cout<< “Enter the Elements : ”; for(i=0;i<size;i++) { cin>>a[i]; } cout<< “Sum of elements in array a : ”<<sum(a, size)<<endl; // calling function }

int sum(int a[], int n) // function definition{ int sum=0; for(int i=0;i<n;i++) sum+=a[i]; return(sum); // return statement} Memory representation of Single Dimension Array

int age[5];age[0] age[1] age[2] age[3] age[4]

2000 2001 2002 2003 2004 2005 2006 2007 2008 2009

char grade[8];grade[0] grade[1] grade[2] grade[3] grade[4] grade[5] grade[6] grade[7]

5000 5001 5002 5003 5004 5005 5006 5007

Address of element with subscript I = Base address + size ( I – Lower Bound ) Some common array errors

Array index to Exceed its Bounds Data Structure is a named group of data of different data types which can be processed as a

single unit.

III) Basic Operations on Array1. Searching2. Insertion

134

Page 120: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

3. Deletion4. Traversal5. Sorting6. Merging7. Splitting

1. Searching There are two types of searching algorithms.

a. Linear Searchb. Binary Search

Linear Search/ Sequential SearchAlgorithm

Step 1 : set ctr=L Step 2 : Repeat steps 3 through 4 until ctr > U.Step 3 : If AR[ctr]= = ITEM then { print “Search Successful” print ctr, “is the location of “, ITEM break }Step 4 : ctr=ctr+1Step 5 : If ctr>U then print “Search Unsuccessful”Step 6 : END C++ Program

void Lsearch(int AR[],int size, int item){ for(int i=0;i<size;i++) {

if(AR[i]==item) cout<<”Search Sucessful”;

cout<<ctr+1<<” is the location of <<item; } cout<<”Search Unsucessful”;}

In Linear search, each element of the array is compared with the given Item to be searched for, one by one. The algorithm will prove the worst, if the element to be searched is one of the last elements of the array as so many comparisons would take place and the entire process would be time consuming. It can work on both sorted and unsorted list.

Binary Search

The precondition for binary search to be performed on a single dimensional array is

135

Page 121: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

The list must be sorted The lower bound and upper bound of the list must be known.

In this the list is divided into two and the searching is done. To save on time and number of comparisons, binary search is very useful.

Algorithm :Step 1 : Set beg = L, last=UStep 2 : Repeat steps 3 through 6 until beg>lastStep 3 : mid = int(beg+last)/2Step 4 : If AR[mid]= = item then { print “Search Successful”

break }Step 5 : If AR[mid]<Item then beg=mid + 1Step 6 : If AR[mid]>Item then last = mid - 1Step 7 : If beg≠last then print “Unsuccessful Search”Step 8 : END

C++ Program

void Bsearch(int AR[], int size, int item){ int beg, last=size-1, mid; beg=0; while (beg <= last) { mid = (beg+last)/2; if(item = = AR[mid]) cout<<“Search successful” else if(item>AR[mid]) beg=mid+1; else last=mid-1; }}

2) InsertionInsertion can be done in two ways.

1. if the array is unordered, the new element is inserted at the end of the array2. if the array is sorted then new element is added at appropriate position without altering the

order and to achieve this, rest of the elements are shifted.Algorithm:Step 1 : ctr = LStep 2 : If Lst = U then { print “Overflow” Exit form program }Step 3 : if AR[ctr]>ITEM then pos=1

136

Page 122: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

else {Step 4 : Repeat steps 5 and 6 until ctr >= UStep 5 : if AR[ctr]<=ITEM and ITEM<=AR[ctr+1] then { pos=ctr+1 break }Step 6 : ctr=ctr+1Step 7 : if ctr=U then pos = U+1 }Step 8 : ctr=UStep 9 : while ctr==pos perform steps 10 through 11 {Step 10 : AR[ctr+1]=AR[ctr]Step 11 : ctr=ctr-1 }Step 12 : AR[pos]=ITEMStep 13 : END

C++ Program

void Insert(int AR[ ], int size, int item){

int pos; if (item<AR[0]) pos=0; else { for(int i=0;i<size-1;i++) { if ((AR[i]<=item) && (item<AR[i+1])) { pos = i + 1; break; } } if (i = size-1) pos = size; } for(i=size;i>pos;i--) { AR[i]=AR[i-1]; } AR[index]=Item;

size+=1; // size of the array has to be changed in the main function}

137

Page 123: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

3) DeletionAlgorithm:Case I ( shifting upwards)Step 1 : ctr=posStep 2 : Repeat steps 3 and 4 until ctr>=UStep 3 : AR[ctr]=AR[ctr+1]Step 4 : ctr=ctr+1Step 5 : End

Case II ( shifting downwards)Step 1 : ctr=posStep 2 : Repeat steps 3 and 4 until ctr<=1Step 3 : AR[ctr]=AR[ctr-1]Step 4 : ctr=ctr-1Step 5 : End

4) TraversalAlgorithm:Step 1 : ctr=LStep 2 : Repeat steps 3 and 4 until ctr>UStep 3 : Print AR[ctr]Step 4 : ctr=ctr+1Step 5 : End

5) Sorting TechniquesSelection sort

void selsort(int AR[], int size){

int small, pos, tmp;for(int i=0;i<size;i++){

small=AR[i];pos=i;{

for(int j=i+1;j<size;j++){

if (AR[j]<small){

small=AR[j];pos=j;

}}tmp=AR[i];AR[i]=AR[pos];AR[pos]=tmp;cout<<"\nArray after sorting : Iteration"<< i<<endl;for(j=0;j<size;j++)

cout<<AR[j]<<" ";}

}cout<<endl;

138

Page 124: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

}

Output:Number of Items : 955 11 33 44 88 222 66 44 33 Array after sorting : Iteration 1

11 55 33 44 88 222 66 44 33Array after sorting : Iteration 2

11 33 55 44 88 222 66 44 33Array after sorting : Iteration 3

11 33 33 44 88 222 66 44 55Array after sorting : Iteration 4

11 33 33 44 88 222 66 44 55Array after sorting : Iteration 5

11 33 33 44 44 222 66 88 55Array after sorting : Iteration 6

11 33 33 44 44 55 66 88 222Array after sorting : Iteration 7

11 33 33 44 44 55 66 88 222Array after sorting : Iteration 8

11 33 33 44 44 55 66 88 222Array after sorting : Iteration 9

11 33 33 44 44 55 66 88 222

11 33 33 44 44 55 66 88 222

Bubble Sortvoid BubbleSort(int AR[], int size){

int tmp;for(int i=0; i<size; i++){

for(int j=0;j<(size-1)-i; j++){

if(AR[j]>AR[j+1]){

tmp=AR[j];AR[j]=AR[j+1];AR[j+1]=tmp;

}cout<<"\nElements after Iteration : "<<i+1<<endl;for(int k=0;k<size;k++)

cout<<AR[k]<<" ";

}}cout<<endl;

}

Output:Enter the number of elements : 544 33 11 66 22

139

Page 125: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Elements after Iteration : 133 44 11 66 22Elements after Iteration : 133 11 44 66 22Elements after Iteration : 133 11 44 66 22Elements after Iteration : 133 11 44 22 66Elements after Iteration : 211 33 44 22 66Elements after Iteration : 211 33 44 22 66Elements after Iteration : 211 33 22 44 66Elements after Iteration : 311 33 22 44 66Elements after Iteration : 311 22 33 44 66Elements after Iteration : 411 22 33 44 66

11 22 33 44 66

Insertion SortINT_MIN constant from limits.h can be used to store minimum possible integer value. It is used when n is small. Also this is used in sorting the cards(bridge game)void inssort(int AR[], int size){

int tmp,j; AR[0]=INT_MIN;

for(int i=1;i<=size;i++){

tmp=AR[i]; j=i-1;

while(tmp<AR[j]){

AR[j+1]=AR[j];j--;

}AR[j+1]=tmp;cout<<"\nArray after sorting : Iteration"<< i<<endl;for(j=1;j<=size;j++)

cout<<AR[j]<<" ";}

cout<<endl;}

140

Page 126: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Output: Enter the number of Elements : 955 11 33 44 88 222 66 44 33

Array after sorting : Iteration1 155 11 33 44 88 222 66 44 33Array after sorting : Iteration2 11 55 33 44 88 222 66 44 33Array after sorting : Iteration3 11 33 55 44 88 222 66 44 33Array after sorting : Iteration4 11 33 44 55 88 222 66 44 33Array after sorting : Iteration5 11 33 44 55 88 222 66 44 33Array after sorting : Iteration6 11 33 44 55 88 222 66 44 33Array after sorting : Iteration7 11 33 44 55 66 88 222 44 33Array after sorting : Iteration8 11 33 44 44 55 66 88 222 33Array after sorting : Iteration9 11 33 33 44 44 55 66 88 222

11 33 33 44 44 55 66 88 222

6) Merging

The merge sort combines two sorted lists into one larger sorted list.   Array A and Array B merge to form Array C.  Arrays to be merged MUST be SORTED FIRST!! . Be sure to declare Array C  in main( ) and establish its size.

Example: Ascending OrderArray A: {7. 12}Array B: {5,  7, 8}Array C: {5, 7, 7, 8, 12} after merge

Here is how it works:  The first element of array A is compared with the first element of array B.  If the first element of array A is smaller than the first element of array B, the element from array A is moved to the new array C.  At this time, the index of array A is increased since the first element is no longer of concern.  

If the element from array B should be smaller, it is moved to the new array C.  The increment of array B is then increased.  This process of comparing elements continues until one of the "feeder" arrays is empty.  When this occurs, the remaining elements in the other array are "pushed" into the end of array C to complete the merge. 

Algorithm ctrA=L1;ctrB=L2;ctrC=L3while ctrA <= U1 and ctrB <= U2 perform steps 3 through 10{ if A[ctrA] <= B[ctrB] then

{ C[ctrC] = A[ctrA]ctrC = ctrC+1ctrA = ctrA+1

}else{ C[ctrC] = B[ctrB]

ctrC = ctrC+1ctrB = ctrB+1

}}if ctrA > U1 then

141

Page 127: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

{ while ctrB <= U2 perform steps 13 through 15{ C[ctrC] = B[ctrB]

ctrC = ctrC+1ctrB = ctrB+1

}}if ctrB > U2 then{ while ctrA <= U1 perform steps 13 through 15

{ C[ctrC] = A[ctrA]ctrC = ctrC+1ctr = ctrA+1

}}

Two Dimensional Array A 2-D array is an array in which each element is itself an array.

Two Dimensional Array Implementationint AR[3][2]

0 1 0 15 201 25 302 35 40

AR[0][0]= 15 AR[0][1]= 20AR[1][0]= 25 AR[1][1]= 30AR[2][0]= 35 AR[2][1]= 40

1. Row Major Implementation Row 0 Row 1 Row 2

15 20 25 30 35 40 AR[0][0] AR[0][1] AR[1][0] AR[1][1] AR[2][0] AR[2][1]

Formula important Address of [I, J]th element in row major order in an r X c array = B + W [ c ( I - Lr) + ( J - Lc ) ] where B=Base address W= size of the element c= number of columns since in C++ implementation the lower bound of an array is 0, Lr = Lc = 0 There fore Address of [I,J]th element in row major order = B + W [ ( c * I ) + J ]

2. Column Major Implementation

col 0 col 1 15 25 35 20 30 40

142

Page 128: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

AR[0][0] AR[1][0] AR[2][0] AR[0][1] AR[1][1] AR[2][1]

Formula important Address of [I, J]th element in row major order in an r X c array = B + W [ ( I - Lr ) + r ( J - Lc ) ] where B=Base address W= size of the element r= number of rows c = number of columnssince in C++ implementation the lower bound of an array is 0, Lr = Lc = 0There fore Address of [I,J]th element in column major order = B + W [ I + (r * J) ]

143

Page 129: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Practical Questions based on this Chapter1. Linear Searching2. Binary Searching3. Insert and Delete an element in a 1-D array4. Selection Exchange Sorting5. Bubble Sorting6. Insertion Sorting7. Merge two 1-D array into one array in sorted order8. Split one 1-D array into two 1-D arrays9. Change the content of a 1-D array (Traversal)10. Add Two Matrix (Class XI)11. Subtract Two Matrix (Class XI)12. Multiply Two Matrix (Class XI)13. Transpose of a Matrix (Class XI)14. Matrix Display. (Will help in Theory)15. 2-D array Traversal

Note: All the algorithms in this chapter can be incorporated with the questions of data file

handling chapter. The pattern display programs in Class XI will be helpful in displaying the 2–D array

elements in different order. The algorithms will help in understanding the stack and queue chapter. All program should be done using User Defined Functions

144

Page 130: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Solved Problems

(1) Explain the Static Data Structure and dynamic Data Structure. [2]

Ans. Static Data structures are those whose size, structure and associated memory locations are fixed at compile time.

Dynamic Data Structure which can or expand as required during the program execution and their associated locations change

(2) What are primitive and non-primitive data types? [2]Ans. Primitive data types are those data types which are not composed of other data types. Eg: int, float, double etc

Non primitive data types are those data types which are not composed of primitive data types. Eg: array, structure, class etc..

(3) What is the difference between linear and non- linear data structures? [2]Ans. Single level data structures where elements form a sequence are called linear data structures eg. Stacks, queues, linked list etc. are linear data structures.

Multilevel data structures are called non-liner data structures eg. Trees and graphs are non-linear data structures.

(4) What are the limitations of using an array? [2]

Ans : The limitations are listed below:

It is static allocation.

An array is always declared of a fixed size

The insertion and deletion operations are time consuming because lot of shifting operations is required.

(5) Write a function in C++ which accepts a 2 D array of integers and its size as arguments and displays the elements which lie on the left and right side. [Assuming the 2D array to be a square matrix with odd dimension ie. 3 X 3, 5 X 5, 7 X 7 etc…] [3] Eg: if the array contents is

5 4 3 6 7 8 1 2 9 Output through the function should be Left Side : 5 6 1 Right Side : 3 8 9

Ans: void display(int a[][],int m)

{int i, j;cout<<"Matrix:\n";for(i=0;i<m;i++){

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

145

Page 131: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

{ cout<<a[i][j]<<"\t";

}cout<<"\n";

}cout<<"Left Side\t\t\tRight Side\n";for(i=0;i<m;i++){

for(j=0;j<m;j++){

if(j==0)cout<<a[i][j]<<"\t\t\t\t";if(j==m-1) cout<<a[i][j]<<"\n";

}}

}

(6) Write a function in C++ which accepts an integer array and its size as arguments/parameters and assign the elements into a two dimensional array of integers in the following format:

[3]

if the array is 1,2,3,4,5,6the resultant 2 D array is given below1 2 3 4 5 61 2 3 4 5 01 2 3 4 0 01 2 3 0 0 01 2 0 0 0 01 0 0 0 0 0Ans:

void display(int a[],int n){

int i, j,m[20][20];for(i=0;i<n;i++){

for(j=0;j<(n-i);j++)m[i][j]=a[j];

for(j=n-i;j<n;j++) m[i][j]=0;

}for(i=0;i<n;i++){

for(j=0;j<n;j++)cout<<m[i][j]<<"\t";

cout<<"\n";}

}(7) Write a function in C++ which accepts an integer array and its size as arguments. Parameters

and exchanges the values of first half side elements with the second half side elements of the array (CBSE Annual 2005) [3]eg. If an array of eight elements has initial content as 2,4,1,6,7,9,23,10

146

Page 132: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

The function should rearrange the array as 7,9,23,10,2,4,1,6

Ans: void swap(int A[],int size)

{ int i, j, temp, mid=size/2; if (size%2==0)

j=mid; else

j=mid+1;for(i=0;i<mid;i++,j++){

temp=A[i];A[i]=A[j];A[j]=temp;

}for(i=0;i<size;i++)

cout<<A[i]<<" ";}

(8) Write a program in C++ that uses the function Des_Marks() to sort a given list of students in descending order of their marks using bubble sort. [4]

#include<iostream.h>struct student{

int rollno;char name[25];float marks;

};void Des_Marks(student s[],int n){

student temp;int flag=0;int i=0;while ((i<n-1)&&(!flag)){

flag=1;i++;for(int j=0;j<n-1;j++){

if(s[j].marks<s[j+1].marks){

temp=s[j];s[j]=s[j+1];s[j+1]=temp;flag=0;

}}

}}void main()

147

Page 133: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

{student slist[10];int size;cout<<”Enter the size of the list:”;cin>>size;for(int i=0;i<size;i++){

cin>>slist[i].rollno>>slist[i].name>>slist[i].marks;}des_marks(slist, size);cout<<”The sorted list:”;for(i=0;i<size;i++){

cout<<slist[i].rollno<<slist[i].name<<slist[i].marks;cout<<”\n”;

}}

(9) Write a function in C++ which accepts an integer array and its size as arguments/ parameters and rotate the values of the array to right with one position (right rotate)eg. If an array of eight elements has initial content as 2,4,1,6,7,9,23,10The function should rearrange the array as 10,2,4,1,6,7,9,23 [3]

Ans: void rotate(int A[],int size)

{int i, j, temp;temp=A[size-1];for(i=size-1;i>0;i--){

A[i]=A[i-1];}

A[i]=temp; //A[0]=temp;}

(10) Write a function in C++ which accepts an integer array and its size as arguments/ parameters and separate the negative numbers to left and positive numbers to righteg. If an array of eight elements has initial content as 3, -50, 11, 35, 7, 70, -15, 33, -7, -8The function should rearrange the array as -50, -15, -7, -8, 3, 11, 35, 7, 70, 33 [4]

Ans: void partition(int A[],int size)

{int i=0, j=size-1,temp;while(i < j){

while (A[i] < 0) i++;while (A[j] > 0) j--;if(i < j){

temp = A[i];A[i] = A[j];

148

Page 134: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

A[j] = temp;}

}

(11) An array AR[15][35] is stored in the memory. Find out the base address and the address of an element AR[2][5], if the location AR[5][10] is stored at the address 4000.and AR[6][10] in 4008.

(AR[5][10] & AR[6][10] are stored consecutively. Therefore it is stored column wise and width is 8 bytes) [4]

Column Major Formula = B + W ( [ I – Lr ] + R [ J – Lc ])

Address of AR[5][10] =>4000=B + 8(( 5-0 ) + (15 (10-0))

4000 = B + 8 ( 5 + ( 15 * 10))

4000 = B + 1240

Therefore B = 4000 - 1240 = 2760

Address of AR[2][5] = B + 8 ( 2 + ( 15 * 5 ) )

= B + 616 = 2760 + 616 = 3376

(12) An array AR[30][40] is stored in the memory with each element requiring 2 bytes of storage. If the base address of AR is 4000, find out memory location of AR[13][25], if the contents is stored along the row

B= 4000 W = 2

Row Major Formula = B + W ( C * [ I – Lr ] + [ J – Lc ])

=4000 + 2 [ 40 (13-0) + (25 – 0)]

= 4000 + 2 [ (40 * 13 ) + 25 ] = 5090.

Calculate the address of X [4, 3] in a two dimensional array X [1..5, 1..4] stored in row major order in the main memory. Assume the base address to be 1000 and that each element requires 4 words of storage.B=1000, W=4, I=4, J=3, R=5, C=4, Lr=1, Lc=1Row Major Formula = B + W [ C*( I – Lr ) + R ( J – Lc )]

= 1000 + 4 [ 4 ( 4 – 1 ) + ( 3 – 1 ) ]=1000 + 4(14) = 1056

(13) A 2-D array defined as A[4..7, -1..3] requires 2 words of storage space for each element. If the array is stored in row-major form, calculate the address of A[6,2] given the base address as 100.B=100, W=2, Lr=4, Lc=-1, I=6, J=2n, number of rows = Ur – Lr + 1 = 3 – (-1) + 1 = 5c, number of columns = Uc – Lc + 1 = 3 – (-1) + 1 = 5

149

Page 135: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Address of A [6,2] = B + W [c (I – Lr) + (J – Lc)] (Row major) = 100 + 2 [ 5 (6-4) + 2 – (-1) ] =100 + 2(13) = 126

Exercise:(1) Write the steps to search 48 using binary search in the following array

60 53 14 48 34Arr[0] Arr[1] Arr[2] Arr[3] Arr[4]

(2) Write a user defined function in C++ to display those elements of a two dimensional array AR[5][5] which are divisible by 5. Display the elements after multiplying it by 3. Assume the contents of the array are already present and the function prototype is as follows.

void displaymat(int AR[5][5];

(3) If an array AR[11][8] is stored as column wise and AR[2][2] is stored at 1024 and B[3][3] at 1084 find the addresses of AR[5][3] and AR[1][1].

Previous Year Questions

1. Given two arrays of integers A and B of sizes M and N respectively. Write a function named

MIX( ) which will produce a third array named C, such that the following sequence is

followed: (Delhi 2001)

1) All even numbers of A from left to right are copied into C from left to right.

2) All odd numbers of A from left to right copied into C from right to left.

3) All even numbers of B from left to right are copied into C from left to right.

4) All odd numbers of B from left to right are copied into C from right to left.

A, B and C are passed as arguments to MIX( ) Eg: A is {3, 2, 1, 7, 6, 3} and B

is {9, 3, 5, 6, 2, 8, 10}, the resultant array C is {2, 6, 6, 2, 8, 10, 5, 3, 9, 3, 7, 1, 3}

2. An array X[7][20] is stored in the memory with each element requiring 2 bytes of storage. If

the base address of array is 2000, calculate the location of X[3][5] when the array X is stored

in Column major order. (Delhi 2001)

Note : X[7][20] means valid row indices are 0 to 6 and valid column indices are 0 to 19.

150

Page 136: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

3. Write a user-defined function Upper_half( ) which takes a two dimensional array A, with size

N rows and N columns as argument and point the upper half of the array.

Eg. (Delhi 2001)

2 3 1 5 0 2 3 1 5 0

7 1 5 3 1 1 5 3 1

if A is : 2 5 7 8 1 The output will be : 7 8 1

0 1 5 0 1 0 1

3 4 9 1 5 5

4. Given two arrays of integers X and Y of sizes m and n respectively. Write a function named

MERGE( ) which will produce a third array named Z, such that the following sequence is

followed: (Outside Delhi 2001)

1) All odd numbers of X from left to right are copied into Z from left to right.

2) All even numbers of X from left to right copied into Z from right to left.

3) All odd numbers of Y from left to right are copied into Z from left to right.

4) All even numbers of Y from left to right are copied into Z from right to left.

X, Y and Z are passed as arguments to MERGE( ) Eg: X is {3, 2, 1, 7, 6, 3} and Y is

{9, 3, 5, 6, 2, 8, 10}, the resultant array Z is {3, 1, 7, 3, 9, 3, 5, 10, 8, 2, 6, 6, 2}

5. An array X[10][20] is stored in the memory with each element requiring 4 bytes of storage. If

the base address of array is 1000, calculate the location of X[5][15] when the array X is

stored in Column major order. (Outside Delhi 2001)

Note : X[10][20] means valid row indices are 0 to 9 and valid column indices are 0 to 19.

6. Write a user-defined function Lower_half( ) which takes a two dimensional array A, with size

N rows and N columns as argument and point the lower half of the array.

Eg. (Outside Delhi 2001)

2 3 1 5 0 2

7 1 5 3 1 7 1

if A is : 2 5 7 8 1 The output will be : 2 5 7

0 1 5 0 1 0 1 5 0

3 4 9 1 5 3 4 9 1 5

7. 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 following odd location.

Example : if an array of nine elements initially contains the elements as

2, 4, 1, 6, 5, 7, 9, 23, 10 (Outside Delhi 2008)

151

Page 137: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

then the function should rearrange the array as 4, 2, 6, 1, 7, 5, 23, 9, 10

8. An array Arr[50][100] is stored in the memory along the row with each element occupying 2

bytes. Find out the address of the location Arr[20][50], if the location Arr[10][25] is stored at

the address 10000. (Outside Delhi 2008)

9. Write a function in C++ to print the product of each row of a two dimensional integer array

passed as the argument of the function. (Outside Delhi 2008)

Example : If the two dimensional array contains\

20 40 10

40 50 30

60 30 20

40 20 30

then the output should appear as:

Product of Row 1 : 8000

Product of Row 2 : 60000

Product of Row 3 : 36000

Product of Row 4 : 24000

152

Page 138: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS TO REMEMBER

The starting address of the very first element of the array is called base address of the array.

The elements of the array are given contiguous memory allocations.

In linear search, each element of the array is computed with the given Item to be searched for

one by one.

Binary search searches for the given Item in a sorted array. The search segment reduces to

half at every successive stage.

Merging means combining elements of two arrays to form a new array.

A two-dimensional array is an array in which each element is itself an array.

The memory is allocated to two-dimensional array is either row-major form or column major

form.

A vector is numeric one dimensional array.

153

Page 139: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

CHAPTER 10

CONCEPT OF LINKED LIST , STACK AND QUEUE

154

FOREVIEW

POINTS OF FOCUS

SOLVED PROBLEMS

POINTS TO REMEMBER

Page 140: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

FORE VIEW

A stack is a list with the restriction that new nodes can be added to a stack or removed from a

stack only at the top.(LIFO-Last in First Out).

When the element is added into the stack, the operation is called push.

When the element is deleted from the stack, the operation is called pop.

A Queue is linear list where insertions can occur only at the rear and deletions occur at

front.(FIFO-First In First Out)

The Queues implemented in circle form a circular Queue.

155

Page 141: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS OF FOCUS

10.1 WHAT IS A LINKED LIST

List : The elements stored in sequence is called a list.

A linked list is a collection of elements called nodes, each of which stores two items of

information- an element of the list and link. A link is pointer or an address that indicates explicitly

the location of the node containing the successor of the list element. In Fig1.1, the arrows represent

the links. The Data part of each node consists of the marks obtained by a student and the link part is a

pointer to the next node. The NULL in the last node indicates that is the last node in the list.

Fig1.1

10.1.1 Singly Linked List

The term ‘list’ refers to a linear collection of data. One form of linear list is arrays. A

LINKED LIST is a linear collection of data elements, called nodes pointing to the next nodes by

means of pointers.

Each node is divided into two parts: The first part containing the information of the element,

and the second part called the link or next pointer containing the address of the next node in the list.

156

Node

Data link

Data Link Data Link link

Data NULL

nullnlink

Kendriya

vidyalaya sangathan

NULL

Page 142: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Doubly-linked list

A doubly-linked list containing three integer values: the value, the link forward to the next node, and

the link backward to the previous node

Circularly-linked list

A circularly-linked list containing three integer values, last pointer points to the first node.

10.1.3 NEED FOR THE LIKED LIST

For storing similar data in memory we can use either an array or a linked list. Arrays are

simple to understand and elements of an array are easily accessible. But arrays suffer from the

following limitations:

Arrays have a fixed dimension. Once the size of an array is decided it cannot be increased or

decreased during execution. For example, if we construct an array of 100 elements and then

try to stuff more than 100 elements in it, our program may crash. On the other hand, if we use

only 10 elements then the space for balance 90 elements goes waste.

Array elements are always stored in contiguous memory allocation. At times it might so

happen that enough contiguous location might not available for the array that we are trying to

create. Even though the total space requirement of the array can be met through a

combination of non-contiguous blocks of memory, we would still not be allowed to create the

array.

Operations like insertion of a new element in an array or deletion of an existing element from

the array are pretty tedious. This is because during insertion or deletion each element after the

specified position has to be shifted one position to the right or one position to the left.

157

Page 143: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

10.1.4 MEMORY ALLOCATION (Dynamic vs Static)

Each data element, stored in the memory, is given some memory. This process of giving

memory is called memory allocation. The memory can be allocated in two manners: Dynamically

and Statically.

10.1.4.1 STATIC MEMORY ALLOCATION

This memory allocation technique reserves fixed amount of memory before actual processing takes

place, therefore, number of elements to be stored must be predetermined. Such type of memory

allocation is called Static memory allocation. Arrays are allocated memory using this technique only.

10.1.4.2 DYNAMIC MEMORY ALLOCATION

This memory allocation technique facilitates allocation of memory during the program execution

itself, as and when required. This technique of memory allocation is called dynamic memory

allocation. Dynamic memory allocation also facilitates release of memory, if memory is not required

any more. Data structures like linked lists and trees use this very technique for their memory

allocation.

10.1.4.3 CONCEPT OF SINGLY LINKED LISTS

The one-way implementation of a general list having elements: ‘Kendriya’, ‘vidyalaya’,’sangathan’ can be done as shown below:

158

Kendriya

vidyalaya sangathan

NULL

Page 144: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

The pointer START is a special pointer which stores the very first address of a linked list. The Next

pointer of the last node stores NULL value, which means this node is not pointing to any other node

i.e., it is the last node in the list.

Representation of a Linked List in Memory

Let List be a linked list to be implemented in memory in the simplest form of

implementation, LIST requires two linear arrays- one called as INFO array for INFO storage and the

other known as LINK array for next pointer storage such that INFO[1] and LINK[1] contain the

INFO part and next pointer of Kth node. Also a separate variable START is required to store the

beginning location of the list. Science the subscripts of the arrays INFO and LINK will usually be

>=0, we choose NULL = -1, unless otherwise stated.

Start = 6, INFO[7]=’E’ and LINK[7] (next pointer)=4

INFO[4]=’J’ ; LINK[4] =0

INFO[0]=’L’; LINK[0]=2

INFO[2]=’R’;LINK[2]=3

INFO[3]=’S’;LINK[3]=7

INFO[7]=’V’; LINK[7]=-1 i.e. NULL

The maintenance of linked list assumes the possibility of inserting new nodes in the list

thereby requiring a mechanism for allocation of unused memory space for the new nodes.

To incorporate these features, together with the linked list in memory, a special list is

maintained consisting of unused memory cells. This list (called AVAIL list) has its own pointer

pointing to the next free node and is called free-storage list or free-pool. With every insertion,

number of free nodes in AVAIL is reduced and with every deletion this number is increased.

INFO[8] is the first available free node, then INFO[1], INFO[9], and INFO[5] are the

following available nodes. With every insertion, AVAIL points to its next node and with every

deletion AVAIL points to the freed node and next pointer of the freed node points to the previous

first node. This method of adding free nodes in AVAIL list, is called garbage collection

10.1.4.4 FREE-STORAGE ALLOCATION in C++

159

Page 145: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

In C++, every program is provided with a pool of unallocated memory that it may utilize

during execution. This memory is known as free store memory.In C++, one aspect of this free store

memory is that it is unnamed. Object allocated on the free store do not possess any name, rather, they

are manipulated indirectly through pointers.

Applying operator new to a type specifier and which returns a pointer pointing to allocated

memory allocates free store memory. To allocate memory for a node of a linked list the following

statements are given.

struct Node { char info[15]; Node * next;

}Node *ptr ; tr = new Node;

Now to refer to info part, we may write ptr ->info.

To refer to the next pointer , we may write ptr->next.

Using a pointer name , arrow operator and the constituent variable name or constituent pointer name

to access the desired memory.

When a node is deleted, it is done as

delete ptr;

10.1.3 BASIC OPERATION ON SINGLY LINKED LISTS

Linked lists Provide ease of performing basic operation on them . We can perform various basic

operation on singly linked list like searching, insertion, deletion, traversal, reversal, splitting and

concatenation.

10.1.3.1 INSERTIONIn a linked list, new ITEM is either added in the beginning of the list or the in the middle of the list

or in the end of the list.

Insertion in the beginning of the listTo add an ITEM in the beginning of the list, START is modified to point to the new node of ITEM

and the next pointer of the new node points to the previous first node.

160

Page 146: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

ALOGRITHM

For insertion, we require to allocate memory for the new node which will be added in the list, the

algorithm will include following steps:

The algorithm for insertion in the beginning of the list is given below:

/* This algorithm deals with insertion in the beginning of the linked list *//* Initialize the pointer */1. ptr = START //start denotes the first node of the list/* allocate memory for the new node */2. NEWPTR = new Node3. If NEWPTR = NULL4. print “No space Available ! Aborting!”5. else6. {7. NEWPTR ->INFO = ITEM8. NEWPTR ->LINK = NULL9. If START = NULL then10 START = NEWPTR11 else {12 SAVE = START13 START = NEWPTR14 NEWPTR -> LINK = SAVE15 }16 }17 END.

IMP NOTE : We try to insert node, when there is no memory available, it is called “OVERFLOW”.

Insertion at the end of the List

ALGORITHM

1. Declare pointers START, PTR, NEWPTR REAR2. ptr = START3. NEWPTR = new Node4. If NEWPTR = NULL5. Print “No space available !! Aborting!!!”6. Exit 7. ELSE8. {9. NEWPTR->LINK =NULL10 }11 If START = NULL THEN12 {13 START = NEWPTR14 REAR = NEWPTR15 }16 REAR - > LINK = NEWPTR

161

Page 147: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

17 REAR = NEWPTR18 END.

10.1.3.2 DELETION Deletion of ITEM from a linked list involves

i) Search for ITEM in the list for availability

ii) If available, make its previous node point to its next node.

Deletion from the beginning of List

ALGORITHM

/* First of all initialize pointers */If START = NULL THEN

Print “ UNDERFLOW”else

{ ptr = startstart = ptr ->LINKdelete ptr }

END;IMP NOTE : We try to delete node, when there is no items is available in the list , it is called “UNDERFLOW”.

10.1.3.3 TRAVERSAL

Traversal of a linked list means processing all the nodes of the list one by one. Following

algorithm traverses a list to print all the elements of it.

Traversal in a List ( ALGORITHM)

/* Initialise counters */ptr = startRepeat step 3 and 4 until ptr =NULLPrint ptr- > INFOPtr = ptr->LINKEND.

10.2 CONCEPT OF STACKA stack is a LIFO1 structure and physically it can be implemented as an array or as a linked

list. A stack implemented as an array inherits all the properties of an array and if implemented as a

linked list, all characteristics of a linked list are possessed by it. But whatever way a stack may be

implemented, insertion and deletions occur at the top only. An insertion in a stack is called Pushing

and the deletion from the stack is called popping.

162

Page 148: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

10.2.1 OPERATIONS ON STACK

A stack is generally implemented with two basic operations- Push and Pop.

Push – Allows adding an element at the top of the Stack.

Pop - Allows to remove an element from the top of the Stack.

10.2.2 STACK AS AN ARRAY

As arrays are static data structure, space required for them must be predetermined i.e. , how many

total elements will be existing together at any point of time must be known beforehand.

INSERTION IN STACK AS AN ARRAY ( PUSHING)

Pushing an element in the stack may involve shifting of elements, as the new element will be inserted

at the top only.

TOP

TOP

TOP

A B C

After pushing H , Stack becomes as B , After pushing another element Q, the stack become as C.In

case the array is full and no new element can be accommodated, it is called STACK-FULL

condition. This condition is also called an OVERFLOW.

Function for pushing an element in to the stack

Int push(int stack[ ], int &top, int item){ if (top= = size – 1)

{ cout<<”Overflow”; return -1;

}else

{top++;stack[top] = item;}

return 0;

163

H

S

V

K

S

V

K

Q

H

S

V

K

Page 149: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

}

DELETION IN STACK ( AS AN ARRAY) – POPING

Popping i.e. , deletion of an element from a stack removes the element at top most position.

For instance, from the stack shown in Fig, the top most element, which is Q, can be popped and after

popping Q, the stack looks as shown Fig A. After popping element P, the stack looks as Fig B. 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.

TOP

TOP

Fig A B

Function for poping an element from the stack.Int pop(int stack[],int &top){

int element; if(top= =-1)

{ cout<<”Underflow”; return -1;}else{element=stack[top];top--;return element;

}

10.2.3 STACK AS A LINKED LIST (LINKED STACK)

A linked list is a dynamic data structure where space requirements need not be predetermined. A

stack implemented as a linked list also inherits all these properties. The creation of a stack ( as a

164

H

S

V

K

Q

HS

V

K

Page 150: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

linked list) is the same as the creation of a linked list i.e., after getting a node for the ITEM to be

inserted , TOP point to the newly inserted node.

INSERTION IN A LINKED STACK (PUSHING)

As a push can only occur at the TOP gets modified every time. For instance, if we have a stack as

shown in fig (a) after pushing ‘S’, it becomes as Fig (b). After pushing another element ‘P’, it

becomes as Fig (c).

TOP

Fig (a)TOP

Fig (b)TOP

Fig (c)

Function to create a node;struct node{int item; node *next;} *top,*ptr;

Function to insert a node;

node * new_node(int n){ ptr=new node;

ptr->item=n;ptr->next=NULL;return ptr;

}

Function to push an element in to the stack;

void push(node *np){

if(top= = NULL)

165

N K nI

L N K nI

N K n

Page 151: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

top= np;else{

temp=top;top=np;np->next=temp;

}}

DELETION FROM A LINKED STACKDeletion i.e. popping also require modification of TOP i.e. TOP is made to point to the next node in

the sequence. For instance, if the stack is shown in Fig a; after popping ‘P’ , it becomes as Fig b.

After Popping ‘S’ , it becomes a Fig c.

TOP

Fig (a)

TOP

Fig (b)

TOP

Fig (c )

popping an element from a stack.void pop(){

if (top= = NULL)cout<<”Underflow”;

else{

ptr=top;top=top->next;delete ptr;

}}

10.2.4 APPLICATION OF STACK

166

L N K nI

N K nI

N K n

Page 152: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

There are several applications and uses of stacks. The stacks are basically applied where LIFO ( Last

In First Out) scheme is required.

1. Reversing a Line : A simple example of stack application is reversal of a given line. We can

accomplish this task by pushing each character on to a stack as it is read. When the line is finished

characters are then popped off the stack, and they will come off in the reverse order as shown in fig.

1. Push R in empty stack Push D Push B

Push M Push S

2. Now Pop the element of the Stack One By one

Pop S, Pop M, Pop B, Pop D and Pop R

We get SMBDR reverse of RDBMS

2. POLISH NOTATIONAnother application of stacks is in the conversion of arithmetic expression in high level

programming languages into machine-readable form. As our computer system can only understand

and work on a binary language, it assumes that an arithmetic operation can take place in two

operands only e.g. A + B, C * D, D/A etc. But in our usual form an arithmetic expression consist of

more than one operator and two operands e.g.

( A+B)* C( D/(J+D)). This complex arithmetic operation can be converted into polish strings using

stacks, which then can be executed in two operands and a operator form.

Polish string, named after a polish mathematician, Jan Lukasiewicz, refers to the notation in

which the operator symbol is placed either before its operands (prefix notation) or after its operands

(postfix notation) in contrast to usual form when operator is placed in between the operands ( Infix

notation).

Following table shows the three types of notations:

Infix notation Prefix Notation Postfix NotationA+B(A-C)*B(A+B) /( C-D)

+AB* - ACB/+AB-CD

AB+AC- B*AB+CD-/

10.2.3 CONVERSION OF INFIX EXPRESSION TO POSTFIX (SUFFIX) EXPRESSIONWhile evaluating an infix expression, there is an evaluation order according to which

167

R BD

RMB

D

R

S

MB

D

R

D R

Page 153: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

I Brackets or ParenthesisII ExponentiationIII Multiplication or Division,IV Addition or Subtraction

Take place in the above specified order. The operators with the same priority are evaluated from left

and right. To convert an infix expression into a postfix expression, this evaluation order is taken into

consideration. An infix expression may be converted into postfix from either manually or using a

stack. the manual conversion requires two passes : one for inserting braces and another for

conversion. However, the conversion through stack requires single pass only.

ALGORITHM TO CONVERT INFIX EXPRESSION TO POSTFIX FORM

The algorithm transforms the infix expression X into its equivalent postfix expression Y.

The algorithm uses a stack to temporarily hold operators and left parentheses. The postfix expression

Y will be constructed from left to right using the operands from X and the operators, which are

removed from STACK. We begin by pushing a left parenthesis onto STACK and adding a right

parenthesis at the end of X. The algorithm is completed when STACK is empty.

Suppose X is an arithmetic expression written in infix notation. This algorithm finds the equivalent

postfix expression Y.

1. Push “(“ onto STACK, and add “)” to the end of X.2. Scan x from left to right and REPEAT Steps 3 to 6 for each element of X UNTIL the STACK

is empty:3. If an operand is encountered, add it to Y.4. If a left parenthesis is encountered, push it onto STACK.5. If an operator is encountered, then:

a. Repeatedly pop from STACK and add to Y each operator( on the top of STACK) which has the same precedence as or higher precedence than operator.

b. Add operator to STACK./* End of If Structure*/

6. If a right parenthesis is encountered, then:a. Repeatedly pop from STACK and add to Y each operator (on the top of STACK)

until a left parenthesis is encountered.b. Remove the left parenthesis. [Do not add the left parenthesis to Y].c. /*End of Step 2 loop*/

7. END.

Concept of Evaluating a Postfix Expression (Algorithm)

/* Reading of expression takes place left to right */1. Read the next element /* first element for the first time */2. If element is operand then Push the element in the stack3. If element is operator then

{4. Pop two operands from the stack/* Pop one operand in case of unary operator*/

168

Page 154: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

5. Evaluate the expression formed by the two operands and the operator6. push the result of the expression in the stack end

{7. If no more elements then

Pop the resultelse

go to step –18. END.

10. 3 QUEUE

Logically a queue is a FIFO structure and physically it can be implemented either as an array

or as a linked list. Whatever way a queue is implemented, insertion take place at the “ Rear” end and

deletion at the “Front” end.

10.3.1 QUEUE AS AN ARRAY

When a queue is created as an array, its number of elements is declared before processing.

The beginning of the array becomes its “ front” end and the end of the array become “rear” end. The

terms “front” and “rear” are used in describing a linear list only when it is implemented as a queue.

“Front” stores the index of first element in the queue and the “rear” stores the index of last element

in the queue. The number of elements in a queue at any given time can be calculated from the values

of the “front” and the “rear”.

If front = 0 then no-of-elements = 0

Else no-of-elements = front – rear + 1.

10.3.1.1 INSERTION IN AN ARRAY QUEUELet us consider that a queue is stored in the memory using an array QUEUE with N elements

Fig a. Fig (b), (c) and Fig(d) show the way new elements will be added to the queue. Observe that

with every insertion, the value of “rear” is increased by 1. This means that after N insertions the rear

element will occupy QUEUE[N-1] and after it, the queue becomes FULL and no more elements can

be added to it.

0 1 2 3 4 5 …. N-2 N-1

front =null

169

Page 155: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

rear = nullFig(a)

front = 0rear = 0

Fig(b)

front = 0rear = 1

Fig(c)

front = 0rear = 2

Fig(d)

Function to push an element in QueueInt insert-in-Q(int Queue[], int BOOK){

if(rear= = size -1)return -1;

else if(rear= = -1){

front= rear=0;Queue[rear]=Book;

}else{

rear++;Queue[rear]=Book;

}return 0;}

Function remove() recycles the queue array

If underflow occur, it returns -1 and if it successfully remove the element, if returns deleted element.

Int remove(int Queue[]){

int ret;if(font = = -1)

return -1;else{

ret=Queue[front];if(font= = rear)

front=rear=-1;elsefront ++;

}return ret;

170

6 4

6 4 19

6

Page 156: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

}

10.3.1.2 DELETION IN AN ARRAY QUEUEAs deletion can occur at the “front” end only, with every deletion, the “front” gets modified.

Whenever an element is deleted from the queue, the value of “front” is increased by 1. Following fig

b,c, and d show the way elements will be deleted from the original queue shown in fig a.

0 1 2 3 4 5 …. N-2 N-1

front = 0rear = 5

Fig(a)

front = 1rear = 5

Fig(b)

front = 2rear = 5

Fig(c)

front = 3rear = 5

Fig(d)

10.3.2 LINKED QUEUES

Linked queue are the queues having links among its elements. Two pointers are maintained to store

the “front” position and the “rear” position.

Insertion in a linked Queue:

Insertion in a linked queue also take place only at the “rear” and i.e. the “rear” gets modified with

every insert.

10.3.2.1 Deletion in a Linked Queue

Deletion in a linked queue take place from the “front” end. Therefore, the “front” gets modified with

every delete.

Program for Insertion and deletion an element in a Queue :

#include<iostream.h>

171

6 4 19 25 17 12

4 19 25 17 12

19 25 17 12

25 17 12

Page 157: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

#include<conio.h>#include<process.h>#include<malloc.h>

// Creating a NODE Structurestruct node{ int data; struct node *next;};

// Creating a class QUEUEclass queue{ struct node *frnt,*rear; public: queue() // constructure {

frnt=rear=NULL; } void insert(); // to insert an element void del(); // to delete an element void show(); // to show the stack};// Insertionvoid queue::insert(){ int value; struct node *ptr; cout<<"\nInsertion\n"; cout<<"Enter a number to insert: "; cin>>value; ptr=new node; ptr->data=value; ptr->next=NULL; if(frnt==NULL) frnt=ptr; else rear->next=ptr; rear=ptr; cout<<"\nNew item is inserted to the Queue!!!"; getch();}

// Deletionvoid queue::del(){ if(frnt==NULL) { cout<<"\nQueue is empty!!"; getch(); return;

172

Page 158: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

} struct node *temp; temp=frnt; frnt=frnt->next; cout<<"\nDeletion Operation........\nDeleted value is "<<temp->data; delete temp; getch();}

// Show Queuevoid queue::show(){ struct node *ptr1=frnt; if(frnt==NULL) { cout<<"The Queue is empty!!"; getch(); return; } cout<<"\nThe Queue is\n"; while(ptr1!=NULL) { cout<<ptr1->data<<" ->"; ptr1=ptr1->next; } cout<<"END"; getch();}

// Main functionint main(){ clrscr(); queue q; int choice; while(1) { cout<<"\n-----------------------------------------------------------"; cout<<"\n\t\tQUEUE USING LINKED LIST\n\n"; cout<<"1:INSERTION\n2:DELETION\n3:DISPLAY QUEUE\n4:EXIT"; cout<<"\nEnter your choice(1-4): "; cin>>choice; switch(choice) { case 1:

q.insert(); break;

case 2: q.del(); break;

case 3: q.show();

173

Page 159: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

break; case 4:

exit(0); break;

default: cout<<"Please enter correct choice(1-4)!!"; getch(); break;

} } return 0;}

10.3.3 Variations in Queues

Queues can be used in several forms and ways, depending upon the requirements of the

program. Two popular variations of queues are circular queue and Dequeues( double-ended queues).

Circular Queues - Are the queue implemented in circular form rather than a straight line.

Circular queues overcome the problem of unutilized space in linear queues implemented as

arrays. The circular queue considers itself contiguous ends, that is why, if space is there in

the beginning, the rear shift back to beginning after reaching the maximum possible index-

number.

ALGORITHM ( Insertion in a Circular Queue)/* Assuming that the circular queue is stored in QU with size N. */Check if Queue already filled or not */

1. I f ( FRONT = 0 AND REAR =N –1) or ( FRONT =REAR +1) Then { Write “Overflow!!” }

Else{

174

Page 160: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

2. If FRONT = NULL Then [QU is initially empty]{ set FRONT =0

Rear = 0}

3. Else IF REAR = N-1 Then Set REAR = 0

Else4. Set REAR = REAR + 1

}5. Set QU[REAR] = IN_ITEM //End of If6. END. // (to insert the new item I_ITEM)

ALOGRITHM (Deletion in a circular Queue)

/* Assuming that the queue is stored in as array QU with size N. This algorithm will delete an element from the queue and assign it to D-ITEM . *//* Check if QU is already empty or not? */

1. If FRONT = NULL Then { Write “Underflow !!” Return}Else{

2. Set D-ITEM = QU[ FRONT]/* Now Make FRONT point to the next element in the queue */

3. If FRONT = REAR Then {

FRONT = NULLREAR = NULL

}4. Else If FRONT = N –1 Then

FRONT = 0 Else

5. FRONT = FRONT + 1}

6. END.

DEQUE ( double-ended queue ) – are the refined queues in which elements can be added or moved

at either end but not in the middle.

There are two variations of a deque – an Input restricted deque and an Output-restricted deque.

An input restricted deque is a deque which allows insertion at only one end but allows deletions at

both ends of the list. An Output restricted deque is a deque which allows deletions at only one end of

the list but allows insertions at both ends of the list.

SOLVED QUESTIONS

175

Page 161: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

LINKED LIST

Q. Define LINKED LIST 1

Answer : The term ‘list’ refers to a linear collection of data. A LINKED LIST is a linear collection

of data elements, called nodes pointing to the next nodes by means of pointers.

Q. What is the advantages of linked list over the array . 2

Answer : The advantages of linked list are following :

1. A linked list can grow and shrink in size during its lifetime. In other words, there is no

maximum size of a linked list.

2. The second advantage of linked lists is that, as nodes(elements) are stored at different

memory locations it hardly happens that we fall short of memory when required.

3. The Third advantage is that , unlike arrays , while inserting or deleting the nodes of

the linked list , shifting of nodes is not required.

Q. State the Overflow and Underflow . 2

Answer:

Overflow: If We try to insert node, when there is no memory available, it is called “OVERFLOW”.

Underflow : If we try to delete node, when there is no items is available in the list , it is called

“UNDERFLOW

Q. Write the algorithm for insertion of new node at the beginning of linked list. 4

Answer: The algorithm for insertion in the beginning of the list is given below:

/* This algorithm deals with insertion in the beginning of the linked list *//* Initialize the pointer */1. ptr = STRAT //start denotes the first node of the list/* allocate memory for the new node */2. NEWPTR = new Node3. If NEWPTR = NULL4. print “No space Available ! Aborting!”5. else6. {7. NEWPTR ->INFO = ITEM8. NEWPTR ->LINK = NULL9. If START = NULL then10 START = NEWPTR11 else {12 Save = START13 START = NEWPTR

176

Page 162: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

14 NEWPTR -> LINK = Save15 }16 }17 END.Q. Write a function in c++ to insert a node at last containing Custmer information from a

dynamically allocated Link List of Cust implemented with the help of the following structure

5

struct Cust

{

int Cno ;

char Cname[20];

char phno[10];

Cust * next ;

}*first,*last;

Answer :

#include<conio.h>#include<string.h>#include<iostream.h>#include<stdlib.h>

struct Cust{

int Cno ;char Cname[20];

char phno[10];Cust * next ;

}*first,*last;

Cust * ncust(int cno,char * cname,char * ph) {struct Cust * n;n = new Cust;strcpy(n->Cname,cname);strcpy(n->phno,ph);n->Cno = cno;n->next=NULL;

return n;

}void insertlast(Cust * node) {

if (last==NULL) {first = last = node;

177

Page 163: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

}else {

last->next=node;last = node;

}}void showall() {

Cust * t;t = first;while(t!=NULL){

cout<<endl<<t->Cname;cout<<endl<<t->Cno;cout<<endl<<t->phno;t=t->next;

}}void main() {

first = last = NULL;Cust * t;t = ncust(1,"a","123456");insertlast(t);t = ncust(2,"b","234567");insertlast(t);t = ncust(3,"c","345678");insertlast(t);t = ncust(4,"d","456789");insertlast(t);

showall();}

STACK

Q. What is stack ? Specify the operation on Stack. 2

Answer : Stack is a linear data structure which is following the rule of LIFO.

A stack is generally implemented with two basic operations- Push and Pop.

Push – Allows adding an element at the top of the Stack.

Pop - Allows to remove an element from the top of the Stack.

Q. Convert ( A + B) * C/D into postfix notation. 2

Solution:

Step I Determine the actual evaluation order by putting braces.

(( A + B) * C) / D

StepII Converting expression into innermost braces

178

Page 164: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

(( AB +)*C) /D

((AB+C*)/D

AB+C*D/

EXERCISE: Convert the following infix to postfix Expression.

1. (( A+B)*C/D+ E^F) / G2. A*(B+(C+D)*(E+F)/G)*H3. A+[( B +C) + (D +E)* F) /G4. NOT A OR NOT B NOT C

Q. Convert X: A + (B * C – (D / E ^ F) * G) * H into postfix form showing stack

status after every step in tabular form: 5

Solution:.

Symbol Scanned Stack Expression Y1. A ( A2. + ( + A3. ( ( + ( A 4. B ( + ( A B5. * ( + ( * A B6. C ( + ( * A B C7. - ( + ( - A B C *8. ( ( + ( - ( A B C *9. D ( + ( - ( A B C * D 10. / ( + ( - ( / A B C * D11. E ( + ( - ( / A B C * D E12 ^ ( + ( - ( / ^ A B C * D E 13 F ( + ( - ( / ^ A B C * D E F14 ) ( + ( - A B C * D E F ^ /15 * ( + ( - * A B C * D E F ^ /16 G ( + ( - * A B C * D E F ^ / G17 ) ( + A B C * D E F ^ / G * -18 * ( + * A B C * D E F ^ / G * -19 H ( + * A B C * D E F ^ / G * - H20 ) A B C * D E F ^ / G * - H * +

Q. What is the advantage of Postfix Expression over Infix Expression? 2

Answer : Advantage of Postfix Expression over Infix Expression

An infix expression is difficult for the machine to know and keep track of precedence of operators. On the other hand, a postfix expression itself determines the precedence of operators ( as the placement of operators in a postfix expression depends upon its precedence). Therefore, for the machine it is easier to carry out a postfix expression than infix expression.

179

Page 165: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Q. Evaluate the expression 5, 6, 2, +, *, 12, 4, /, - in tabular form showing stack status after every

step. 4

Answer: Step Input Symbol / Element Stack Intermediate

calculations Output

1 5 Push 52 6 Push 5, 63 2 Push 5,6,24 + Pop ( 2 elements) & evaluate 5 6+2 = 85. Push result ( 8) 5, 86. * Pop ( 2 elements) & evaluate # empty 5 *8 = 407. Push Result ( 40) 408. 12 Push 40, 129 4 Push 40, 12, 410 / Pop ( 2 elements) & evaluate 40 12/3 = 311 Push result ( 3) 40, 312 - Pop ( 2 elements) & evaluate # 40 – 3 = 3713 Push Result ( 37) 3714 No-more elements 37 result

Q. A line of text is read from the input terminal into stack .Write an algorithm to output the string in

the reverse order ,each character operating twice (eg. The string a b c d e should be changed to ee dd

cc bb aa ). 3

Solution:: 1.ptr = top 2. While (ptr <> NULL or ptr <> 0 ) do steps 3 through 5 3. { print ptr -> INFO ,ptr -> INFO 4. POP(stack,ITEM) 5. Ptr = ptr-1 ; }

Q. A stack containing integer type numbers, is to be implemented as linked list , give the necessary

declarations. 2

Solution::: struct S { int info; S * next ; }*top , *ptr ;

Q. Write the algorithm to change an infix notation into postfix notation. Change following

expression by using it. (Create its changing table) 5

12 + 30 * 2 – 35 / (5 + 2 ) * 2 Answer :

180

Page 166: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

To convert an infix notation in to prefix notation we need one infix string(infix) one prefix string (prefix) one stack. And we perform following steps ;1. Get character in c from infix from left to right till it have characters. And repeat step 2 to

4.2. If c is a operand add it to postfix.3. If c is a ‘(‘ then push it to stack.4. If c is operator then:

(i) Pop operator from stack if it have same or higher priority than c then add it to postfix. Repeat this process till you get same of higher priority operator in stack.

(ii) Push c in stack.5. If c is right parenthesis then :

(i) Pop all item from stack till you doesn’t get ‘(‘ and add them in postfix.(ii) Remove the left parenthesis and do not add it to postfix.

6. End

Sn Symbol

Stack Postfix

1 12 122 + + 123 30 + 12 304 * +* 12 305 2 +* 12 30 26 - - 12 30 2 *+7 35 - 12 30 2 *+358 / -/ 12 30 2 *+359 ( -/( 12 30 2 *+3510 5 -/( 12 30 2 *+35 511 + -/(+ 12 30 2 *+35 512 2 -/(+ 12 30 2 *+35 5 213 ) -/ 12 30 2 *+355 2+14 * -* 12 30 2 *+35 5 2+/15 2 -* 12 30 2 *+35 5 2+/216 12 30 2 *+35 5 2+/2*-

12 30 2 *+35 5 2+/2*-

SAMPLE QUESTION

1 Mark questions 1. What is the significance of NULL pointer in a linked list ?2. What is the advantage of using doubly linked list ?3. Give the postfix expression of the following expression A*(B+(C+D)*(E+F)/G)*H4. Differentiate between LIFI and FIFO list .

181

Page 167: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

5.What is stack ? 2/3 Marks questions1.Given an integer k ,write an algorithm which deletes the node located in kth position from a linked list .Say START gives the location of the first node and P is the location of the node previous to k.

2.Give one merit and demerit of circular list ?

3. Why stack is called LIFO data structure? Give an algorithm POP to delete the topmost element from a stock S.4. Change the following infix expression into postfix expression: 2

A+[(B+C) +(D+E)*F]/G

Show the complete steps.5. Write the functions in C++ to insert as well as delete elements from a stack which is implemented as an array.6. Evaluate the following postfix expression using a stack and show the contents of stack after

execution of each operation. Don’t write any code. 2

TRUE, FALSE,TRUE,FALSE,NOT,OR,TRUE,OR,OR,AND

3

4/5 Marks questions 1. Define linked list and linear list .Explain with examples .2. Write a program to create and display a list of patients in a small hospital using linked list

data structure .Each node contains the name of the patient ,his age and his admit number .

QUEUE

Q. Consider the following circular queue capable of accommodating maximum six elements :

front =2 , Rear = 4 ; Queue:: -- , X ,Y,Z ,-- ,--

Describe the queue as the following operations take place :

(a) Add N (b) Add M (c) Delete two letters (d) Add M,H,I (e) Delete one

letter 3

Answer:: (a) front = 2 , Rear = 5 Queue : - ,X,Y,Z,N , --

(b) front =2 Rear = 6 Queue : - ,X,Y,Z,N , M © front = 4 Rear = 6 Queue : -- ,--,--,Z,N , M (d) front =4 Rear = 3 Queue : M ,H,I ,Z,N , M

(e) front = 5 Rear = 3 Queue : M ,H,I, -- ,N , MQ An array circular Queue[10] of integers exist, where currently 3

Rear = 0

Front = 1

182

Page 168: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Answer the following questions based on above given data

a. How many values are there in Queue?

b. If five values are deleted, what would be the new value of Front?

Ans: i) Front is > Rear, so the number of elements are N+ (Rear—Front) + 1

= 10 +( 0 – 1 ) + 1

= 10

ii) After deletion of five elements the value of front will be six.

Q class queue

{ int data[10];int front, rear;public:

queue(){ front =-1, rear=1;}void add(); // to add an elemnt into the queuevoid remove(); //to remove an element from the queue};

Complete the class with all function definitions for a circular array queue. 4Ans : Void queue :: add(){ if (rear == front)

{ if (rear = = -1)front = rear =0;

elserear = (rear + 1) % 10;

cout<<”Enter data:”;cin>> data[rear];

}else

cout<<”Queue full”;}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 “;}Q. Write functions in C++ to insert and delete an element in a linked implementation of queue called

names. 4

Ans : //Function to add an elemntnode *add-Q(node *rear, char val){

183

Page 169: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

node *temp;temp = new node;temp->dat = val;temp->link = NULL;rear->link = temp;rear = temp;return(rear);}

// Function to delete an elementnode *del_Q(node *front, char name[]){

node *temp;if(front = = NULL )

{ cout<< “Queue empty “; val = -1;}else{

temp = front;front = front ->link;strcpy(name,temp->data);temp->link = NULL;delete tem;

}return(front);

}Q Write a function in C++ to perform Insert operation on a dynamically allocated Queue containing

names of students. 4

Q:Give the necessary declarations of a queue containing integers .Write a user defined function in

C++ to delete an integer from the queue .The queue is to be implemented as a linked structure.

4

Q Define member functions quiens( ) to insert and quedel() to delete nodes of the linked list

implemented class queue. Where each node has the following structure: 4

Struct node{Char name[20];Int age;Node *link;

};class queue{

node *rear, *front;public:queue(){ rear = NULL; front = NULL; };void queins( );void quedel( );

};

184

Page 170: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

185

Page 171: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS TO REMEMBER

A stack is a list with the restriction that new nodes can be added to a stack or removed from a

stack only at the top.(LIFO-Last in First Out)

When the element is added into the stack, the operation is called push.

When the element is deleted from the stack, the operation is called pop.

When a stack is implemented as an array, is full and no new element can be added, it is called

an OVERFLOW.

If we try to delete node, when there is no items is available in the list , it is called

UNDERFLOW.

When the operator is placed in between the operands, the expression is called Infix

expression, eg, A +B

When the operator is placed after the operands, the expressions is called postfix expression

eg, AB+.

A Queue is linear list where insertions can occur only at the rear and deletions occur at

front.(FIFO-First In First Out)

The Queues implemented in circle form a circular Queue.

186

Page 172: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

CHAPTER -11

DATABASE CONCEPTS

FORE VIEW

POINTS OF FOCUS

SOLVED PROBLEMS

POINTS TO REMEMBER

187

Page 173: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

FORE VIEW

1. Database Concepts

1.1 .Relational data modelIt represents data and relationships among data by a collection of tables known as relations, each of which has a number of columns with unique names.

1.1.1. Concept of domainTuple: The row of a table (Relation).Relation: A table with rows and columnsKeys-Primary key : A Primary Key is a set of one or more attributes that can uniquely identify tuples within the relation.

Alternate key: A candidate key that is not the Primary key is called an Alternate Key. Candidate key: All attribute combinations inside a relation that can

serve as Primary key are Candidate Keys as they are candidates for the Primary key position.

1.2 .Relational Algebra1.2.1. Selection : The select operation selects tuples(horizontal subset) from a

relation1.2.2. Projection : The project operation yields a “vertical” subset of a given

relation1.2.3. Union : The union operation is a binary operation that requires

two relations as its operands1.2.4. Cartesian Product: The Cartesian product is a binary operation and is

denoted by a cross(X).

188

Page 174: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS OF FOCUS

Database: A database is a collection of correlated data stored together.

DBMS: Data base management system. It is basically a computer based record keeping system to manage the database.

Domain: It is the distinguished part of an abstract or physical space where something exists, is performed, or valid.Data domain refers to all the unique values which a data element may contain. For example, a database table that has information about people, with one record per person, might have a "gender" column. This gender column might be declared as a string data type, and allowed to have one of two known code values: "M" for male, "F" for female and NULL for records where gender is unknown or not applicable (or arguably "U" for unknown as a sentinel value). The data domain for the gender column is: "M", "F".

Types of data model:1. Relational data model2. Network data model3. Hierarchical data model

Relational data model: It represents data and relationships among data by a collection of tables known as relations, each of which has a number of columns with unique names.

Relation: A table with rows and columns.

Tuple: The row of a table (Relation).

Attributes: The column of a table (Relation).Degree: The number of attributes in a relation.

Cardinality: The number of tuples (rows) in a relation.

View: A view is a (Virtual) table that does not really exist in its own right but is instead derived from one or more existing base tables.

Primary Key: A Primary Key is a set of one or more attributes that can uniquely identify tuples within the relation.

Candidate Key: All attribute combinations inside a relation that can serve as Primary key are Candidate 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.

Relational algebra:

189

Page 175: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

It is a new collection of operations on relations. Each operation takes one or more relations as its operand and produces another relation as its result. The operations defined in relational algebra include: select, project, Cartesian product, union, set difference, set intersection, natural join, division etc.

The Select operation: The select operation selects tuples(horizontal subset) from a relation that satisfy a given predicate. The selection is denoted by lowercase Greek letter sigma σ.

The project operation:The project operation yields a “vertical” subset of a given relation. That is, the projection lets you select the specified attributes in a specified order. It is denoted by Greek letter pi Π.

The Cartesian product operation:The Cartesian product is a binary operation and is denoted by a cross(X).The Cartesian product of two relations A and B is written as AxB. The Cartesian product yields a new relation which has a degree (no: of attributes) equal to sum of the degrees of 2 relations operated upon. It yields a relation with all possible combinations of the tuples of the two relations operated upon.

The Union operation:The union operation is a binary operation that requires two relations as its operands. It produces a third relation that contains tuples from both the operand relation. Union operation is denoted by U.

The set difference operation:The set difference operation is denoted by –(minus)allows us to find the tuples that are in one relation but not in another. The expression A-B results in a relation containing those tuples in A but not in B.

The set intersection operation:The set intersection operation finds tuples that are common to the two operand relations.The set intersection operation is denoted by ∩

190

Page 176: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

SOLVED PROBLEMS

1 mark questions

1) Define the following terms Database: A Database is a collection of interrelated data stored together.

DBMS: Database Management System. It is basically a computer based record keeping system to manage the database.Relation : A Table with rows and columnsTuple : The row of a Table (Relation) Attributes : The column of Table (Relation)Degree : The number of attributes in a relation.Cardinality: The number of tuples (rows) in a relation.

Relational Data Model: It represents data and relationships among data by a collection of tables known as relations, each of which has a number of columns with unique names.

View : A view is a (Virtual) table that does not really exist in its own right but is instead derived from one or more existing base tables.

Primary Key: A Primary Key is a set of one or more attributes that can uniquely identify tuples within the relation

Candidate Key: All attribute combinations inside a relation that can serve as Primary key are Candidate 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.

Data Redundancy: Duplication of data is known as data redundancy.

2 marks questions

1) What are the advantages of database?Ans)PURPOSE OF DATABASE:

1) Database reduce the data redundancy. 2) Databases can control data inconsistency.3) Databases facilitate sharing of data.4) Database enforce standards.5) Databases can ensure data Security.6) Integrity can be maintained through databases.

2) What is database abstraction?Ans) Database abstraction means that the DBMS does not disclose all the details of data, rather it hides certain details how the data is stored and maintained.

3) What is data independence?

191

Page 177: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

The ability to modify a scheme definition in one level without affecting a scheme definition in the next higher level is called data independence.5 marks questions

1) How many levels of Data Abstraction are there in a Database System and explain them briefly. Ans) Various levels of Data Abstraction in a Database SystemInternal Level (Physical Level)This level Describes how the data is actually stored on the storage medium. At this level complex low-level data structures are described in detail.Conceptual Level This level describes What data are actually stored in the database. It also describes the relationships existing among data. At this level, the database is described logically in terms of simple data-structures.External Level (View Level)This level is concerned with the way the data is viewed by the individual users. Only a part of the database relevant to the user(s) is provided to them through this level.

2) What are the various types of data independence? Ans) There are two levels of Data IndependencePhysical 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. Logical Data Independence : It refers to the ability to modify the scheme followed at the Conceptual level without affecting the scheme followed at the View level.

3) What are the various data models available for database system?Ans) A Data Model is a collection of conceptual tools for describing data, data relationships, data semantics etc.Relational Data Model:It represents data and relationships among data by a collection of tables known as relations, each of which has a number of columns with unique names.Network Data ModelThe Network Model represents data by collection of Records and relationships among data are represented by links which can be viewed as pointers.Hierarchical Data ModelThe Hierarchical Data Model is similar to the network model in the sense that data and relationships among data are represented by records and links respectively. It differs from the Network model, in that the records are organized as collection of TREES rather than arbitrary graphs.

192

Page 178: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Points to remember

A collection of data is referred to as database and a DBMS is a computer based record

keeping system.

Database systems help reduce data redundancy, data inconsistency and facilitate sharing of

data standardization of data and data security.

There are 3 models available in data management-relational, network and hierarchical.

A relational data model organizes the data into tables known as relations.

A view is a virtual table derived from one or more underlying base class.

The relational algebra is a collection of operations on relations. The various operations of

relational algebra are select, project, Cartesian product.

193

Page 179: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

CHAPTER 12

STRUCTURED QUERY LANGUAGE

FORE VIEW

POINTS OF FOCUS

SOLVED PROBLEMS

POINTS TO REMEMBER

194

Page 180: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

FOREVIEW1. General Concepts

1.1. Aadvantages of SQL

1.1.1 D D L : DDL provides commands for defining relation schemas, deleting relations, creating indexes and modifying relation .

1.1.2 D M L:

DML includes data manipulation queries ie, it includeslanguage based on both the relational algebra and the tuple relational calculus. It includes commands to insert ,delete and modify tuples in the database.

1.2. Data Ttypes

1.2.1 Number

1.2.2 Character

1.2.3 Date

1.3. SQL Commands

1.4. SQL Functions

195

Page 181: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS OF FOCUS

SQL :- SQL stands for "Structured Query Language" which is the standard language used to interact with databases. It helps us to create and operate on relational databases which are sets of related information stored in tables.

This is originally called as “sequel” and changed in to “SQL”

Mainly SQL can be divided into DDL and DML(Data Definition language and Data Manipulation Language)

ADVANTAGES OF SQL

1. Embedded Data Manipulation Language:-This is used for general - purpose programming languages like Pascal, C,Cobol etc.

2. View Definition Language:- The DDL also includes commands for defining views.

3. Authorization:-The SQL DDL Includes commands for defining access rights to relations and views.

4. Integrity:-The SQL Provides forms of integrity checking.

5. Transaction Control Statements:-SQL Includes commands for specifying the beginning and ending of the transactions.

DDL and DML

DDL(Data Definition Language) :- DDL provides commands for defining relation schemas, deleting relations, creating indexes and modifying relation schema.

Eg: for DDL Commands :- Create,Drop,Alter commands

DML (Data Manipulation Language):- DML includes data manipulation queries ie, it includes language based on both the relational algebra and the tuple relational calculus. It includes commands to insert ,delete and modify tuples in the database.

Data manipulation Language is a language that enables users to access or manipulate data as organized by the appropriate data model.

Ie, the retreivel of information stored in database the insertion of new information in to the database the deletion of information from the database the modification of data stored in the database

Eg: for DML commands Select,Insert,Update etc

DATATYPES

In SQL each field is distinguished with the help of data type that indicates the type of value the field will contain.

196

Page 182: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Data type DescriptionText Char(size) or

CharacterValues of this type should be given in single quotes having max string length size bytes

Varchar(size) Variable Character having max string length size bytes

Varchar2(size) Variable Character having max string length size bytes

Integer Number(p,s)or Dec

Number having precision p and scale s Precision can range from 1 to 38 and scale can range form -84 to 127

Int or integer(size)

It represents a number without decimal point

Float (size) It represents a floating point number in base 10 exp notation

Real Same as float but no size argument is usedDate Date Formats:-yyyy-mm-dd,

yyyy-mm-dd,dd-mm-yyyymm/dd/yyyy

Time Time Formats:-hh-mm-sshh.mm.sshh.mm.AM/PM

SQL Commands

1.CREATE TABLE COMMAND

SYNTAX:- Create table <tablename>(<column name> <datatype>(<size>), <column name> <data type>(size),….);

When we are creating a table its column should be named, data types and sizes should be supplied for each column .Each table must have at least one column

Eg:- syntax for creating student table with 4 columnns

Sql> Create table student (sno integer,sname char(20),sex char(1),addr char(2));

GIVING CONSTRAINTS TO TABLE

A Constraint is a condition or check applicable on a field or set of fields

There are 2 types of constraints

1. Column Level constraints – Applied on a single column2. Table level constraints- Applied on multiple columns

197

Page 183: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Types of Constraints:

1. Unique Constraint :-This ensures that no rows have the same value in the specified column(s)

Syntax:Sql> Create table student (sno integer unique,sname char(20),sex char(1),addr char(2));

Unique constraint applied on sno of student table ensures that no rows have the same sno value

2. Primary key Constraint:-This declares a column as the primary key of the table This is similar to unique constraint except that one column (or one group of columns)can be applied in this constraint .The primary key cannot allow NULL values but Unique key allows for the first time (allows only once)

Syntax:- Create table student (sno integer primary key,sname char(20),sex char(1),addr char(2));

Here all the values of sno will be different for all the tuples in the student relation.Primary key uniquely identifies a tuple of a relation

3. Default constraint:-A default value can be specified for a column using the default

clause .when a user does not enter a value for the column (having default value)automatically the defined default value is inserted in the field

Syntax:- Create table student(sno integer primary key, sname char(20),sex char(1),addr char(2) default=’A’);If no value is provided for addr the default value ‘A’ will be entered

4. Check constraint:-This constraint limits values that can be inserted into a column of a tableSyntax:- Create table student(sno integer primary key, sname char(20),sex char(1),addr char(2) default=’A’,mark decimal check(mark>80));This statement ensures that the value inserted for mark must be greater than 80

1.use of ‘IN’ desc char(20) check (desc in(‘nut’,’bolt’,’screw’))2.use of ‘BETWEEN’ price decimal check(price BETWEEN 253.00 and 770.00)3.use of ‘LIKE’ordate char(10) Not null Check(ordate Like ’--/--/----‘)

5. Not null:-This constraint ensures column should not be NULLSyntax:Create table student (sno integer Not null unique, sname char(20),sex char(1),addr char(2));

Multiple constraints can be given by putting space in between them comma should be given at the end of the constraint

198

Page 184: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Table constraint When a constraint to be applied on a group of columns of a table we use tale constraintEg:- Create table student(sno integer , sname char(20),sex char(1),addr char(2) default=’A’, primary key (sno,sname));

2. SELECT COMMAND

A select command can be used to retrieve a subset of rows or columns from one or more tables

Syntax:-SELECT <columnname>[,<columnname>,…] from <tablename>;Eg:-select sno , sname from student;This query displays sno and sname column of student table

To display whole table

Select * from <tablename>Eg:-select * from student;

Elimination of redundant data with DISTINCT keyword

Select DISTINCT <columnname> from <tablename>Eg:-Select Distinct city from Suppliers;

ALL keyword

Select ALL <columnname> from <tablename>Eg:-select all city from suppliers;

If we give ‘ALL’ keyword it will retain multiple rows in the output.

Restricting rows with “WHERE ‘ Clause

The where clause in the select statement specifies the criteria for selection of rows to be returned ie, we can give condition using where clauseSyntax:- select <columnname> from<tablename> WHERE condition;Eg:-Select sno ,sname from student where mark>75;

Use of relational operators in where clause

1. Select * from suppliers where city <> ‘Delhi’; This query will display details of the table where city not equal to Delhi

2. Select sno ,sname from student where (mark=75 or mark=89); This query will display student details having mark 75 or 89 from table student

3. Select sno, sname from student where (grade=’E1’and mark>85); This query will display the details of employee having grade E1 and with gross >2000

4. Condition based on a range select sno,sname from student where mark between 75 and 100;

199

Page 185: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

This query will display the details of students having marks between 75 and 100

5. Condition based on a list select * from suppliers where city not in(‘Delhi’,Mumbai’,’Chennai’); This query will display details of suppliers whose are not in Delhi,Chennai and Mumbai select * from suppliers where city in (‘Calcutta’, ‘Hyderabad’); This query will display the details of suppliers whose are in Calcutta and Hyderabad

6. Condition based on pattern matches

1. select sno,sname from student where sname like ‘A%’; This displays the details of student whose name starts with A

2. Select sno,sname from student where sname like ‘_A%’; This displays the details of employee whose name second letter is A

‘_’ replaces one character while ‘ %’ replaces one or more characters

7. Searching for Null

Null value column can be searched for in a table using IS NULL in the where clause Select Ecode ,ename from EMP where deptno is NULL 8.ORDER BY clause we can sort the results of the query in a specific order using ORDER By clause To arrange the name of the students in ascending order Select * from student ORDER BY sname;

To arrange the name of the students in ascending orderSelect * from student ORDER BY sname desc;

Order by can be used in multiple fieldsSelect * from student ORDER BY sno desc, sname asc ;

9.Performing simple calculations select 4*3 from dual; dual is a dummy table used for calculations

10. to display today’s date Select sysdate from dual;

Aggregate functions

Avg()- to compute average valueSelect avg(gross) from EMP;

200

Page 186: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Min()- to compute minmum valueSelect min(gross) from EMP;

Max()- to compute maximum valueSelect max(gross) from EMP Sum()- to compute total valueSelect sum(gross) from EMP

Count()-to count number of employees in EMP tableSelect count(*) from EMP;

Count(distinct)-to count distinct numberSelect count(distinct city) from EMP;

GROUP BY AND HAVING CLAUSE

The Group by clause is used in select statements to divide table into groups .Grouping can be done by a column name or with aggregate functions in which the aggregate produces a value for each group

Select job,count(*) ,sum(comm) from emp group by job;This calculates the number of employees in each grade and average gross of each grade of employees .

To introduce condition on group by we use having clause for eg:-Select job,count(*) ,sum(comm) from emp group by job having grade=’E4’;This calculates the number of employees in each grade and average gross of each grade of employees whose grade =E4 .

Putting text in the output

Select salesman_name,comm.*100,’%’ from salesman;

In this query we are inserting the symbol ’%’ after comm. By putting in single inverted comma

3.CREATING TABLE FROM EXISTING ONE

syntax:- Create table <tablename> as (select command);eg:- create table EMP1 as(Select Ecode ,ename from EMP where deptno is NULL);

4.INSERT COMMAND

The rows are added to the table using insert commandSyntax:-Insert into <tablename>[<columnlist>] values (<value>,<value>,…);

Eg:- insert into EMP Values( 1,’abc’.’f’);

201

Page 187: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

If we are not specifying columnlist we must give values to all columns of the table if we are specifying the column list then we should give only values to those columns for

eg:- Insert into EMP (ecode,ename)values(1,’abc’);

5.DELETE COMMAND

This is used to delete a row from the table Syntax:-Delete from<tablename> where[<condition>];Eg:-delete from EMP where ename=’abc’;

6.UPDATE COMMAND

we use update command if need to change the values of some or all existing rows.Syntax:-update <tablename> set <columnname>=value where condition;Eg:-update EMP set ename=’CDE’ where ecode=123;

We can use expressions in update command for eg:-Update EMP set gross=gross+900;

We can also use Null values in update command for egUpdate EMP set grade =Null where grade=’E1’;

7.CREATING VIEWS

View is a virtual table with no data and need no space for storage. we can use view as a window to view the details of a table.

Syntax for creating views:-

Create VIEW <viewname> as select statement;Eg:-Create VIEW taxpayee as select * from EMP where gross>8000;

Views contain columns having calculated values like Create VIEW taxpayee (ecode,ename,tax) as select ecode,ename, gross from EMP where gross>8000;

To delete view we use drop view command For eg:- DROP VIEW <viewname>;Drop view taxpayee;

Select statement used in view should not contain ORDER BY,INTO

Some built-in functions:-1. lower() - to convert into lower case eg:- select lower(‘HELLO’) from dual;2.Upper() - to convert in to upper case eg:- select upper(‘hello’) from dual;3.replicate() - to replicate the character given

202

Page 188: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

eg:- select replicate(‘&’,4) from dual; so it will display &&&&4.getdate() - returns the current date5.Substr() -extracts no:of characters from a string eg:- select substr(‘pointer’,3,2) from dual; this will return - in

8.ALTER TABLE COMMAND

Alter table command is used to change the definitions of existing tables like adding columns, deleting columns changing size of column etc

To add new column:-

Syntax:- ALTER TABLE <tablename> ADD <columnname>datatype<size>;Eg:- ALTER TABLE student add mark number(1);

To modify the existing column:-

Syntax:- ALTER TABLE <tablename> modify <columnname>newdatatype<newsize>;Eg:- Alter table student modify sno varchar2(5);

9. DROP TABLE COMMAND

Drop table command is used to delete a table structure. A table with no rows can be deleted . to delete rows we can use delete command

Delete from <tablename> where condition;Delete from student;

After deleting all rows we can delete the table structure using DROP Command

Syntax:- DROP TABLE <tablename>;Drop table student;

SHORT ANSWER QUESTIONS (2 marks)

1. What do you understand by Primary Key and Candidate keys? Ans. A Primary key is a set of one or more attributes that can uniquely identify the tuples within the relation. Candidate keys are the attributes that can serve as a primary key.

2. Differentiate between Data Definition Language and Data Manipulation Language.

Ans. The SQL DDL provides commands for defining relation schemes, deleting relations, creating indexes. Eg. CREATE, DROP, ALTER The SQL DML commands are used to insert, delete, and modify tuples in the database. Eg. INSERT, UPDATE, DELETE

203

Page 189: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

3. Differentiate between SQL commands: DROP TABLE and DROP VIEW.Ans. The DROP TABLE command deletes a table, whereas the DROP VIEW deletes view. The DROP TABLE will work on empty table only, whereas in the DROP VIEW deletion of rows is not necessary.

4. What are constraints? What are two types of constraint?Ans. A constraint is a condition or check applicable on a field or set of fields. The two basic types of constraints are column constraints and table constraints. The difference between the two is that column constraints apply only to individual columns, whereas table constraints apply to groups of one or more columns.

5. Compare DISTINCT and ALL Keywords when used with SELECT command.Ans. DISTINCT Keyword in SELECT statement will not include duplicate rows but ALL keyword include all the duplicate rows.

6. What is the condition of dropping table?Ans. Drop table command is used to delete a table structure. Drop table command execute only on empty table. To remove the content DELETE command is used.

7. What is the difference between the working of following functions?count(*), count (<column name>), count(DISTINCT), count(ALL)Ans. count(*) - to count total number of rows in a table count(<column name>) – to count number of values in a column

count(DISTINCT) – to count unique values in a column count(ALL) – to count the number of value in a column (includes repeating values)

8. What is the difference between WHERE and HAVING clause?Ans. The HAVING clause places conditions on groups in contrast to WHERE clause that places conditions on individual rows. WHERE conditions cannot include aggregate functions, HAVING conditions can do so.

9. Difference between char(n) and varchar2(n).Ans. char data type declare the variable as fixed length whereas varchar2 declares variable as variable length. When a column is given a data type as char(n), then ORACLE ensures that all values stored in that columns have this length i.e n bytes. If a value is shorter than this length i.e n blanks are added. But the size of value remains n bytes.

10. Difference between VIEW and TABLE.Ans. View is a virtual table that doesn’t have existence of its own. It takes data from the base table using SELECT command. A table is relation that has physical existence of its own and is used to store data.

11. What is the difference between unique constraint and primary key constraint?Ans. Unique key constraint ensures that no two rows have the same value in the specified columns similar to primary key but primary key cannot allow NULL values. A table can have only one primary key but Unique key can be more than one.

12. What is the use of ORDER BY clause? Ans.Use of ORDER BY clause:- Results of SQL query can be sorted in a specific order using ORDER BY clause The ORDER BY clause allows sorting of query results by one or more columns

204

Page 190: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

The sorting can be done either in ascending or descending order

LONG ANSWER TYPE QUESTIONS (4 marks)

1. Consider the following tables GAMES and PLAYER. Write SQL commands for the statement (i) to (iv) and give outputs for SQL queries (v) to (vii).

Table: GAMES

GCode GameName NoOfParticipant PrizeMoney ScheduleDate101 Carom Board 2 5000 23-Jan-2004102 Badminton 2 12000 12-Dec-2003103 Table Tennis 4 8000 14-Feb-2004104 Chess 2 9000 01-Jan-2004108 Lawn Tennis 4 25000 19-Mar-2004

Table: PLAYERPCode Name GCode1 Nabi Ahmad 1012 Ravi Sahai 1083 Jatin 1014 Nazneen 103

(i) To display the name of all Games with their GCodes.Ans. Select GCode, GameName from GAMES;(ii) To display details of those games which are having PrizeMoney more than

7000.Ans. Select * from GAMES where PrizeMoney > 7000;(iii) To display the content of the GAMES table in ascending order of

ScheduleDate.Ans. Select * from GAMES order by ScheduleDate ASC;(iv) To display sum of PrizeMoney for each of the Number of participation

groupings. Ans Select sum(PrizeMoney) from Games group by NoOfParticipant;

(v) Select count (Distinct NoOfParticipant) from GAMES.Ans. COUNT(Distinct NoOfParticipant) 2

(vi) Select Max(ScheduleDate), Min(ScheduleDate) from GAMES.Ans. Max(ScheduleDate) Min(ScheduleDate) 19-Mar-2004 12-Dec-2003

(vii) Select Sum(PrizeMoney) from GAMES.Ans. Sum(PrizeMoney 59000

(viii) Select distinct GCode from PLAYER.

205

Page 191: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

DISTINCT GCode 101

103 108

2. Study the following tables DOCTOR and SALARY and write SQL commands for the questions (i) to (iv) and give outputs for SQL queries (v) to (vi).

TABLE: DOCTORID NAME DEPT SEX EXPERIENCE101 John ENT M 12104 Smith ORTHOPEDIC M 5107 George CARDIOLOGY M 10114 Lara SKIN F 3109 K George MEDICINE F 9105 Johnson ORTHOPEDIC M 10117 Lucy ENT F 3111 Bill MEDICINE F 12130 Morphy ORTHOPEDIC M 15

TABLE: SALARYID BASIC ALLOWANCE CONSULTATION101 12000 1000 300104 23000 2300 500107 32000 4000 500114 12000 5200 100109 42000 1700 200105 18900 1690 300130 21700 2600 300

(i) Display Name of all doctors who are in “MEDICINE” having more than 10 years experience from the table DOCTOR.

Ans. Select Name from DOCTOR where DEPT= “MEDICINE” and EXPERIENCE>10;

(ii) Display the average salary of all doctors working in “ENT” department using the tables DOCTOR and SALARY. Salary= BASIC + ALLOWANCE.

Ans. Select avg(S.BASIC + S.ALLOWANCE) , D.DEPT from DOCTOR D, SALARY S where D.ID= S.ID;

(iii) Display the minimum ALLOWANCE of female doctors.Ans. Select min(S.ALLOWANCE) from DOCTOR D,SALARY S where D.SEX= “F”

and D.ID=S.ID;(iv) Display the highest consultation fee among all male doctors.

206

Page 192: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Ans. Select max(S.Consultation) from DOCTOR D, SALARY S where D.Sex=”M” and D.ID=S.ID;

(v) Select count(*) from DOCTOR where SEX = “F”.Ans. COUNT(*)

4(vi) Select NAME, DEPT, BASIC from DOCTOR, SALARY where DEPT= ‘ENT’

and DOCTOR.ID= SALARY.ID.Ans. NAME DEPT BASIC John ENT 12000

3. Study the following table CLUB and ACTIVITY and write SQL commands for questions (i) to (iv) and give outputs for SQL queries (v) to (vi):

Table: CLUBMcode Mname Sex Age Fees Activity_code Type1 Granth Male 35 7000 A001 Monthly2 Ananya Female 25 8000 A003 Monthly3 Triveni Female 42 24000 A001 Yearly4 Hansia Female 27 12000 A001 Quarterly5 Tarun Male 54 6000 A002 Monthly6 Mani Male 43 4500 A002 Monthly7 Farah Female 22 500 A005 Guest8 Vipin Male 51 24000 A002 Yearly9 Harshan Male 44 1000000 A003 Life Time

Table: ActivityActivity_code Activity_nameA001 SwimmingA002 CricketA003 SkatingA004 Table tennisA005 Badminton

i. Display the Mname, Age and Fees of those members of the CLUB whose Fees is between 6000 to 10000.

Ans. Select Mname, Age, fees from CLUB where Fees between 6000 and 10000;ii. Display Mname, fees and activity_name of all Female of the CLUB with Mname in

ascending order.Ans. Select C.Mname, C.Fees, A.Activity_Name from CLUB C, ACITIVITY A where C.SEX=”Female” and C.Activity_Code= A. Activity_Code;

iii. Display Mname, Fees of all those members of the CLUB whose age< 40 and are Monthly type members of the CLUB.

Ans. Select Mname, Fees from Club where age<40 and Type=”Monthly”;iv. To insert a new tuple in the table CLUB with the following data:

11, “Keshav”, “Male”, 27, 600, “Guest”Ans. Insert Into CLUB (Mcode,MName, Age, Fees, Type) VALUES (11, ‘Keshav’, ‘Male’, 27, 600, ‘Guest’)

v. Select Sum(Fees) from CLUB where age> 40.Ans. Sum(Fees)

1058500

207

Page 193: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

vi.Select avg(age) from CLUB where type= “Yearly”

Ans. AVG(age) 46.5

4. Table: SPORTS

i.Display the name of the students who have grade1 C Ans. Select STUDENT NAME from SPORTS where grade1=”C” ;ii.Display the number of students getting grade1 A in Cricket.Ans. Select count(distinct STUDENT NAME) from SPORTS where GRADE1=’A’ and Game1=’Cricket’orGame2=’Cricket’;iii.Display the names of the students who have same game for both game 1and game2Ans. Select STUDENT NAME from SPORTS where game1=game2;iv. Display the game taken up by the students whose name starts with AAns.Select Game1,Game2 from SPORTS where Game1=’A%’ or Game2=’A%’;v.Add a new column named ‘marks’Ans.Alter Table SPORTS add marks number(3);vi. Assign a value 200 for ‘marks’ for those who are getting Grade A in both game 1 and game 2

STUDENT NO

CLASS STUDENT NAME

GAME1 GRADE1 GAME 2 GRADE2

10 7 Sammer Cricket B Swimming A

11 8 Sujit Tennis A Skating C

12 7 Kamal Swimming B Football B

13 7 Venna Tennis C Tennis A

14 9 Archana Basketball A Cricket A

15 10 Arpit Cricket A Athletics C

208

Page 194: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Ans.update Sports set marks=200 where grade1=’A’ and Grade2=’A’;

vii. Arrange the whole table in the Alphabetical order of the name.Ans:Select * from sports where Order by STUDENT NAME;viii.display the name of the students who got 200 markAns: Select STUDENT NAME from Sports where mark=200;ix Display the names of the students in upper caseAns Select UPPER(STUDENT NAME) From Sports;

POINTS TO REMEMBER:

SQL is a language that enables you to create and operate on relational databases.

The various processing capabilities of SQL are:

data definition language (DDL), interactive and embedded data manipulation language

(DML), view definition, authorization, integrity and transaction control.

The DDL provides statements for the creation and deletion of tables and indexes.

The DML provides statements to enter, update, delete data and perform complex queries on

these tables

The CREATE TABLE command creates a new table.

The SELECT command lets you make queries on the database. Rows returned are restricted

using WHERE clause.

Results are sorted using ORDER BY clause and the GROUP BY clause divides the result

obtained into groups and the HAVING clause sets condition for the GROUP BY clause.

The rows are added to relations using INSERT command

The rows are removed from a relation using DELETE command.

The UPDATE command lets you change some or all of the values in an existing row.

The CREATE VIEW creates view from a table.

The ALTER TABLE changes the definition of an existing table.

209

Page 195: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

The DROP TABLE drops a table from the database

The DROP VIEW drops a view from the database

CHAPTER 13

BOOLEAN ALGEBRA

FORE VIEW

POINTS OF FOCUS

SOLVED EXAMPLES

POINTS TO REMEMBER

210

Page 196: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

FOREVIEW

Truth Table

Truth table is a table which represents all the possible values of logical variables /statements

along with all the possible results of the given combinations of values.

TAUTOLOGY

If result of any logical statement or expression is always TRUE or 1 then it is called

Tautology.

FALLACY

If result of any logical statement or expression is always FALSE or 0, it is called Fallacy.

Logic Gate

A Gate is simply an electronic circuit which operates on one or more signals to produce an

output signal.

Inverter (NOT Gate)

An inverter (NOT gate) is a gate with only one input signal and one output signal. The output

signal is always the opposite of the input state.

OR Gate

The OR Gate has two or more input signals but only one output signal. If anyone input signal

is high (1) then output signal will be high (1).

AND Gate

The AND Gate has two or more input signals but only one output signal. If anyone input

signal is low (0) then output signal will be low otherwise high

211

Page 197: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

PRINCIPLE OF DUALITY

This states that starting with a Boolean relation another Boolean relation can be derived by.

BASIC THEOREMS OF BOOLEAN ALGEBRA

(1) Properties of 0 and 1

(2) Indempotence Law

(3) Involution

(4) Complementarity Law

(5) Commutative Law

(6) The Associative Law

(7) The Distributive Law

(8) Absorption law

DEMORGAN’S THEOREMS

Minterms

Minterms is a product of all the literals (with or without the bar) within the logic system.

Maxterms

Maxterm is a sum of all the literals (with or without the bar) within the logic system.

Canonical Expression

Boolean expression composed entirely either of minterms or Maxterm is referred to as

canonical expression. Canonical expression can be represented in two forms:

Canonical Sum of Products form

When a Boolean expression is represented purely as sum of minterms (Product terms), it is

said to be canonical Sum of Product form.

Karnaugh map

Karnaugh map or K – map is a graphical display of the fundamental products in a truth table.

K – Map is nothing but a rectangle made up of certain number of squares represents a Maxterm

or minterm.

NAND and NOR Gates

NAND and NOR gates can greatly simplify circuit diagrams. As we will see you can use

these gates wherever you could use AND, OR, and NOT.

XOR and XNOR Gates

XOR is used to choose between two mutually exclusive inputs. Unlike OR, XOR is true

only when one input or the other is true, not both

212

Page 198: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS OF FOCUSBOOLEAN ALGEBRA

TRUTH TABLE

Truth table is a table which represents all the possible values of logical variables /statements

along with all the possible results of the given combinations of values.

Eg:

X Y R

1 1 1

1 0 0

0 1 0

0 0 0

1 represents TRUE and 0 represents FALSE.

TAUTOLOGY

If result of any logical statement or expression is always TRUE or 1, it is called Tautology.

FALLACY

If result of any logical statement or expression is always FALSE or 0, it is called Fallacy.

NOT OPERATOR

This Operator operates on single varibles.

Truth Table

213

Page 199: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

X R

0 0

1 1

OR OPERATOR

Operator denotes operation called logical addition.

X Y X+ Y

0 0 0

0 1 1

1 0 1

1 1 1

AND OPERATOR

AND Operator denotes operation called logical Multiplication.

X Y X . Y

0 0 0

0 1 0

1 0 0

1 1 1

Evaluation of Boolean Expressions Using Truth Table.

1. X + (Y.Z)’

X Y Z Y.Z (Y.Z)’ X+(Y.Z)’

0 0 0 0 1 1

0 0 1 0 1 1

0 1 0 0 1 1

0 1 1 1 0 0

1 0 0 0 1 1

1 0 1 0 1 1

1 1 0 0 1 1

1 1 1 1 0 1

214

Page 200: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

BASIC LOGIC GATES

Logic Gate

A Gate is simply an electronic circuit which operates on one or more signals to produce an

output signal.

There are three types of logic gates:-

1. Inverter (NOT Gate)

2. OR gate

3. AND gate

Inverter (NOT Gate)

An inverter (NOT gate) is a gate with only one input signal and one output signal. The output

signal is always the opposite of the input state.

Truth Table of NOT Gate

X X’

0 0

1 1

NOT Gate Symbol

OR Gate

The OR Gate has two or more input signals but only one output signal. If anyone input signal

is high (1) then output signal will be high (1).

X Y X+ Y

0 0 0

0 1 1

1 0 1

1 1 1

OR Gate Symbol

215

Page 201: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

AND Gate

The AND Gate has two or more input signals but only one output signal. If anyone input

signal is low (0) then output signal will be low otherwise high

X Y X. Y

0 0 0

0 1 0

1 0 0

1 1 1

AND Gate Symbol

BASIC POSTULATES OF BOOLEAN ALGEBRA

I. If x != 0 then x=1 and if x!=1 then x=0

II. OR Relations (logical Addition)

0 + 0 = 0

0 + 1 = 1

1 + 0 = 1

1 + 1 = 1

III. AND Relations (Logical Multiplication)

0 . 0 = 0

0 . 1 = 1

1 . 0 = 1

216

Page 202: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

1 . 1 = 1

IV. Complement rules

0’ = 1

1’ = 0

PRINCIPLE OF DUALITY

This states that starting with a Boolean relation another Boolean relation can be derived by

1. Changing each OR sign to an AND sign.

2. Changing each AND sign to OR sign.

3. Replacing each 0 by 1 and each 1 by 0.

The derived relation using duality principal is called dual of original expression.

BASIC THEOREMS OF BOOLEAN ALGEBRA

(1) Properties of 0 and 1

(a) 0 + X = X

(b) 1 + X = 1

(c) 0 . X = 0

(d) 1. X = X

(2) Indempotence Law

(a) X + X = X

(b) X . X = X

Proof

(a) X + X = X

X X R

0 0 0

1 1 1

Proof

(b) X . X = X

X X R

0 0 0

1 1 1

(3) Involution

X’’ = X

Proof

217

Page 203: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

X X’ X’’

0 1 0

1 0 1

(9) Complementarity Law

(a) X + X’ = 1

(b) X . X’ = 0

Proof

X X’ X+X’

0 1 1

1 0 1

X X’ X.X’

0 1 0

1 0 0

(10) Commutative Law

i. X + Y= Y + X

X Y X + Y Y + X

0 0 0 0

0 1 1 1

1 0 1 1

1 1 1 1

ii. X.Y = Y. X

X Y X.Y Y.X

0 0 0 0

0 1 0 0

1 0 0 0

1 1 1 1

(11) The Associative Law

218

Page 204: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

(i) X + (Y + Z) = (X + Y) + Z (ii) X(YZ) =(XY)Z

Truth table for X+(Y+Z) = (X+Y)+Z is given below :

Input Output

X Y Z Y+Z X+Y X+(Y+Z) (X+Y)+Z

0 0 0

0 0 1

0 1 0

0 1 1

1 0 0

1 0 1

1 1 0

1 1 1

0

1

1

1

0

1

1

1

0

0

1

1

1

1

1

1

0

1

1

1

1

1

1

1

0

1

1

1

1

1

1

1

Comparing the columns X+(Y+Z) and (X+Y)+Z, we see both of these are identical, Hence

proved. Since (i) is proved, (ii) is dual of rule (ii), hence it is also proved.

(12) The Distributive Law

(i) X(Y+Z) = XY+XZ (ii) X+YZ =(X+Y)(X+Z)

Truth table for X(Y+Z) = XY+XZ are given below:

Input Output

X Y Z Y+Z XY XZ X(Y+Z) XY+XZ

0 0 0

0 0 1

0 1 0

0 1 1

1 0 0

1 0 1

0

1

1

1

0

1

0

0

0

0

0

0

0

0

0

0

0

1

0

0

0

0

0

1

0

0

0

0

0

1

219

Page 205: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

1 1 0

1 1 1

1

1

1

1

0

1

1

1

1

1

Both the columns X(Y+Z) and XY+YZ are identical, hence proved.

The algebraic proof of law X+YZ=(X+Y)(X+Z)

RHS = (X+Y)(X+Z)

=XX+XZ+XY+YZ

=X+XZ+XY+YZ

=X+XY+XZ+YZ

=X(1+Y)+Z(X+Y)

=X.1+Z(X+Y)

=X+XZ+YZ=X(1+Z)+YZ

=X +YZ

= LHS, Hence proved.

Eg: State Distributive law and verify the same using truth table.

Ans. 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

220

Page 206: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

(13) Absorption law

(i) X+XY = X (ii) X(X+Y) =X

(i) Truth table for X+XY = X is given below :

Input Output

X Y XY X+XY

0 0

0 1

1 0

1 1

0

0

0

1

0

0

1

1

Both the columns X+XY and X are identical, hence proved.

(ii) Truth table for X.(X+Y) = X is given below :

Input Output

X Y X+Y X(X+Y)

0 0

0 1

1 0

1 1

0

1

1

1

0

0

1

1

Column X and X(X+Y) are identical, hence proved.

DEMORGAN’S THEOREMS

1. Demorgan’s First Theorem

221

Page 207: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

(X+Y)’ = X’Y’

Proof

(X+Y)+(X’Y’) = 1

(X+Y)+X’Y’=((X+Y)+X’).((X+Y)+Y’)

= (X+X’+Y).(X+Y+Y’)

= (1+Y).(X+1)

= 1.1

= 1

(X+Y).(X’Y’) = 0

(X+Y).(X’Y’) = X’Y’.(X+Y)

= X’Y’X+X’Y’Y

= 0.Y+X’.0

= 0

Hence proved

2. Demorgan’s Second Theorem

(X.Y)’ = X’+Y’

Proof

XY + (X’+Y’) = 1

=(X’+Y’)+XY

=(X’+Y’+X).(X’+Y’+Y)

=(X+X’+Y’).(X’+Y+Y’)

=(1+Y’).(X’+1)

=1.1

=1

XY. (X’+Y’) = 0

= XY.( X’+Y’) ->X(Y+Z)=XY+XZ

= XYX’+XYY’

= 0.Y+X.0

= 0+0

= 0

Note:- Find the dual of the following expression.

(X+Y)+Z=X+(Y+Z)

The dual is (X.Y).Z=X.(Y.Z)

222

Page 208: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Derivation of Boolean expression

1) Minterms

Minterms is a product of all the literals (with or without the bar) within the logic system.

Example: Convert X+Y to minterm

X+Y

= X.1+Y.1 (Because X.1 = X)

= X.(Y+Y’)+Y.(X+X’) (Because X+X’ = 1)

= XY+XY’+XY+X’Y By Distributive law

= XY+XY’+X’Y (Because X+X = X)

2) Maxterms

Maxterm is a sum of all the literals (with or without the bar) within the logic system.

Example:

If the value of the variables are X=0, Y=1 and Z=1 then the Maxterm will be X+Y’+Z’

3) Canonical Expression

Boolean expression composed entirely either of minterms or Maxterm is referred to as

canonical expression. Canonical expression can be represented in two forms:

i) Sum – of – Products (SOP) form

ii) Product – of – Sum (POS) form

Canonical Sum of Products form

When a Boolean expression is represented purely as sum of minterms (Product terms), it

is said to be canonical Sum of Product form.

Truth table for Product Terms (3 input)

X Y Z Product

Terms/

Minterms

0 0 0 X’Y’Z’

0 0 1 X’Y’Z

0 1 0 X’YZ’

0 1 1 X’YZ

1 0 0 XY’Z’

1 0 1 XY’Z

223

Page 209: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

1 1 0 XYZ’

1 1 1 XYZ

Canonical sum of products expression can also be represented by the following Short hand

notation.

Example: - F=∑(1,4,5,6,7)

= m1 + m4 + m5 + m6 + m7

= 001 + 100 + 101 + 110 + 111 (Boolean values for decimal numbers)

= X’Y’Z + XY’Z’+ XY’Z+XYZ’+XYZ

Canonical Product of sum form

When a Boolean expression is represented purely as product of maxterms, it is said to be

in canonical Product of Sum form of expression.

Truth table for Sum Terms (3 input)

X Y Z Sum Terms/

Maxterms

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’

Canonical product of sum expression can also be represented by the following Short hand

notation.

Example(1): - F=∏ (1,4,5,6,7)

=M1 . M4. M5. M6.M7

= 001 + 100 + 101 + 110 + 111 (Boolean values for decimal numbers)

= (X+Y+Z’)( X’+Y+Z)( X’+Y+Z’)( X’+Y’+Z)( X’+Y’+Z’)

Minimization of Boolean expression

1) Algebraic method

Example : - Reduce X’Y’Z’ + X’YZ’ + XY’Z’ + XYZ’

= X’(Y’Z’ + YZ’) + X(Y’Z’+YZ’)

=X’(Z’(Y’+Y)) + X(Z’(Y’+Y))

224

Page 210: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

=X’(Z’.1)+X(Z’.1)

=X’Z’+XZ’

=Z’(X’+X’)

=Z’.1

=Z’

2) Simplification using karnaugh maps

Karnaugh map

Karnaugh map or K – map is a graphical display of the fundamental products in a truth table.

K – Map is nothing but a rectangle made up of certain number of squares represents a Maxterm

or minterm

SOP reduction using K-maps

For a function of n variables, there would be a map of 2n squares each represents a minterm.

Following are two, three, four variables k-maps for SOP reduction.

Two variables

Y’ Y

X’

X

Three variables

Y’Z’ Y’Z YZ YZ’

X’

X

Four variables

X’Y’ 0 X’Y 1

XY’ 2 XY 3

X’Y’Z’ 0

X’Y’Z 1

X’YZ 3

X’YZ’ 2

XY’Z’

4

XY’Z

5

XYZ

7

XYZ’

6

225

Page 211: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Y’Z’ Y’Z YZ YZ’

W’X’

W’X

WX

WX’

Example:

1) Reduce the following Boolean expression using K-Map

F(U,V,W,Z) = ∑ (0, 1, 2, 3, 4, 10, 11)

Ans.

2) Obtain the simplified form of a boolean expression using Karnaugh map.

F(U,V,W,X) = ∑ (0,3, 4, 5, 7, 11, 13, 15)

[00]W’Z’ [01] W’Z [11]WZ [10]WZ’

W’X’Y’Z’

0

W’X’Y’Z

1

W’X’YZ

3

W’X’YZ’

2

W’XY’Z’

4

W’XY’Z

5

W’XYZ

7

W’XYZ’

6

WXY’Z’

12

WXY’Z

13

WXYZ

15

WXYZ’

14

WX’Y’Z’

8

WX’Y’Z

9

WX’YZ

11

WX’YZ’

10

226

Page 212: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

1 1

1 1 1

1 1

1

2 quads, 1 pair.

Quad 1(m3+m7+m11+m15) reduces to WZ

Quad 2(m5+m7+m13+m15) reduces to VZ

Pair 1(m0,m4) reduces to U’W’Z’

Therefore F=WZ + VZ + U’W’Z’

POS reduction using K-maps : -

For a function of n variables, there would be a map of 2n squares each represents a maxterm.

Following are two, three, four variables k-maps for POS reduction.

Two variables

Y Y’

X

X’

Three variables Y+Z Y+Z’ Y’+Z’ Y’+Z

X

X’

X+Y

0

X+Y’

1

X’+Y

2

X’+Y’

3

X+Y+Z 0

X+Y+Z’ 1

X+Y’+Z’ 3

X+Y’+Z 2

X’+Y+Z

4

X’+Y+Z’

5

X’+Y’+Z’

7

X’+Y’+Z

6

227[00] U’V’

[01] U’V

[11] UV

[00] UV’

Page 213: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Four variables

Y+Z Y+Z’ Y’+Z’ Y’+Z

W+X

W+X’

W’+X’

W’+X

More about Logic Gates

NAND and NOR Gates

NAND and NOR gates can greatly simplify circuit diagrams. As we will see you can use

these gates wherever you could use AND, OR, and NOT.

NAND Gate:-

The NAND gate has two or more input signals but only one output signal. If all of the inputs

are (high), then the output produced is 0 (low).

NAND

NOR Gates:-

W+X+Y+Z 0

W+X+Y+Z’ 1

W+X+Y’+Z’ 3

W+X+Y’+Z 2

W+X’+Y+Z 4

W+X’+Y+Z’ 5

W+X’+Y’+Z’ 7

W+X’+Y’+Z 6

W’+X’+Y+Z 12

W’+X’+Y+Z’ 13

W’+X’+Y’+Z’ 15

W’+X’+Y’+Z 14

W’+X+Y+Z 8

W’+X+Y+Z’ 9

W’+X+Y’+Z’ 11

W’+X+Y’+Z 10

228

001111110011111100110000

AABBBBAA

Page 214: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

The NOR gates has two or more input signals but only one output signal. If all inputs are 0

(i.e., low), then the output signal is 1 (high).

NOR

XOR and XNOR Gates

XOR is used to choose between two mutually exclusive inputs. Unlike OR, XOR is true only when

one input or the other is true, not both

XOR Gate (Exclusive OR gate):-

The XOR gate can also have two or more inputs but produces one output signal. Exclusive-

OR gate different from OR gate. OR gate produces output 1 for any input combination having

one or more 1’s, but XOR gate produces output 1 for only those input combinations that have

odd number 1’s.

XOR

XNOR Gate (Exclusive NOR gate)

The XNOR Gate is logically equivalent to an inverted XOR i.e., XOR gate followed by a

NOT gate (inventor). Thus XNOR produces 1 (high) output when the input combination has

even number of 1’s.

A B AÅB

0 0 0

0 1 1

1 0 1

1 1 0

229

001111000011001100110000

AABBBBAA

Page 215: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

XNOR

SOLVED PROBLEMS

1 mark Questions

1) Why are AND and NOR gates called Universal gates? (1)

Ans. NAND and NOR gates are less expensive and easier to design. Also, other switching

functions (AND, OR) can easily be implemented using NAND/NOR gates. Thus, these

(NAND, NOR) gates are also reffered to as Universal Gates.

(2) Write the Sum of Products form of the function G(U,V,W). Truth table representation

of G is as follows: (1)

U V W G

0 0 0 0

0 0 1 0

0 1 0 1

0 1 1 0

1 0 0 1

1 0 1 0

1 1 0 1

1 1 1 1

A B A B

0 0 1

0 1 0

1 0 0

1 1 1

230

Page 216: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Ans. To get the product of sums form, we need to add maxterms for all those input combinations

that produce output as 0. Thus ,

G(U,V,W) = (U + V + W) (U + V + W’) (U + V’ + W’) (U’ + V + W’)

(3) Convert P+Q’R to product of sum

Ans:

P+Q’R=(P+Q’) (P+R’) [ by the rule A+BC= (A+B)(A+C)

=(P+Q’+RR’) ( P+QQ’+R) [ by the rule AA’=0

= (P+Q’+R) (P+Q’+R’) (P+Q+R) (P+Q’+R) [ by the rule A+BC= (A+B)(A+C)

(4) Concert X+YZ into sum of product

Ans:

X+YZ=X.1+YZ.1 [by the rule A.1=A

= X(Y+Y’)+YZ(X+X’) [ by the rule A+A’=1

=XY+XY’+YZX+YZX’

=XY.1+XY’.1+XYZ+YZX’ [by the rule A.1=A

=XY(Z+Z’)+XY’(Z+Z’)+XYZ+X’YZ [ by the rule A+A’=1

=XYZ+XYZ’+XY’Z+XY’Z’+XYZ+X’YZ

2 marks Questions

(1) Write the equivalent Boolean Expression for the following Logic circuit.

(2)

231

Page 217: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

2) Prove that X.(X+Y)=X by truth table method. (2)

Ans.

X Y X+Y X.(X+Y)

0 0 0 0

0 1 1 0

1 0 1 1

1 1 1 1

From the above table it is obvious that X.(X+Y) = X because both the columns are identical.

3) Prove that X.(X+Y)=X by algebric method (2)

Ans. LHS = X.(X+Y)

= X.X+X.Y

=X+X.Y

=X.(1+Y)

=X.1 = X = RHS

232

Page 218: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

4) State the distributive laws of Boolean algebra. How are they different from distributive

laws of ordinary algebra. (2)

Ans. Distributive laws of Boolean algebra state that

i. X(Y+Z) = XY+XZ

ii. X+YZ =(X+Y)(X+Z)

Ist law X(Y+Z) = XY+XZ holds good for all values of X, Y and Z in ordinary algebra

whereas X+YZ =(X+Y)(X+Z) holds good only for two values (0,1) of X, Y and Z.

5) In Boolean algebra, verify using truth table that (X + Y)’ = X’ Y’ for each X, Y in (0, 1).

(2)

Ans. As it is a 2-variable expression, truth table will be as follows :

X Y X+Y (X+Y)’ X’ Y’ X’Y’

0 0 0 1 1 1 1

0 1 1 0 1 0 0

1 0 1 0 0 1 0

1 1 1 0 0 0 0

6) State Demorgan’s laws. Verify one of the Demorgan’s laws using truth tables. (2)

Ans. De Morgan’s first theorem. It states that X + Y = X . Y

De Morgan’s second theorem. It states that X . Y = X + Y

Truth table for second theorem

X Y X.Y X.Y X Y X+Y

0 0 0 1 1 1 1

0

1

1

0

0

0

1

1

1

0

0

1

1

1

233

Page 219: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

1 1 1 0 0 0 0

X.Y and X+Y are identical.

7) Draw the logic circuit diagram for the following expression : (2)

Y = a b + b c + c a

8) Prepare a truth table for X’ Y Z’ + X Y’ (2)

Ans. Truth table for is given below :

(9) Write the equivalent expression for the following logic circuit : (2)

Input Output

X Y Z X’ Y’ Z’ X’YZ’ XY’ X’YZ’ + XY’

0 0 0

0 0 1

0 1 0

0 1 1

1 0 0

1 0 1

1 1 0

1 1 1

1

1

1

1

0

0

0

0

1

1

0

0

1

1

0

0

1

0

1

0

1

0

1

0

0

0

1

0

0

0

0

0

0

0

0

0

1

1

0

0

0

0

1

0

1

1

0

0

234

Page 220: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Ans. F=(AC)’ +(BA)’+(BC)’

(10) Write the equivalent expression for the following logic circuit: (2)

Ans. (X + Y’)(X’ + Y)(X’ + Y’)

4 marks Questions

(1) Obtain the simplified form of a boolean expression using Karnaugh map. (4)

F(u,v,w,x) = ∑ (0, 3, 4, 5, 7, 11, 13, 15)

[00]W Z [01] W Z [11]W Z [10]W Z

1 1

1 1 1

235

[00] U V

[01] U V

[11] U V

[00] U V

Page 221: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

1 1

1

2 quads, 1 pair.

Quad 1(m3+m7+m11+m15) reduces to WZ

Quad 2(m5+m7+m13+m15) reduces to VZ

Pair 1(m0,m4) reduces to UWZ

Therefore F=WZ + VZ + UWZ

9) By means of truth table, demonstrate the validity of the following Postulates / Laws of

Boolean algebra: (4)

a. Commulative law

b. Idempotent law

Ans.

(a) The commulative law states that

(i) X+Y = Y+X (ii) X.Y =Y.X

(i) Truth table for X+Y = Y+X is given below :

Input Output

X Y X+Y Y+X

0 0 0 0

0 1 1 1

1 0 1 1

1 1 1 1

Comparing the columns X+Y and Y+X, we see both of these are identical. Hence proved.

(ii) Truth table for X.Y = Y.X is given below:

Input Output

236

Page 222: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

X Y X.Y Y.X

0 0 0 0

0 1 0 0

1 0 0 0

1 1 1 1

Comparing the columns X.Y and Y.X, we see both of these are identical. Hence proved.

(b) The Idempotent law states that

(i) X+X = X ii) X.X =X

(i) Truth table for X+X = X is given below :

Input Output

X X X+X

0 0

1 1

0

1

(ii) Truth table for X.X = X is given below :

Input Output

X X X.X

0 0

1 1

0

1

POINTS TO REMEMBER

Binary Decision

237

Page 223: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Logical Statements

TRUTH TABLE :-Truth table is a table which represents all the possible values of logical

variables /statements along with all the possible results of the given combinations of values

TAUTOLOGY:-If result of any logical statement or expression is always TRUE or 1, it is

called Tautology.

FALLACY : - If result of any logical statement or expression is always FALSE or 0, it is

called Fallacy.

PRINCIPLE OF DUALITY

This states that starting with a Boolean relation another Boolean relation can be derived by

1. Changing each OR sign to an AND sign.

2. Changing each AND sign to OR sign.

3. Replacing each 0 by 1 and each 1 by 0.

The derived relation using duality principal is called dual of original expression.

BASIC THEOREMS OF BOOLEAN ALGEBRA

(4) Properties of 0 and 1

(5) 0+x=x

(6) 1+x=1

(7) 0.x=0

(8) 1.x=x

(9) Indempotence law

(a) x+x=x

(b) x.x=x

Involution

x’’=x

Complementarity law

(a) x+x’=1

(b) x.x’= 0

Cummtative law

x + y= y+x

The associative law

(i) X+(Y+Z) = (X+Y)+Z (ii) X(YZ) =(XY)Z

The distributive law

238

Page 224: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

(i) X(Y+Z) = XY+XZ (ii) X+YZ =(X+Y)(X+Z)

Absorption law

(i) X+XY = X (ii) X(X+Y) =X

DEMORGAN’S THEOREMS

(X+Y)’=X’Y’

(X.Y)’=X’+Y’

Minterms: - Minterms is a product of all the literals (with or without the bar) within the

logic system.

Maxterms: - Maxterm is a sum of all the literals (with or without the bar) within the logic

system

Canonical sum of product form:- When a Boolean expression is represented purely as sum

of minterms or product terms, it is said to be canonical sum of product form.

Canonical Product of sum form: - When a Boolean expression is represented purely as

product of maxterms, it is said to be in canonical product of sum form of expression.

NOR Gates:-

The NOR gates has two or more input signals but only one output signal. If all inputs are 0

(i.e., low), then the output signal is 1 (high).

NAND Gate:-

The NAND gate has two or more input signals but only one output signal. If all of the inputs

are (high), then the output produced is 0 (low).

XOR Gate (Exclusive OR gate):-

The XOR gate can also have two or more inputs but produces one output signal. Exclusive-

OR gate different from OR gate. OR gate produces output 1 for any input combination having

one or more 1’s, but XOR gate produces output 1 for only those input combinations that have

odd number 1’s.

XNOR Gate (Exclusive NOR gate)

The XNOR Gate is logically equivalent to an inverted XOR i.e., XOR gate followed by a

NOT gate (inventor). Thus XNOR produces 1 (high) output when the input combination has

even number of 1’s.

239

Page 225: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

240

Page 226: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

CHAPTER 14

COMMUNICATION & NETWORK CONCEPTS

FORE VIEW

POINTS OF FOCUS

SOLVED EXAMPLES

POINTS TO REMEMBER

241

Page 227: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

FORE VIEW

Computer Network -computer network is an interconnected collection of devices that enables you to store, retrieve, and share information.

Network interface card handles the connection to the network itself through one or more connectors on the backplane of the card.

A Hub is a multipurpose network device that lies at the centre of a network to channel the traffic from one computer to another.

A Repeater is a network device that boosts the power of incoming signals to allow the length of a network to be extended.

A Bridge is a network device capable of connecting networks that use similar protocols. It connects two local area networks running the same network operating system.

A Router is a network device that connects LAN’s, that may be running on different operating systems, into an inter network and routes traffic between them.

A Gateway forwards data between IP networks. It is a machine that acts as an interface between a small network and a much larger one.

A Backbone is a set of nodes and links connected together comprising a network, or the upper layer protocols used in a network.

Modems provide the means to transmit digital computer data over analog transmission media, such as ordinary, voice-grade telephone lines

On an inter network, data units must be switched through the various intermediate devices until they are delivered to their destination. Two contrasting methods of switching data are commonly used Circuit Switching and Packet Switching.

Circuit-switching a type of network in which a physical path is obtained for and dedicated to a single connection between two end-points in the network for the duration of the connection.

Packet-switching Breaking communication down into packets allows the same data path to be shared among many users in the network.

Twisted-pair wiring refers to a type of cable composed of two (or more) copper wires twisted around each other within a plastic sheath.

This type of cable is referred to as "coaxial" because it contains one copper wire (or physical data channel) that carries the signal and is surrounded by another concentric physical channel consisting of a wire mesh or foil. The outer channel serves as a ground for electrical interference.

242

Page 228: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Optical fiber cable can transmit data over very long distances with little loss in data integrity by the mean of light transmission.

Microwave transmitters and receivers, especially satellite systems, are commonly used to transmit network signals over great distances. A microwave transmitter uses the atmosphere or outer space as the transmission medium to send the signal to a microwave receiver.

Infrared transmit light waves rather than radio waves, they require a line-of-sight transmission path.

Local Area Networks (LAN) is a number of devices (Computers, Printers, Fax) that are connected to each other by some form of wiring, within a localized area (within building e.g. a school, an office etc. ) to share data and resources.

Wide Area Networks (WAN) is a number of local area networks that are connected to form a large, logical network without any geographical limitation.

In a Metropolitan Area Network computer connected to each other with in a city to have the organization concentric needs. Though the distance between the devices is not very large, they can have their own cabling plan.

243

Page 229: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS OF FOCUS

Introduction

On the most fundamental level, a computer network is an interconnected collection of computer systems that enables you to store, retrieve, and share information.

Overview

Evolution of Networking Advance Research Project Network ARPANET: In 1969, the first computer network was created. Called ARPANET (Advanced

Research Projects And Network, it interconnected UCLA, Stanford Research Institute, and UC Santa Barbara in California with the University of Utah.

Internet: Network of Networks connected word-wide is internet. Interspace: It is a client/ server software which allows real time interface access.

Different ways of sending data across the network Circuit switching techniques Packet Switching techniques

Data Communication terminologies Concept of Channel, Baud, Bandwidth (Hz, KHz, MHz) Data transfer rate (bps, kbps, Mbps, Gbps, Tbps)

Transmission Media Guided Media

Twisted pair cable Coaxial cable – Thin and Thick Coaxial Optical fiber

Non Guided Media Infrared radio link microwave link satellite link

Network devices Modem, RJ45 connector Ethernet Card Hub Switch Gateway

Different Topologies Bus Star Tree Mesh

Types of Networks

244

Page 230: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

LAN WAN MAN

Protocol: TCP/IP File Transfer Protocol (FTP) PPP

Level of Connectivity Remote Login (Telnet) Internet Wireless/Mobile Communication GSM CDMA WLL 3G SMS Voice mail

Application Electronic Mail Chat Video Conferencing

Network Security Concepts: Cyber Law Virus Threats and Prevention Firewall Cookies Hacking

Web Related Topics WebPages Hyper Text Markup Language (HTML) eXtensible Markup Language (XML) Hyper Text Transfer Protocol (HTTP) Domain Names URL Protocol Address Website Web browser Web Servers Web Hosting.

One Marks Questions: -

What is a Computer Network?

A computer network is an interconnected collection of devices that enables you to store, retrieve, and share information. Commonly connected devices include personal computers (PCs), minicomputers, mainframe computers, terminals, workstations, printers, fax machines, pagers, and various data-storage devices.

What is Data-communication?

245

Page 231: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Data-communication is the combination of data-processing and telecommunication. It includes the processing of data of program's running on computer-systems, and the communication over great distance where the information is transported by using of electrical-conductivity, radio-ways, light-signals, etc.

What is ARPANET?

In 1969, the first computer network was created. Called ARPANET, it interconnected UCLA, Stanford Research Institute, and UC Santa Barbara in California with the University of Utah. As time passed, more and more organizations joined this growing computer network.

What is Network Interface Card (NIC)?

The network interface card handles the connection to the network itself through one or more connectors on the backplane of the card.

What is Hub?

A Hub is a multipurpose network device that lies at the centre of a network to channel the traffic from one computer to another.

What is Repeater?

A Repeater is a network device that boosts the power of incoming signals to allow the length of a network to be extended.

What is Bridge?

A Bridge is a network device capable of connecting networks that use similar protocols. It connects two local area networks running the same network operating system.

Define Router?

A Router is a network device that connects LAN’s, that may be running on different operating systems, into an inter network and routes traffic between them. The router can have software that converts on Network Operating System's packets to the other's.

What is Gateway?

A Gateway forwards data between IP networks. It is a machine that acts as an interface between a small network and a much larger one. Usually, the gateway connects to a high-speed network cable or medium called the backbone.

246

Page 232: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

What is Backbone?

A Backbone is a set of nodes and links connected together comprising a network, or the upper layer protocols used in a network.

What is Modem?

Modems provide the means to transmit digital computer data over analog transmission media, such as ordinary, voice-grade telephone lines. The word "modem" is derived from "MOdulate and DEModulate"—modems convert digital (computer) signals to analog (audio) signals and vice versa.

What is the switching Technique?

Switching Data:

On an inter network, data units must be switched through the various intermediate devices until they are delivered to their destination. Two contrasting methods of switching data are commonly used Circuit Switching and Packet Switching.

Define Circuit Switching?

Circuit-switched is a type of network in which a physical path is obtained for and dedicated to a single connection between two end-points in the network for the duration of the connection. Ordinary voice phone service is circuit-switched.

Write down the disadvantage of Circuit Switching?

The chief disadvantage of circuit switching is that when communication takes place at less than the assigned circuit capacity, bandwidth is wasted. Also, communicating devices can’t take advantage of other, less busy paths through the network unless the circuit is reconfigured.

Write down the advantage of Circuit Switching?

End devices benefit greatly from circuit switching. Since the path is pre-established, data travel through the network with little processing in transit. And, because multipart messages travel sequentially through the same path, message segments arrive in an order and little effort is required to reconstruct the original message.

Important Note: Circuit switching does not necessarily mean that a continuous, physical pathway exists for the sole use of the circuit. The message stream may be multiplexed with other message streams in a broadband circuit. In fact, sharing of media is the more likely case with modern telecommunications. The appearance to the end devices, however, is that the network has configured a circuit dedicated to their use.

Define Packet Switching?

Packet Switching :

247

Page 233: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Packet-switched describes the type of network in which relatively small units of data called packets are routed through a network based on the destination address contained within each packet. Breaking communication down into packets allows the same data path to be shared among many users in the network. This type of communication between sender and receiver is known as connectionless (rather than dedicated).

Describe Network Transmission Media?

When data is sent across the network it is converted into electrical signals. To be sent from one location to another, a signal must travel along a physical path. The physical path that is used to carry a signal between a signal transmitter and a signal receiver is called the transmission medium. There are two types of transmission media: guided and unguided.

What is Twisted-Pair Cable?

Twisted-pair wiring refers to a type of cable composed of two (or more) copper wires twisted around each other within a plastic sheath. The wires are twisted to reduce crosstalk (electrical interference passing from one wire to the other). There are "shielded" and "unshielded" varieties of twisted-pair cables.

What is Coaxial Cable?

This type of cable is referred to as "coaxial" because it contains one copper wire (or physical data channel) that carries the signal and is surrounded by another concentric physical channel consisting of a wire mesh or foil. The outer channel serves as a ground for electrical interference.

What is difference between thin and thick coaxial cable?

Thinnet is not as flexible as twisted-pair, but it is still used in LAN environments. The connectors on coaxial cable are called BNC twist-on connectors.

Thicknet is similar to thinnet except that it is larger in diameter. The increase in size translates into an increase in maximum effective distance. The drawback to the increase in size, however, is a loss of flexibility.

Define Optical Fiber Cable?

Better known as "fiber optic," are the same types of cable used by most telephone companies for long-distance service. Optical fiber cable can transmit data over very long distances with little loss in data integrity.

Write down the advantages of Fiber Optical?

Data is transferred as a pulse of light rather than an electronic pulse, optical fiber is not subject to electromagnetic interference. The light pulses travel through a glass or plastic wire or fiber encased in an insulating sheath.

As with thicknet, optical fiber's increased maximum effective distance comes at a price. Optical fiber is more fragile than wire, difficult to split, and very labor-intensive to install.

248

Page 234: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

What is Unguided Media of transmission?

Unguided media are natural parts of the Earth's environment that can be used as physical paths to carry electrical signals. The atmosphere and outer space are examples of unguided media that are commonly used to carry signals. These media can carry such electromagnetic signals as microwave, infrared light waves, and radio waves.

What is Microwave Transmitters?

Microwave transmitters and receivers, especially satellite systems, are commonly used to transmit network signals over great distances. A microwave transmitter uses the atmosphere or outer space as the transmission medium to send the signal to a microwave receiver. The microwave receiver then either relays the signal to another microwave transmitter or translates the signal to some other form, such as digital impulses, and relays it on another suitable medium to its destination.

Write down the advantage and disadvantage of Microwave transmission?

Advantages:

It is cheaper then the guided media, and require less maintenance. It provides communication over difficult environment.

It cover large distance.

Disadvantages:

It is unsecured medium of communication. The loss of signal is more as compared to guided media.

Its communication depend up on the atmospheric conditions.

What is Infrared signal and its uses?

Infrared transmit light waves rather than radio waves, they require a line-of-sight transmission path.

Infrared are useful for signaling across short distances where it is impractical to lay cable. Because infrared and laser signals are in the light spectrum therefore, rain, fog, and other environmental factors can cause transmission problems.

What is LAN?

Local Area Networks (LAN) is a number of devices (Computers, Printers, Fax) that are connected to each other by some form of wiring, within a localized area (within building e.g. a school, an office etc. ) to share data and resources. A LAN enables independent devices to communicate directly with each other through direct communications.

There are three characteristics of LAN’s that must always be considered:

249

Page 235: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

• The transmission medium (the type of cabling used as the link).

• The transmission technique (the technique used to handle transmission on the medium).

• The access control method (which decides how a machine accesses the medium).

What is WAN?

Wide Area Networks (WAN) is a number of local area networks that are connected to form a large, logical network without any geographical limitation. WAN’s can be close together physically or separated by a large distance. WAN’s can share a large numbers of resources, or they can have different big network.

What is MAN?

In a Metropolitan Area Network computer connected to each other with in a city to have the organization concentric needs. Though the distance between the devices is not very large, they can have their own cabling plan.

What is Network Topologies?

The term "network topology" refers to the layout of a network. Due to the specific nature of computer network technology, networks must be arranged in a particular way in order to work properly. These arrangements are based on the network hardware's capabilities and the characteristics of the various modes of data transfer.

What is Bus Topology and its advantage?

The simplest form of a physical bus topology consists of a trunk (main) cable with only two end points. When the trunk cable is installed, it is run from area to area and device to device—close enough to each device so that all devices can be connected to it with short drop cables and T-connectors.

The principal advantage of this topology is cost: no hubs are required, and shorter lengths of cable can be used. It is also easy to expand. This simple "one wire, two ends" physical bus topology is illustrated in Figure 10.

Figure 10: Physical bus topology

250

Page 236: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

What is Star Topology?

The simplest form of the physical star topology consists of multiple cables—one for each network device—attached to a single, central connection device. 10Base-T Ethernet networks, for example, are based on a physical star topology: each network device is attached to a 10Base-T hub by means of twisted-pair cable.

What is Ring Topology?

251

Page 237: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

It is a closed network structure in the form of a circle, to which all nodes are connected. The ring name comes from the design of the central network device, which has a loop inside it to which are attached cables for all the devices on the network..

What is Tree Topology?

Also called a "hierarchical" or "star of stars" topology, tree topology is a combination of bus and star topologies. Nodes are connected in groups of star-configured workstations that branch out from a single "root". The root node usually controls the network and sometimes network traffic flow.

What is Mesh Topology?

In a full mesh topology, each node is physically connected to every other node. Partial mesh topology uses fewer connections, and though less expensive is also less fault-tolerant. In a hybrid mesh the mesh is complete in some places but partial in others.

The primary advantage of this topology is that it is highly fault tolerant: when one node fails, traffic can easily be diverted to other nodes. It is also not especially vulnerable to bottlenecks.

252

Page 238: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Define the term bandwidth? Give the unit of bandwidth.

Bandwidth means the capacity of a medium to transmit a signal. It is the bandwidth that determines the amount of information that can be transmitted for a distance. To carry digital signals, baseband modulation is used that allows transmission at a signal frequency at a time. To carry Radio Frequency signals, broadband modulation is used that allows multiple transmission taking place at different frequencies. Unit of bandwidth is Hertz.

What is a protocol?

A protocol means the set of rules that are applicable for a network for the transmission of data and signals. Protocols define standardized formats for data packets, techniques for detecting and correcting errors and so on. E.g. HTP, FTP, PPP etc.

What are cookies?

Cookies are messages that a web server transmits to a web browser so that the web server can keep track of the user’s activity on a specific web site.

What is web hosting? What are its various categories?

Web hosting mean hosting of web-server applications on a computer system through which electronic content on the Internet is readily available to any web browser client.

What is Cyberlaw?

In internet, the communication technology uses the means of transferring textual messages, pictures and many more. Each time there may be number of threats on either from senders or receivers side which creates a bridge between networking communication.

253

Page 239: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

These predefined rules are called cyber law or law of Internet.

What is the firewall ?what are the different firewall techniques?

The system designed to prevent unauthorized access to or fro a private network is called Firewall.

There are several types of firewall techniques:

(i) Packet Filter : Looks as each packet entering or leaving the network and accepts or rejects it based on user-defined rules.

(ii) Application gateway : Applies security mechanisms to specific applications, such as FTP and Telnet servers.

(iii)Circuit-level gateway : Apply security mechanisms when a connection is established.

(iv)Proxy server : Intercepts all messages entering and leaving the network. The proxy server effectively hides the true network addresses.

Write Differentiate between GSM and CDMA ?

GSM(Global System for Mobile) communications is a technique that uses narrowband TDMA, which allows eight simultaneous calls on the same radio frequency. TDMA is short for Time Division Multiple Access.

CDMA(Code-division Multiple Access) on the other hand, unlike GSM, does not assign a static frequency to each user. CDMA uses spread spectrum technique where every channel uses full available spectrum . With CDMA, data is sent in small pieces over a number of discrete frequencies available for use at any time in specified range..

Define the following :

(a) Data channel (f) Cookies

(b) Baud (g) Crackers

(c) Mbps (h) Hackers

(d) bps (i) Modem

(e) Web server

(a) Data channel : It is the medium used to carry information or data from one point to another.

(b) Baud : It is the measurement for the information carrying capacity of a communication channel. It is synonymous with bps(bits per second).

(c) Mbps : Mega bits/Bytes per second. It refers to million thousand bits or bytes transmitted per second.

(d) bps : bits per second. It refers to thousand bits transmitted per second.

254

Page 240: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

(e) Web server : It is a WWW(World Wide Network) server that responds to requests made by web browser.

(f) Cookies : Cookies are messages that a web server transmits to a web browser so that the web server can keep track of the user’s activity on a specific web site.

(g) Crackers : These are malicious programmers who break into secure systems .

(h) Hackers : These are more interested in gaining knowledge about computer systems and possibly using this knowledge for playful pranks.

(i) Modem : It is Modulator-demodulator which modulates & demodulates the signals to & fro.

(2) Expand the following terms:

(a) XML (f) HTML (k) EDGE

(b) GSM (g) WLL (l) WLL

(c) SMS (h) DHTML (m) SLIP

(d) CDMA (i) HTTP (n) PPP

(e) URL (j) TCP/IP (o) RJ-45

Ans.

(a) Extensible Markup Language

(b) Global System for Mobile

(c) Short Message Service

(d) Code Division Multiple Access

(e) Uniform Resource Locator

(f) Hypertext Markup Language

(g) Wireless Local Loop

(h) Dynamic Hypertext Markup Language

(i) Hypertext Transfer Protocol

(j) Transfer Control Protocol- Internet Protocol

(k) Enhanced Data rate for Global Evolution

(l) Wireless in Local Loop

(m) Serial Line Interrupt Protocol

(n) Point to Point Protocol

(o) Registered Jack – 45.

255

Page 241: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Five key areas for network managers to focus on, as recommended by ISO:

1. Fault management 2. Configuration management 3. Performance management 4. Accounting management 5. Security management

For Good Network Design: 80/20 Rule

The 80/20 rule is actually used as guideline when segmenting LAN 80% of the traffic of should remain on the local LAN, while 20% of the traffic should exit the LAN i.e. toward Backbone . But with the needs of the users having to access to servers outside of the LAN. The 80/20 rule has gradually changed into a 20/80 rule where 80% of the traffic has to exit the LAN and 20% of the network traffic remains in the local LAN. That means instead of upgrading the network device, it may easier to change the following:

Moving Resource to contain traffic locally Moving users Adding server

Conventional Rules:

Using repeater is the 5-4-3 Rule. the maximum path between two station on the network should not be more than 5 segment with 4 repeaters between those segments and no more than 3 populated segments.

Bridge is used to repeat the signal but in between the specific route. Hub share bandwidth with all the devices i.e. it make the communication channel of the

entire terminal busy with its broadcast signal.

4 Marks Question Case Study

1. A company in Reliance has 4 wings of buildings as shown in the diagram:

256

W1

W3 W4

W2

Page 242: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

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 135

W2 25

W3 20

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 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 :

1) Repeater (2) Hub (3) Switch (4) Bridge

iv) The company is planning to link its head office situated in India with the offices at Britain.

Suggest a way to connect it; the company may compromise with the speed of connectivity. Justify

your answer.

Ans:

i) The cable layout will be

257

W1

W3 W4

W2

Page 243: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

ii) The topology will be star. Because the distance from W1 to other Places is average, whereas in

ring and tree we will require more cabling.

iii) Hub in W1,W2, W3 and W4 , everyone and Switch in W1 to communicate with other network.

iii) They can connect with either satellite link, or through internet.

2. Indian Industries has the following four buildings in Chennai. Distance between various wings are given below:

Wing II1 to Wing II 3 70mWing II1 to Wing II 2 20mWing II 1 to Wing II 4 115mWing II 3 to Wing II 4 30mWing II 2 to Wing II3 25m

Number of ComputersWing II 1 35Wing II 2 25Wing II 3 80Wing 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)

Ans :

(i) Suitable cable layout is

258

30m

25m20m

II1

II 4II 2

II 3

II 4II 2

Page 244: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

(ii) As the 80 – 20 rule, th server should be placed in the building with maximum number of computers. Thus, we suggest that the server should be placed in Wing II 3.

(iii)

(iv) Dial – up NetworkBroad BandCable(Twisted paid or Fiber optical or Coaxial cable)ISDNRadio Wave

4. Indian Public School in Darjeeling is setting up the network between its different wings. There are 4 wings named as SENIORS(S), JUNIOR(J), ADMIN(A) and HOSTEL(H).

Distance between various wings are given below:

Wing A to Wing S 100 m

259

II1 II 3

30m25m20m

II1

II 4II 2

II 3

Hub/

Hub/

Hub/

Hub/

Page 245: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Wing A to Wing J 200 m

Wing A to Wing H 400 m

Wing S to Wing J 300 m

Wing S to Wing H 100 m

Wing J to Wing H 450 m

Number of computers

Wing A 10

Wing S 200

Wing J 100

Wing H 50

(a) Suggest a suitable Topology for networking the computer of all wings

(b) Name the wing where the server is to be installed. Justify your answer

(c) Suggest the placement of Hub/Switch in the network.

(d) Mention an economic technology to provide internet accessibility to all wings.

Ans.(a) Star or Bus or any other valid topology or diagram.

(b) Wing S, because maximum number of computers are located at Wing A.

(c) Hub/switch in all the wings.

(d) Coaxial cable/Modem/LAN/TCP-IP/Dialup/DSl/Leased lines or any other valid technology.

5. The Great Brain Organization has set up its new Branch at Sri-Nagar for its office and web based activities. It has 4 Wings of buildings as shown in the diagram:

260

Page 246: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

Number of computers

Wing X 50

Wing Z 130

Wing Y 40

Wing U 15

(a) Suggest a most suitable cable layout of connections between the wings & topology.

(b) Suggest a most suitable place(ie. Wing) to house the server of this organization with a suitable reason with justification.

(c) Suggest the placement of the following devices with justification :

(i) Repeater (ii) Hub/ Switch

(d) The organization is planning to link its head office situated in Delhi with the offices at Mizoram. Suggest an economic way to connect it. The company is ready to compromise on the speed of connectivity. Justify your answer.

Ans. (a) Bus topology

(b) Wing Y as it has the most number of computers thus cabling cost will be reduced and most traffic will be local.

(c) (i) Repeater is used if the distances are more than 70m. It regenerate data & voice

signals.

(ii) Hub/Switch is better to place in nearby buildings. The maximum distance covered by an active hub is about 2000ft.

(d) An economic way of connecting is dial-up or broadband as it can connect two computers at an economic rate through it provides lesser speed than other expensive methods.

261

Page 247: CHAPTER 1 · Web viewThe cout and cin are defined in C++ standard library file “iostream.h” We can use some library functions for performing input and output. 21.1 getchar() This

POINTS TO REMEMBER: A network is a collection of interlinked computer by mean of communication system.

InterSpace is the future technology of future.

Two type of switching technologies circuit and packet switching is used for

transmitting data.

Twisted pair, coaxial cable, optical fiber are communally used transmission media.

On the basis of geographical condition networks can be classified into LAN, WAN

and MAN.

The most popular topologies are star, ring, tree and mesh.

RJ45 is an eight wire connector, which I communally used to connect computer on

LAN.

3G (Third Generation) mobile communications technology is a broadband, packet-

based transmission of text, digitized voice, video and multimedia.

Remote login (Telnet) is the process of accessing a network from a remote place

without actually being at the actual place of working.

The crackers are malicious programmers who break into secure system whereas

hackers are more interested in gaining knowledge about computer system.

262