Sie sind auf Seite 1von 83

BOSCO PUBLIC SCHOOL, SUNDER VIHAR, NEW DELHI

SESSION (2019-20)
SUBJECT : COMPUTER SCIENCE
CLASS: XII
BOOK NAME : Computer Science with C++

INDEX

Topic: C++ Revision Tour

C++, as we all know is an extension to C language and was developed by Bjarne stroustrup at bell
labs. C++ is an intermediate level language, as it comprises a confirmation of both high level and
low level language features. C++ is a statically typed, free form, multiparadigm, compiled general-
purpose language.
C++ is an Object Oriented Programming language but is not purely Object Oriented. Its features
like Friend and Virtual, violate some of the very important OOPS features, rendering this language
unworthy of being called completely Object Oriented. Its a middle level language.
C++ Character Sets:
Letters A-Z , a-z
Digits 0-9
Special Symbols Space + - * / ^ \ ( ) [ ] { } = != <> . „ ― $ , ; : % ! & ? _ # <= >= @
White Spaces Blank spaces, horizontal tab, carriage return
Other Characters Any of the 256 ASCII character
Token:-The smallest individual unit in a program is known as token. Tokens used in C++ are:
KEYWORDS : Keywords are the certain reserved words that convey a special meaning to the
compiler. These are reserve for special purpose and must not be used as identifier name.eg for , if,
else , this , do, etc.
IDENTIFIERS: Identifiers are programmer defined names given to the various program elements
such as variables, functions, arrays, objects, classes, etc.. It may contain digits, letters and
underscore, and must begin with a letter or underscore. C++ is case sensitive as it treats upper and
lower case letters differently. The following are some valid identifiers: Pen time580 s2e2r3 _dos
_HJI3_JK
LITERALS: The data items which never change their value throughout the program run. There are
several kinds of literals: • Integer literals • Character literals • Floating literals • String literals
COMMENTS IN A C++ PROGRAM.: Comments are the pieces of code that compiler ignores to
compile. There are two types of comments in C++.
1. Single line comment: The comments that begin with // are single line comments. The Compiler
simply ignores everything following // in the same line.
2. Multiline Comment : The multiline comment begin with /* and end with */ . This means
everything that falls between /* and */ is consider a comment even though it is spread across many
lines.
DATA TYPES IN C++: Data types are means to identify the types of data and associated
operations of handling it. Data types in C++ are of two types:
1. Fundamental or Built-in data types .
2. Derived data types.
1.Fundamental or Built-in data types: These data types are already known to compiler. These are
the data types those are not composed of other data types. There are following fundamental data
types in C++:
(i) int data type (for integer) :- int data type is used for integer value. An identifiers declare as
int cannot have fractional part.
(ii) char data type (for characters):- An identifiers declare as char can store a character.
(iii) float data type (for floating point numbers):- An identifier declare as float can hold a
floating point number.
1
(iv) double data type (for double precision floating point numbers):- The double data type is
also used for handling floating point numbers but it occupies twice as much memory as float
and store numbers with much larger range and precision.
Data Type Modifiers:-There are following four data type modifiers in C++ , which may be used
to modify the fundamental datatypes to fit various situations more precisely: (i) signed (ii)
unsigned (iii) long (iv) short
2. Derived Data Types:- These are the data types that are composed of fundamental data types.
e.g., array, class, structure, etc.
Variables:-A named memory location, whose contains can be changed with in program execution
is known as variable.
Constant:- A named memory location, whose contains cannot be changed with in program
execution is known as constant.
const float pi = 3.14
Operators:-
Arithmetic operators :-Those operators are operates only on numeric data types operands are
known as arithmetic operators.
Relational Operator: These operators are used to compare two values. If comparison is true, the
relational expression results into the value 1 and if the comparison is false its result will be 0 like:
>,>=,<,<=,==,!=
Logical Operators : In addition to the relational operator, C++ contains three logical operators.
Relational operators often are used with logical operators to construct more complex decision
making expressions. Like &&-and ,||-or , !-not
Assignment Operator: C++ offers an assignment operator (=) to assign a value to an identifier.
The assignment statement that make use of this operator are written in the form :var = expression ;
Conditional operator ( ? : ) The conditional operator (? :) is a ternary operator i.e., it require three
operands. The general form of conditional operator is: expression1? expression2: expression3 ;
min = a<b?a:b;
Comma operator ( , ) The comma operator (,) is used to separate two or more expressions that are
included where only one expression is expected. When the set of expressions has to be evaluated
for a value, only the rightmost expression is considered.
For example, the following code: a = (b =3 , b +2 );
sizeof() This operator returns the size of its operand in bytes. The operand may be an expression or
identifier or it may be a data type. a= sizeof (char); This will assign the value 1 to a because char is
a one-byte long type
Type Conversion:-The process of converting one predefined data type into another is called type
conversion. C++ facilitates the type conversion in two forms:
(i) Implicit type conversion:- An implicit type conversion is a conversion performed by the
compiler without programmer‘s intervention. An implicit conversion is applied
generally whenever different data types are intermixed in an expression. The C++
compiler converts all operands upto the data type of the largest data type‘s operand,
which is called type promotion.
(ii) Explicit type conversion :- An explicit type conversion is user-defined that forces an
expression to be of specific data type.
Increment and Decrement Operators (++ , - -) :
The increment operator (++) adds 1 to its operand and decrement operator (--) subtract one from its
operand. In other word a = a + 1; is same as ++a; or a++; & a = a – 1 ; is same as --a; or a--; Both
the increment & decrement operators comes in two version :
(i) Prefix increment/decrement :- When an increment or decrement operator precedes its operand,
it is called prefix increment or decrement (or pre-increment / decrement). In prefix
increment/decrement , C++ perform the increment or decrement operation before using the value of
the operand. e.g., If sum = 10 and count =10 then Sum = sum +(++count); First count incremented
and then evaluate sum = 21.
(ii) Postfix increment/decrement :- When an increment or decrement operator follows its operand,
it is called postfix increment or decrement (or post-increment / decrement). In postfix
2
increment/decrement C++ first uses the value of the operand in evaluating the expression before
incrementing or decrementing the operand‘s value. e.g., If sum = 10 and count =10 then Sum = sum
+(count++); First evaluate sum = 20 , and then increment count to 11
Type Casting:- The explicit conversion of an operand to a specific type is called type casting
Type Casting Operator - (type) :-Type casting operators allow you to convert a data item of a
given type to another data type. To do so , the expression or identifier must be preceded by the
name of the desired data type , enclosed in parentheses . i. e., (data type) expression Where data
type is a valid C++ data type to which the conversion is to be done. For example , to make sure that
the expression (x+y/2) evaluates to type float , write it as: (float) (x+y/2)
Statement Flow Control:-In a program , statements may be executed sequentially,selectively, or
iteratively.
Every programming language provides three constructs:
1. Sequence Constructs
2. Selection Constructs
3. Iteration Constructs
Sequence Construct:-The sequence construct means the statements are
being executed sequentially. It represents the default flow of statements.

Selection Construct:- The selection construct means the


execution of statement(s) depending on a condition. If a
condition is true, a group of statements will be executeotherwise another group of statements will
be execute.
1. if statement
2. switch statement
Looping or Iteration Statements:-Looping the iteration construct means
repetition of set of statements depending upon a condition test. The iteration
statements allow a set of instructions to be performed repeatedly until a certain
condition is true.

There are two types of loops:-


1. Entry controlled loop – For loop and while loop
2. Exit controlled loop – do .. while loop

Jump Statements:-These statements unconditionally transfer control within function . In C++ four
statements perform an unconditional branch :
1. return
2. goto
3. break
4. continue

Functions :-Function is a named group of programming statements which perform a specific


task and return a value. There are two types of functions:-
1. Built-in (Library )functions

Built-in Functions (Library Functions) :- The functions, which are already defined in
C++Library ( in any header files) and a user can directly use these function without giving
theirdefinition is known as built-in or library functions. e.g., sqrt( ), toupper( ), isdigit( ) etc.

Following are some important Header files and useful functions within them :
stdio.h (standard I/O function) gets( ) , puts( )
ctype.h (character type function) isalnum( ) , isalpha( ), isdigit ( ), islower (), isupper ( ), tolower
( ), toupper( )
string.h (string related function ) strcpy ( ), strcat ( ), strlen( ), strcmp( ) , strcmpi( ) , strrev( ),
strupr( )
3
math.h (mathematical function) fabs ( ), pow ( ), sqrt ( ), sin ( ), cos ( ), abs ( )
stdlib.h randomize ( ), random ( )

2. User defined functions


Three components are:
1. Declaration of user-defined Function:
2. Calling of a function
3. Prototype of a function

Calling a function can be of two types:


Call by Value (Passing by value) :- The call by value method of passing arguments to a function
copies the value of actual parameters into the formal parameters , that is, the function creates its
own copy of argument values and then use them, hence any chance made in the parameters in
function will not reflect on actual parameters .
Call by Reference ( Passing by Reference) :- The call by reference method uses a different
mechanism. In place of passing value to the function being called , a reference to the original
variable is passed . This means that in call by reference method, the called function does not create
its own copy of original values , rather, its refers to the original values only by different
names i.e., reference , thus the called function works the original data and any changes are reflected
to the original values.

Types of parameters in function


Formal Parameters:- The parameters that appear in function definition are formal parameters.
Actual Parameters :- The parameters that appears in a function call statement are actual
parameters.

Scope of Identifier :- The part of program in which an identifier can be accessed is known as
scope of that identifier. There are four kinds of scopes in C++
(i) Local Scope :- An identifier declare in a block ( { } ) is local to that block and canbe used only
in it.
(ii) Function Scope :- The identifier declare in the outermost block of a function havefunction
scope.
(iii) File Scope ( Global Scope) :- An identifier has file scope or global scope if it isdeclared outside
all blocks i.e., it can be used in all blocks and functions.

ARRAYS :-Array is a group of same data types variables which are referred by a commonname.
Types of Array :-Arrays are of two types:
1. One-dimensional Arrays
The simplest form of an array is one - dimensional. The array itself
is given a name and its elements are referred to by their subscripts. In C++ , an array must be
defined before it can be used to store information. The general form of an array declaration
is:
Data_type Array_name[size];

2. Two-dimensional Arrays
Two dimensional array : A two dimensional array is a continuous memory location
Holding similar type of data arranged in row and column format (like a matrix structure).
Declaration of 2-D array:- The general syntax used for 2-Darray declaration is:
Data_type Array_name [R][C] ;
Where R represent number of rows and C represent number of columns in array.
For example, int marks [3][5];

Array of Strings:-An array of string is a two-dimensional character array. The size of first
index determines the number of strings and size of second index determines maximum length of
4
each string. The following statement declares an array of 10 strings , each of which can hold
maximum 50 valid characters.
char string[10][51] ;
Notice that the second index has been given 51, because 1 extra size is given for store null
character ‗\0‘.

User Defined Data Types:-


The C++ language allows you to create and use data types other than the fundamental data types.
These types are called user-defined data types.
Structures:- In C++, a structure is a collection of variables that are referenced by a single name.
The variable can be of different data types. They provide a convenient means of keeping related
information together.
Defining Structure :-
A Structure is defined by using the Keyword struct. The General Syntax for defining a
Structureis :
Syntax :
struct< Name of Structure >
{
<datatype>< data-member 1>;
<datatype>< data-member 2>;
<datatype>< data-member 3>;


<datatype>< data-member n>;
};
Initializing of Structure elements:- You can initialize members of a structure in two ways.
You can initialize members when you declare a structure or you can initialize a structure with in
the body of program. For Example:
First Method:-
#include <iostream.h>
#include <conio.h>
void main()
{
// Declaring structure at here
struct Employee
{
int empcode;
float empsalary;
};

Employee emp1 = {100, 8980.00} ; // emp1 is the structure variable ,// which is also initialize
with declaration
clrscr();
int i; // declares a temporary variable for print a line
// Printing the structure variable emp1 information to the screen
cout<< "Here is the employee information : \n";
for (i = 1; i <= 32; i++)
cout<< "=";
cout<< "\nEmployee code : " << emp1.empcode;
cout<< "\nEmployee salary : " << emp1.empsalary;
}

Second Method:-
#include <iostream.h>
5
#include <conio.h>
void main()
{
// Declaring structure here
struct Employee
{
int empcode;
float empsalary;
} emp1; // emp1 is the structure variable
clrscr();
int i; // declares a temporary variable for print a line
// Initialize members here
emp1.empcode = 100;
emp1.empsalary = 8980.00;
// Printing the structure variable emp1 information to the screen
cout<< "Here is the employee information : \n";
for (i = 1; i <= 32; i++)
cout<< "=";
cout<< "\nEmployee code : " << emp1.empcode;
cout<< "\nEmployee salary : " << emp1.empsalary;
}

typedef :- The typedef keyword allows to create a new names for data types. the syntax is:
typedef existing_data_type new_name ;
e.g.,typedef int num;

#define Preprocessor Directive :-The # define directive create symbolic constant, constants that
are represent as symbols and macros (operation define as symbols). The syntax is:
#define identifier replacement_text ;
When this line appears in a file, all subsequent occurrences of identifier in that file will be
replaced by replacement_text automatically before the program is compiled. e.g.,
Program: Program to calculate area of a circle by using #define preprocessor directive.
#include <iostream.h>
#define PI 3.14159
#define CIRCLE_AREA(x) (PI * (x) * (x))
void main()
{float area;int r;
cout<< "Enter the radius : ";
cin>> r;
area = CIRCLE_AREA(r);
cout<< "Area is : " << area;
}

Solved Questions(Hots Questions)

Q1. Write the names of the header file to which of the following belong: (1)
(i) sqrt( )
(ii) randomize()
Answer: (i) math.h(ii) stdlib.h

Q2. Write a function in C++ to find the sum of left diagonal elements passed as an argument to a
function sum (3)

Answer:
6
void sum(intarr[][4],intr,int c)
{
inti,j,sum=0;
for(i=0;i<r; i++)
{ for(j=0; j<c; j++)
{
if (i==j)
{
sum=sum+arr[i][j];
}
}
}

}
Q3. How many times will the following program will print ―examination‖? (2)
#include<iostream.h>
void main( )
{
while(1)
{
cout<<‖examination‖
}
}

Answer : Unless ^C is pressed ,program will print ―examination‖ infinitely.

Unsolved questions
(1) What is the difference between Auto variables and Static variables? Give an example to
illustrate the same. (2)

(2) Name the header files for the following functions (2)
(1) gets()
(2) floor()
(3) isalpha()
(4) setw()
(3) In the following C++ program what is expected value of myscore from options (i) to (iv) given
below. (2)
#include
void main( )
{
randomize( );
int score[]={ 25, 20,34,56, 72, 63};
int myscore=score[2+random(2)];
cout<<myscore<<endl;
}
i) 25 ii) 34 iii) 20 iv) None of these
(4) Give the output of the following program (Assuming all required header files are included in the
program). (3)

void swap(char &c1,char &c2)


{ char temp;
temp=c1;
7
c1=c2;
c2=temp;
}
void update(char *str)
{ int k,j,l1,l2;
l1 = (strlen(str)+1)/2;
l2=strlen(str);
for(k=0,j=l1-1;k<j;k++,j–)
{ if(islower(str[k]))
swap(str[k],str[j]);
}
for(k=l1,j=l2-1;k<j;k++,j–)
{ if(isupper(str[k]))
swap(str[k],str[j]);
}
}
void main()
{ char data[100]={―gOoDLUck‖};
cout<<―Original Data : ―<<data<<endl;
update(data);
cout<<―Updated Data ―<<data;
}
(5) What is the difference between Global Variable and Local Variable? Also, give a suitable C++
code to illustrate both. (2)

(6) Which C++ header file(s) will be essentially required to be included to run / execute the
following C++ code: (3)
void main()
{
char Msg[ ]=‖Sunset Gardens‖;
for (int I=5;I<strlen(Msg);I++) puts(Msg); }
Find the output of the following program: [2 Mark]
#include
struct GAME
{ int Score, Bonus;};
void Play(GAME &g, int N=10)
{
g.Score++;g.Bonus+=N;
}
void main()
{
GAME G={110,50};
Play(G,10);
cout<<G.Score<<―:‖<<G.Bonus<<endl;
Play(G);
cout<<G.Score<<―:‖<<G.Bonus<<endl;
Play(G,15);
cout<<G.Score<<―:‖<<G.Bonus<<endl;
}
(7) Find the output of the following program: (3)

#include <iostream.h>
void Secret(char Str[ ])
{
8
for (int L=0;Str[L]!=‖;L++);
for (int C=0;C<L/2;C++)
if (Str[C]==‘A‘ || Str[C]==‘E‘)
Str[C]=‘#‘;
else
{char Temp=Str[C];
Str[C]=Str[L-C-1];
Str[L-C-1]=Temp;
}
}
void main()
{char Message[ ]=‖ArabSagar‖;
Secret(Message);
cout<<Message<<endl;
}
(8) In the following program, if the value of Guess entered by the user is 65, what will be the
expected output(s) from the following options (i), (ii), (iii) and (iv)?
#include<iostream.h>
#include<stdlib.h>
void main()
{ int Guess, New;
randomize();
cin>>Guess;
for (int I=1;I<=4;I++)
{
New=Guess+random(I);cout<<(char)New;
}
}
(i) ABBC
(ii) ACBA
(iii) BCDA
(iv) CABD

(9)Find the output for the following program: (3)


#include<iostream.h>
#include<ctype.h>
void Encript ( char T[ ])
{ for( int i=0 ; T[i] != ‗ \0‘ ; i += 2)
if( T[i] = = ‗A‘ || T[i] = = ‗E‘ )
T[i] = ‗#‘ ;
else if (islower (T[i] ))
T[i] = toupper(T[i]);
else
T[i] = ‗@‘;}

void main()
{ char text [ ] = ―SaVEEArTh in 2012‖;
encrypt(text);
cout<<text<<endl;
}
(10) Find the output of the following program: (3)
#include<iostream.h>
void main( )
9
{ int U=10,V=20;
for(int I=1;I<=2;I++)
{ cout<<‖[1]‖<<U++<<‖&‖<<V 5 <<endl;
cout<<‖[2]‖<<++V<<‖&‖<<U + 2 <<endl;
}
}
(11) What happens when an inline function is written? (2)

(12) Differentiate between ( 1 x 17 = 17)


1. Actual and Formal Parameters
2. Implicit and explicit conversion
3. Comments and Indentation
4. Passing by value and Passing by address/reference
5. strcmp() and strcmpi()
6. islower(c) and tolower(c)
7. break and continue
8. Keywords and identifiers
9. Post tested loop and Pre tested loop
10. i++ and ++i
11. Derived and fundamental data types
12. Conditional and Comma operator
13. Inbuilt and user defined functions
14. String and a Character
15. Class and Structure
16. #define and typedef
17.Selection and Iteration Construct

Topic : Database Concepts

Basic Database terms


Data :- Raw facts and figures which are useful to an organization. We cannot take
decisions on the basis of data.
Information:- Well processed data is called information. We can take decisions on the basis of
information
Field: Set of characters that represents specific data element.
Record: Collection of fields is called a record. A record can have fields of different data
types.
File: Collection of similar types of records is called a file.
Table: Collection of rows and columns that contains useful data/information is called a
table. A table generally refers to the passive entity which is kept in secondary
storage device.
Relation: Relation (collection of rows and columns) generally refers to an active entity on
which we can perform various operations.
Database: Collection of logically related data along with its description is termed as database.
Tuple: A row in a relation is called a tuple.
Attribute: A column in a relation is called an attribute. It is also termed as field or data item.
Degree: Number of attributes in a relation is called degree of a relation.
Cardinality: Number of tuples in a relation is called cardinality of a relation.
Primary Key: Primary key is a key that can uniquely identifies the records/tuples in a relation.
This key can never be duplicated and NULL.
Foreign Key: Foreign Key is a key that is defined as a primary key in some other relation. This
key is used to enforce referential integrity in RDBMS.
10
Candidate Key: Set of all attributes which can serve as a primary key in a relation.
Alternate Key: All the candidate keys other than the primary keys of a relation are alternate keys
for a relation.
DBA: Data Base Administrator is a person (manager) that is responsible for defining the
data base schema, setting security features in database, ensuring proper
functioning of the data bases etc.
View : A view is a virtual table based on the result-set of an SQL statement A view
contains rows and columns, just like a real table. The fields in a view are fields
from one or more real tables in the database.
Type of Data Models
1. Hierarchical Data Model : Hierarchical depicts one-to –many relationship between a parent
and child segment.
2. Network data model: It consists of collection of records connected to one another through
links. The network model replaces the Hierarchical model with a graph, thus allowing
multiple connections among the nodes.
3. Relational data model : A relation model consists of a collection of tables, each of which is
assigned a unique name, represents the database as a collection of relations or tables.
Relational Algebra
1. Union : Tuples in r1 and/or in r2
2. Intersection: Tuples in both r1 and r2
3. Set –difference : tuples in r1, but not in r2
4. Cartesian product: allows us to combine two relations
5. Selection: Selects a subset of rows from a relation.
6. Projection: Retains only wanted columns from a relation.
7. Natural : one column should be same in both the tables.
Solved Questions
Define the terms: (1 x 7 = 7)
i. Database Abstraction
ii. Data inconsistency
iii. Conceptual level of database implementation/abstraction
iv. Primary Key
v. Candidate Key
vi. Relational Algebra
vii Domain
Ans: :
i. Database Abstraction
Ans: Database system provides the users only that much information that is required
by them, and hides certain details like, how the data is stored and maintained in
database at hardware level. This concept/process is Database abstraction.
ii. Data inconsistency
Ans: When two or more entries about the same data do not agree i.e. when one of
them stores the updated information and the other does not, it results in data
inconsistency in the database.
iii. Conceptual level of database implementation/abstraction
Ans: It 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.
iv. Primary Key
Ans : It is a key/attribute or a set of attributes that can uniquely identify tuples within the
relation.
v. Candidate Key
Ans : All attributes combinations inside a relation that can serve as primary key are
candidate key as they are candidates for being as a primary key or a part of it.
vi. Relational Algebra
11
Ans : It is the collections of rules and operations on relations(tables). The various operations
are selection, projection, Cartesian product, union, set difference and intersection, and
joining of relations.
vii. Domain
Ans : it is the pool or collection of data from which the actual values appearing in a given
column are drawn.

Unsolved Questions
1. What is relation? What is the difference between a tuple and an attribute? (2)
2. Define the following terminologies used in Relational Algebra: (4)
(i) selection (ii) projection (iii) union (iv) Cartesian product
3. What are DDL and DML? (2)
4. Differentiate between primary key and candidate key in a relation? (2)
5. What do you understand by the terms Cardinality and Degree of a relation in relational
database? (2)
6. Differentiate between (1 x 7 = 7)
1. Table and Database
2. Primary Key and Foreign Key
3. Tuple and Attribute
4. Alternate Key and Candidate Key
5. View and table
6. Cartesian Product and Union
7. Relational and Network data model

Topic : Structured Query Language

SQL is a non-procedural language that is used to create, manipulate and process the
databases(relations).

Characteristics of SQL
1. It is very easy to learn and use.
2. Large volume of databases can be handled quite easily.
3. It is non-procedural language. It means that we do not need to specify the procedures to
accomplish a task but just to give a command to perform the activity.
4. SQL can be linked to most of other high level languages that makes it first choice for the
database programmers.

Processing Capabilities of SQL


The following are the processing capabilities of SQL
1. Data Definition Language (DDL)
DDL contains commands that are used to create the tables, databases, indexes, views,
sequences and synonyms etc.
e.g: Create table, create view, create index, alter table etc.
2. Data Manipulation Language (DML)
DML contains command that can be used to manipulate the data base objects and to
query the databases for information retrieval.
e.g Select, Insert, Delete, Update etc.
3. View Definition:
DDL contains set of command to create a view of a relation.
e.g : create view
4. Data Control Language:
This language is used for controlling the access to the data. Various commands like
GRANT, REVOKE etc are available in DCL.
12
5. Transaction Control Language (TCL)
TCL include commands to control the transactions in a data base system. The commonly
used commands in TCL are COMMIT, ROLLBACK, SAVEPOINT etc.

Data types of SQL


Just like any other programming language, the facility of defining data of various types is available
in SQL also. Following are the most common data types of SQL.
1) INTEGER(NUMERIC) ,
2) CHAR
3) VARCHAR / VARCHAR2
4) DATE
5) LONG

1. INTEGER
Used to store a numeric value in a field/column. It may be decimal, integer or a real value. General
syntax is INTEGER(d) Where d specifies the number of digits and
e.g marks Integer(3) declares marks to be of type number with maximum value 999.
2. CHAR
Used to store character type data in a column. General syntax is
Char (size)
where size represents the maximum number of characters in a column. The CHAR type data can
hold at most 255 characters.
e.g name char(25) declares a data item name of type character of upto 25 size long.
3. VARCHAR/VARCHAR2
This data type is used to store variable length alphanumeric data. General syntax is
varchar(size) / varchar2(size)
where size represents the maximum number of characters in a column. The maximum allowed size
in this data type is 2000 characters.
e.g address varchar(50); address is of type varchar of upto 50 characters long.
4. DATE
Date data type is used to store dates in columns. SQL supports the various date formats other that
the standard DD-MON-YY.
e.g dob date; declares dob to be of type date.
5. LONG
This data type is used to store variable length strings of upto 2 GB size.
e.g description long;

SQL Commands
CREATE TABLE Command:
Create table command is used to create a table in SQL. It is a DDL type of command. The general
syntax of creating a table is

Creating Tables
The syntax for creating a table is
create table <table> (
<column 1><data type> [not null] [unique] [<column constraint>],…….
)
Operators in SQL:
The following are the commonly used operators in SQL
1. Arithmetic Operators +, -, *, /
2. Relational Operators =, <, >, <=, >=, <>
3. Logical Operators OR, AND, NOT
Arithmetic operators are used to perform simple arithmetic operations.
13
Relational Operators are used when two values are to be compared and
Logical operators are used to connect search conditions in the WHERE Clause in SQL.

Create Database:
The CREATE DATBASE command is used to create database in RDBMS.
Create database Bosco;

This command creates the database school.

Open Database:
The use <database name> is use to open database
Use Bosco;

This command opens the existing database.

Constraints:
Constraints are the conditions that can be enforced on the attributes of a relation. The constraints
come in play when ever we try to insert, delete or update a record in a relation.
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGN KEY
5. CHECK
6. DEFAULT
Not null ensures that we cannot leave a column as null. That is a value has to be supplied for that
column.
e.g name varchar(25) not null;
Unique constraint means that the values under that column are always unique.
e.g Roll_nonumber(3) unique;
Primary key constraint means that a column can not have duplicate values and not even a null
value.
e.g. Roll_nonumber(3) primary key;
The main difference between unique and primary key constraint is that a column specified as
unique may have null value but primary key constraint does not allow null values in the column.
Foreign key is used to enforce referential integrity and is declared as a primary key in some other
table.
e.g cust_idvarchar(5) references master(cust_id);
it declares cust_id column as a foreign key that refers to cust_id field of table master. That means
we cannot insert that value in cust_id filed whose corresponding value is not present in cust_id field
of master table.
Check constraint limits the values that can be inserted into a column of a table.
e.g marks number(3) check(marks>=0);
The above statement declares marks to be of type number and while inserting or updating the value
in marks it is ensured that its value is always greater than or equal to zero.
Default constraint is used to specify a default value to a column of a table automatically. This
default value will be used when user does not enter any value for that column.
e.g balance number(5) default = 0;

CREATE TABLE student (


Roll_no number(3) primary key,
Name varchar(25) not null,
Class varchar(10),
Marks number(3) check(marks>0),
City varchar(25) );
14
Data Modifications in SQL (Insert, Delete and Update)
After a table has been created using the create table command, tuples can be inserted into the table,
or tuples can be deleted or modified.

INSERT Statement
The simplest way to insert a tuple into a table is to use the insert statement
insert into <table> [(<column i, . . . , column j>)] values (<value i, . . . , value j>);

INSERT INTO student VALUES(101,'Rohan','XI',400,'Jammu');


While inserting the record it should be checked that the values passed are of same data types as the
one which is specified for that particular column.

For inserting a row interactively (from keyboard) & operator can be used.
e.g INSERT INTO student VALUES(&Roll_no‘,‘&Name‘,‘&Class‘,‘&Marks‘,‘&City‘);
In the above command the values for all the columns are read from keyboard and inserted into the
table student.

NOTE:- In SQL we can repeat or re-execute the last command typed at SQL prompt by typing
“/” key and pressing enter.

Roll_no Name Class Marks City


101 Rohan XI 400 Jammu
102 Aneeta Chopra XII 390 Udhampur
103 Pawan Kumar IX 298 Amritsar
104 Rohan IX 376 Jammu
105 Sanjay VII 240 Gurdaspur
113 AnjuMahajan VIII 432 Pathankot

Modifying Data in the table:


Update Command
Update command is used to change the data in the table.
For eg.
Update student set marks = marks +50 where class=‘XI‘;
This command increases the marks by 50 where the class ix XI.

Deleting data in the table;


Delete Command

Delete command is used to delete a row/tuple from the table.


For eg.
Delete from student where rollno=103;

This command deletes the row from student table.

Queries:
To retrieve information from a database we can query the databases. SQL SELECT statement is
used to select rows and columns from a database/relation.

15
SELECT Command
This command can perform selection as well as projection.
Selection: This capability of SQL can return you the tuples form a relation with all the
attributes.
Projection: This is the capability of SQL to return only specific attributes in the relation.
* SELECT * FROM student; command will display all the tuples in the relation student
* SELECT * FROM student WHERE Roll_no<=102;
The above command display only those records whose Roll_no less than or equal to 102.
Select command can also display specific attributes from a relation.

* SELECT name, class FROM student;


The above command displays only name and class attributes from student table.

* SELECT count(*) AS ―Total Number of Records‖ FROM student;


Display the total number of records with title as ―Total Number of Records‖ i.e an alias

We can also use arithmetic operators in select statement, like


* SELECT Roll_no, name, marks+20 FROM student;
* SELECT name, (marks/500)*100 FROM student WHERE Roll_no> 103;

Eliminating Duplicate/Redundant data

DISTINCT keyword is used to restrict the duplicate rows from the results of a SELECT statement.
e.g. SELECT DISTINCT name FROM student;
The above command returns
Name
Rohan
Aneeta Chopra
Pawan Kumar

Conditions based on a range


SQL provides a BETWEEN AND operator that defines a range of values that the column value
must fall for the condition to become true.
e.g. SELECT Roll_no, name FROM student WHERE Roll_no BETWEEN 100 AND 103;

The above command displays Roll_no and name of those students whose Roll_no lies in the range
100 to 103 (both 100 and 103 are included in the range).

Conditions based on a list


To specify a list of values, IN operator is used. This operator select values that match any value in
the given list.
e.g. SELECT * FROM student WHERE city IN (‗Jammu‘,‘Amritsar‘,‘Gurdaspur‘);
The above command displays all those records whose city is either Jammu or Amritsar or
Gurdaspur.

Conditions based on Pattern


SQL provides two wild card characters that are used while comparing the strings with LIKE
operator.
a. Percent(%) Matches any string
b. Underscore(_) Matches any one character

e.g SELECT Roll_no, name, city FROM student WHERE Roll_no LIKE ―%3‖;
displays those records where last digit of Roll_no is 3 and may have any number of characters in
front.
16
e.g SELECT Roll_no, name, city FROM student WHERE Roll_no LIKE ―1_3‖;
displays those records whose Roll_no starts with 1 and second letter may be any letter but ends
with digit 3.

ORDER BY Clause
ORDER BY clause is used to display the result of a query in a specific order(sorted order).
The sorting can be done in ascending or in descending order. It should be kept in mind that the
actual data in the database is not sorted but only the results of the query are displayed in sorted
order.
e.g. SELECT name, city FROM student ORDER BY name;
The above query returns name and city columns of table student sorted by name in
increasing/ascending order.
e.g. SELECT * FROM student ORDER BY city DESC;
It displays all the records of table student ordered by city in descending order.
Note:- If order is not specifies that by default the sorting will be performed in ascending order.

GROUP BY Clause
The GROUP BY clause can be used in a SELECT statement to collect data across multiple records
and group the results by one or more columns.
The syntax for the GROUP BY clause is:
SELECT column1, column2, ...column_n, aggregate_function (expression)
FROM tables
WHERE conditions
GROUP BY column1, column2, ... column_n;
aggregate_function can be a function such as SUM, COUNT, MAX, MIN, AVG etc.

e.g SELECT name, COUNT(*) as "Number of employees"


FROM student
WHERE marks>350
GROUP BY city;

HAVING Clause
The HAVING clause is used in combination with the GROUP BY clause. It can be used in a
SELECT statement to filter the records that a GROUP BY returns.
The syntax for the HAVING clause is:
SELECT column1, column2, ...column_n, aggregate_function (expression)
FROM tables
WHERE predicates
GROUP BY column1, column2, ... column_n
HAVING condition1 ... condition_n;

e.g SELECT SUM(marks) as "Total marks"


FROM student
GROUP BY department
HAVING SUM(sales) > 1000;
Note: select statement can contain only those attribute which are already present in the group
by clause.

ALTER TABLE Command (DDL)

In SQL if we ever need to change the structure of the database then ALTER TABLE command is
used. By using this command we can add a column in the existing table, delete a column from a
table or modify columns in a table.

17
Adding a column
The syntax to add a column is:-

ALTER TABLE table_name


ADD column_name datatype;

e.g ALTER TABLE student ADD(Address varchar(30));


The above command add a column Address to the table Student.
If we give command SELECT * FROM student;
The following data gets displayed on screen:
Roll_no Name Class Marks City Address
101 Rohan XI 400 Jammu
102 Aneeta Chopra XII 390 Udhampur
103 Pawan Kumar IX 298 Amritsar
104 Rohan IX 376 Jammu
105 Sanjay VII 240 Gurdaspur
113 AnjuMAhajan VIII 432 Pathankot

Note that we have just added a column and there will be no data under this attribute.
UPDATE command can be used to supply values / data to this column.

Removing a column

ALTER TABLE table_name


DROP COLUMN column_name;

e.g ALTER TABLE Student


DROP COLUMN Address;
The column Address will be removed from the table student.

DROP TABLE Command


Sometimes you may need to drop a table which is not in use. DROP TABLE command is used to
Delete / drop a table permanently. It should be kept in mind that we can not drop a table if it
contains records. That is first all the rows of the table have to be deleted and only then the table can
be dropped. The general syntax of this command is:-
DROP TABLE <table_name>;
e.g DROP TABLE student;
This command will remove the table student

CREATE VIEW Command

In SQL we can create a view of the already existing table that contains specific attributes of the
table.
e. g. the table student that we created contains following fields:
Student (Roll_no, Name, Marks, Class, City)
Suppose we need to create a view v_student that contains Roll_no,name and class of student table,
then Create View command can be used:
CREATE VIEW v_student AS SELECT Roll_no, Name, Class FROM student;
The above command create a virtual table (view) named v_student that has three attributes as
mentioned and all the rows under those attributes as in student table.

18
We can also create a view from an existing table based on some specific conditions, like
CREATE VIEW v_student AS SELECT Roll_no, Name, Class FROM student WHERE City
<>‘Jammu‘;

Aggregate functions SQL

Some of the commonly used Aggregate functions are sum() , avg(), count(), min(), max() etc.
e.g. SELECT sum(marks) FROM student;
displays the sum of all the marks in the table student.
e.g. SELECT min(Roll_no), max(marks) FROM student;
displays smallest Roll_no and highest marks in the table student.
String Functions in SQL
String functions
These functions are used to deal with the string type values like
ASCII, LOWEWR, UPPER, LEN, LEFT, RIGHT, TRIM, LTRIM, RTRIM etc.
For eg.SELECT LOWER('STRING FUNCTION') from dual;

Equi Join
Equi Joins are used to give information in different tables. It is a special type of join in which we
use only equality operator.
For example
SELECT *
FROM product, customer
WHERE product. product_no = customer. procuct_no;
(or)
SELECT *
FROM product p, customer c
WHERE p.product_no=c.procuct_no;

SQL Non-equi joins


The non-equi join is a type of join in which, we use only relational operators except equal operator.
These
include>, <, >=, >= and !=.
For example
SELECT *
FROM product, customer
WHERE product. product_no != customer.procuct_no;

Solved Questions
Q1. Differentiate between Table and View 1
A Table is a repository of data. The table resides physically in the database.
A View is not a part of the database's physical representation. It is created on a table or another
view. It is precompiled, so that data retrieval behaves faster, and also provides a secure accessibility
mechanism.
Q2. Write SQL commands for (a) to (f) and write output for (g) on the basis of PRODUCTS
relation given below: 1 mark each
PRODUCT TABLE
PCODE PNAME COMPANY PRICE STOCK MANUFACTURE
WARRANTY
P001 TV BPL 10000 200 12-JAN-2008 3
P002 TV SONY 12000 150 23-MAR-2007 4
P003 PC LENOVO 39000 100 09-APR-2008 2
P004 PC COMPAQ 38000 120 20-JUN-2009 2
P005 HANDYCAM SONY 18000 250 23-MAR-2007 3
19
a) To show details of all PCs with stock of TV more than 110.
b) To list the company which gives warranty for more than 2 years.
c) To find stock value of the BPL company where stock value is sum of the products of price and
stock.
d) To show number of products from each company.
e) To count the number of PRODUCTS which shall be out of warranty on 20-NOV-2010.
f) To show the PRODUCT name which are within warranty as on date.
g). Give the output of following statement.
(i) Select COUNT(distinct company) from PRODUCT;.
(ii) Select MAX(price)from PRODUCT where WARRANTY<=3;

Ans a: select * from products where pname=‘TV‘ and stock>110;


Ans b: select company from products where warranty>2;
Ans c: select sum(price*stock) from PRODUCTS where company=‘BPL‘;
Ans d: select company,COUNT(*) from products group by company;
Ans e: select count(*) from products where (‗20-NOV-2010‘- manufacture)/365>warranty;
Ans f: select pname from products where (sysdate- manufacture)/365<warranty;
Ansg (i): 4(ii): 39000

Unsolved Questions
1. Write SQL commands for (a) to (f) and write output for (g) on the basis of SchoolBus relation
given below. 1 mark each
Table :SchoolBus
Rtno Area_covered Capacity Noofstudents Distance Transporter Charges
1 Vasantkunj 100 120 10 Shivamtravels 100000
2 HauzKhas 80 80 10 Anand travels 85000
3 Pitampura 60 55 30 Anand travels 60000
4 Rohini 100 90 35 Anand travels 100000
5 Yamuna Vihar 50 60 20 Bhalla Co. 55000
6 Krishna Nagar 70 80 30 Yadav Co. 80000
7 Vasundhara 100 110 20 Yadav Co. 100000
8 PaschimVihar 40 40 20 Speed travels 55000
9 Saket 120 120 10 Speed travels 100000
10 JankPuri 100 100 20 Kisan Tours 95000
(b) To show all information of students where capacity is more than the no of student in order of
rtno.
(c) To show area_covered for buses covering more than 20 km., but charges less then 80000.
(d) To show transporter wise total no. of students traveling.
(e) To show rtno, area_covered and average cost per student for all routes where average cost
per student is - charges/noofstudents.
(f) Add a new record with following data:
(11, ― Moti bagh‖,35,32,10,‖ kisan tours ―, 35000)
(g) Give the output considering the original relation as given:
(i) select sum(distance) from schoolbus where transporter= ― Yadav travels‖;
(ii) select min(noofstudents) from schoolbus;
(iii) selectavg(charges) from schoolbus where transporter= ― Anand travels‖;
(iv) select distinct transporter from schoolbus;

20
2. Write SQL commands for (a) to (f) and write output for (g) on the basis of Graduate relation
given below 1 mark each
TABLE : GRADUATE
S.NO NAME STIPEND SUBJECT AVERAGE DIV.
1 KARAN 400 PHYSICS 68 I
2 DIWAKAR 450 COMP. Sc. 68 I
3 DIVYA 300 CHEMISTRY 62 I
4 REKHA 350 PHYSICS 63 I
5 ARJUN 500 MATHS 70 I
6 SABINA 400 CEHMISTRY 55 II
7 JOHN 250 PHYSICS 64 I
8 ROBERT 450 MATHS 68 I
9 RUBINA 500 COMP. Sc. 62 I
10 VIKAS 400 MATHS 57 II
(a) List the names of those students who have obtained DIV 1 sorted by NAME.
(b) Display a report, listing NAME, STIPEND, SUBJECT and amount of stipend received in a
year assuming that the STIPEND is paid every month.
(c) To count the number of students who are either PHYSICS or COMPUTER SC graduates.
(d) To insert a new row in the GRADUATE table: 11,‖KAJOL‖, 300, ―computer sc‖, 75, 1
(e) Give the output of following sql statement based on table GRADUATE:
(i) Select MIN(AVERAGE) from GRADUATE where SUBJECT=‖PHYSICS‖;
(ii) Select SUM(STIPEND) from GRADUATE WHERE div=2;
(iii) Select AVG(STIPEND) from GRADUATE where AVERAGE>=65;
(iv) Select COUNT(distinct SUBDJECT) from GRADUATE;
(f) Assume that there is one more table GUIDE in the database as shown below:
Table: GUIDE
MAINAREA ADVISOR
PHYSICS VINOD
COMPUTER SC ALOK
CHEMISTRY RAJAN
MATHEMATICS MAHESH
g) What will be the output of the following query:
Select name, advisor from graduate, guide where subject = mainarea;

3. Write SQL command for (a) to (g) on the basis of the table SPORTS 1 mark each

Table: SPORTS
Student NO Class Name Game1 Grade Game2 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 Atheletics C

(a) Display the names of the students who have grade ‗C‘ in either Game1 or Game2 or
both.
(b) Display the number of students getting grade ‗A‘ in Cricket.
(c) Display the names of the students who have same game for both Game1 and Game2.
(d) Display the games taken up by the students, whose name starts with ‗A‘.

21
(e) Assign a value 200 for Marks for all those who are getting grade ‗B‘ or grade ‗A‘ in both
Game1 and Game2.
(f) Arrange the whole table in the alphabetical order of Name.
(g) Add a new column named ‗Marks‘.

4. Write SQL command for (i) to (iv)and give output for (v) on the basis of the table
Employees & EmpSalary 1 mark each
Table: Employees
Empid Firstname Lastname Address City
010 Ravi Kumar Raj nagar GZB
105 Harry Waltor Gandhi nagar GZB
152 Sam Tones 33 Elm St. Paris
215 Sarah Ackerman 440 U.S. 110 Upton
244 Manila Sengupta 24 Friends New Delhi
street
300 Robert Samuel 9 Fifth Cross Washington
335 Ritu Tondon Shastri Nagar GZB
400 Rachel Lee 121 Harrison New York
St.
441 Peter Thompson 11 Red Road Paris
Table:EmpSalary
Empid Salary Benefits Designation
010 75000 15000 Manager
105 65000 15000 Manager
152 80000 25000 Director
215 75000 12500 Manager
244 50000 12000 Clerk
300 45000 10000 Clerk
335 40000 10000 Clerk
400 32000 7500 Salesman
441 28000 7500 salesman
Write the SQL commands for the following : (1 x 4 = 4)
(i) To show firstname, lastname, address and city of all employees living in paris
(ii) To display the content of Employees table in descending order of Firstname.
(iii) To display the firstname, lastname and total salary of all managers from the tables
Employee and empsalary , where total salary is calculated as salary+benefits.
(iv) To display the maximum salary among managers and clerks from the table Empsalary.

(v) Give the Output of following SQL commands: (.5 x 4 = 2)


(i) Select firstname, salary from employees ,empsalary where designation = ‗Salesman‘
and Employees.empid=Empsalary.empid;
(ii) Select count(distinct designation) from empsalary;
(iii) Select designation, sum(salary) from empsalary group by designation having
count(*) >2;
(iv) Select sum(benefits) from empsalary where designation =‘Clerk‘;

5. Differentiate between (1 x 4 = 4)
1. Update and Alter Command
2. Drop and Delete command
3. DDL and DML Sql Commands
4. Oder by and Group by clause
6. Pooja created a table 'bank' in SQL. Later on, she found that there should have been another
column in the table. Which command is used to add column to the table? 1
22
7. Surpreeth wants to add two more records of customer in customer table. Which command is
used to implement this? 1
8. Deepak wants to remove all rows from the table Bank. But he needs to maintain the
structure of the table. Which command is used to implement the same? 1
9. While creating table 'customer', Rahul forgot to add column 'price'. Which command is used
to add new column in the table. Write the command to implement the same. 1
10. Write the syntax of creating table command. 1
11. Write the syntax of dropping table command. 1
12. What all are the clause possible in select statement. 3
13. What is the default value of order by command. 1
14. Define the following. 1 mark each
a) Union
b) Cartesian product
c) Equi Join
d) Non equi join

Topic : Object Oriented Programming Concepts

Object Oriented Programming follows bottom up approach in program design and emphasizes on
safety and security of data..
FEATURES OF OBJECT ORIENTED PROGRAMMING:
Inheritance:
Inheritance is the process of forming a new class from an existing class or base class. The base class
is also known as parent class or super class.
Derived class is also known as a child class or sub class. Inheritance helps in reusability of code ,
thus reducing the overall size of the program

Data Abstraction:
It refers to the act of representing essential features without including the background details
.Example : For driving , only accelerator, clutch and brake controls need to be learnt rather than
working of engine and other details.

Data Encapsulation:
It means wrapping up data and associated functions into one single unit called class..
A class groups its members into three sections: public, private and protected, where private and
protected members remain hidden from outside world and thereby helps in implementing data
hiding.

Modularity :
The act of partitioning a complex program into simpler fragments called modules iscalled as
modularity.
It reduces the complexity to some degree and
It creates a number of well-defined boundaries within the program .

Polymorphism:
Poly means many and morphs mean form, so polymorphism means one name multiple forms.
It is the ability for a message or data to be processed in more than one form.
C++ implements Polymorhism through Function Overloading , Operator overloading and Virtual
functions .

23
Data hiding is the implementation details of a class that are hidden from the user.
classMyClass
{public:
int sample();
int example(char *se)
intendfunc();
......... //Other member functions
private:
int x;
float sq;
......... //Other data members
};
In the above example, the data members integer x, float sq and other data members and member
functions sample(),example(char* se),endfunc() and other member functions are bundled and put
inside a single autonomous entity called class MyClass. This exemplifies the concept of
Encapsulation.

Encapsulation alone is a powerful feature that leads to information hiding, abstract data type and
friend functions.

Objects and Classes:


The major components of Object Oriented Programming are. Classes & Objects
A Class is a group of similar objects. Objects share two characteristics state and behavior (data
members and member functions)
Important Terms
OOP Term Definition
Method Same as function, but the typical OO notation is used for the call, i.e.
f(x,y) is written x.f(y) where x is an object of class that contains this f
method.
Send a message Call a function (method)
Instantiate Allocate a class/struct object (ie, instance) with new
Class A struct with both data and functions
Object Memory allocated to a class/struct. Often allocated with new.
Member A field or function is a member of a class if it's defined in that class
Constructor A member function having same name as that of the class that
initializes data members of an object at the time of creation of the
object.
Destructor Function-like code that is called when an object is deleted to free any
resources (e.g. memory) that is has pointers to. It is automatically
invoked when object goes out of scope.
Inheritance Deriving properties of parent class to the child class.
Polymorphism Defining functions with the same name, but different parameters.
Overload A function is overloaded if there is more than one definition. See
polymorphism.
Sub class Same as child, derived, or inherited class.
Super class Same as parent or base class.
24
Attribute Same as data member or member field
Advantages of OOP‟s
1. Simplicity
2. Modularity
3. Modification
4. Extensibility
5. Maintainability
6. Code Reusability

Applications of OOP‟s
1. Object Oriented Databases
2. Artificial Intelligence and Expert System
3. Decision Support and Office Automation System

Programming paradigms:
A methodology of designing and implementing programs with the help of various features of
programming language is termed as Programming paradigms.

Procedural Programming:
It is also known as procedural programming or modular programming. Languages like PASCAL,
C, Basic, Fortran are all procedural programming languages. A program written in procedural
programming consists of various modules with a set of instructions which the computer executes.
Procedures or functions are implemented on the data and variables to perform a task. A program
written in procedural language contains one or more procedures.

Solved Questions
Q1. What two key features of an object are bound together by data Encapsulations? (1)
Data Encapsulation feature binds together the state (data) and behavior (functions) of an object in
one unit.
Q2. What is the fundamental approach of Object oriented Programming ? (1)
The fundamental approach of object oriented Programming is that it lays emphasis on the objects
rather than on procedures or methods.
Q3.How is OOP‘S implemented in C++? (2)
A class binds together data and its associated functions under one unit thereby enforcing
Encapsulation. The private and protected members remain hidden from the outside world. Thus, A
class enforces Data hiding . Also the outside world is given only essential information through
public members, thereby enforcing Abstraction.
Unsolved questions
1. What do you understand by Data Encapsulation and Data Hiding? Also, give an example in
C++to illustrate both? (2)
2. What is the significance of message passing in Object oriented Programming? (2)
3. What do you mean by reusability of code? (2)
4. Define Inheritance and Polymorphism. (2)
5. Why C++ is called as Object oriented Programming? (2)
6. What is significance of classes in Object oriented Programming? (2)
7. Name the two types of classes in Inheritance. (2)
8. When should function overloading be preferred over default arguments? (2)
9. Differentiate between (1 x 5= 5)
a. Class and Object
b. Data Abstraction and Data Encapsulation
c. Function overloading and Method Overloading
d. Base class and Derived class
e. Modular programming and Object Oriented Programming
10. What is robustness of a program? (2)
25
Topic : Function Overloading

Function overloading is the method for calling several functions having the same name .These
functions are differentiated during the calling process by the number and types of arguments passed
to these functions.

• In C++, two or more functions can share the same name as long as their parameter declarations
are different.
• In this situation, the functions that share the same name are said to be overloaded, and the process
is referred to as function overloading
To see why function overloading is important, first consider three functions defined by the C
subset: abs(), labs(), and fabs(). The abs() function returns the absolute value of an integer, labs()
returns the absolute value of a long, and fabs() returns the absolute value of a double.
• Although these functions perform almost identical actions, in C three slightly different names
must be used to represent these essentially similar tasks.
In C++ Function overloading is used to solve the above problem:
Process of executing Overloaded Functions
In function overloading, a function call always matches the function prototype having same number
and type of arguments and then calls the specific function for execution. There can be three possible
causes while making a call to overloaded functions.
1. Exact match is found: The call is resolved to particular overloaded functions.
2. No match is found: The arguments cannot be matched to any overloaded function.
3. An ambiguous match is found: The arguments matched more than one overloaded
function.
4. Search a match through user-defined conversion.
Function Overloading and Ambiguity • Ambiguous statements are errors, and programs containing
ambiguity will not compile. • By far the main cause of ambiguity involves C++'s automatic type
conversions.
Function Overloading and Ambiguity
• void f(int x);
• void f(int &x); // error
• two functions cannot be overloaded when the only difference is that one takes a reference
parameter and the other takes a normal, call-by-value parameter.
Overloading Constructor Functions
• Many times you will create a class for which there are two or more possible ways to construct an
object.
• In these cases, you will want to provide an overloaded constructor function for each way.
• The user is free to choose the best way to construct an object given the specific circumstance
Example : A same function print() is being used to print different data types:

#include <iostream.h>
class printData
{
public:
void print(int i) {cout<< "Printing int: " << i <<endl;}
void print(double f) {cout<< "Printing float: " << f <<endl;}
void print(char* c) {cout<< "Printing character: " << c <<endl;}
};

int main(void)
{
printData pd; // Call print to print integer
pd.print(5); // Call print to print float
pd.print(500.263);//// Call print to print character
26
pd.print("Hello C++"); return 0; }
When the above code is compiled and executed, it produces following result:
Printing int: 5
Printing float: 500.263
Printing character: Hello C++

Solved Questions
Q1. What is Polymorphism? (2)
It is a feature of C++ by which functions and operators acquire the capability of taking more than
one form, ie. When the same function is performing different tasks.
Q2. What are the rules for overloaded function? (2)
Either the number of arguments or types of arguments should be different.
Q3.Write a code to show function overloading by displaying cube of Integer, Float and Double
#include<iostream.h> (3)
#include<conio.h>
class demo
{
private:
int a1,a2;
float b1,b2;
double d1,d2;
public:
void getdata();
int cube(int);
float cube(float);
double cube(double);
void display();
};
void demo:: getdata()
{
cout<<― Enter an integer :‖; cin>> a1;
cout<<― Enter a float no:‖; cin>> b1;
cout<<― Enter a double no :‖; cin>> d1;
}
int demo :: cube (int a1)
{
return (a1*a1*a1);
}
float demo:: cube (float b1)
{
return (b1*b1*b1*);
}
double demo :: cube(double d1)
{
return(d1*d1*d1);
}
void main()
{
demo obj;
a2=obj.cube(a1);
b2=obj.cube(b1);
d2=obj.cube(d1);
cout<<a2<<b2<<d2;
getch();
27
}
Unsolved Questions
1. Find the output of the following program: (2)
#include<iostream.h>
int fun(int &x,int y=10)
{
if(x%y==0)
return ++x;
else
return y--;
}
void main()
{
int p=20,q=23;
q=func(p,q);
cout<<p<<‖<<‖<<q<<\n‖;
p=func(q);
cout<<p<<‖<<‖<<q<<\n‖;
q=func(p)
cout<<p<<‖<<‖<<q<<\n‖;
}
2. Write a program that contains function sum to add numbers of different data types using
function overloading. (3)
3. Write a program to calculate area of circle, rectangle and triangle using function
overloading. (3)
4. Write the output of the following program: (3)
#include<iostream.h>
int num(int &a, int b=25)
{
int temp=a-b;
a-=temp;
if(b==25)
cout<<a<<temp<<‖\n‖;
}
void main()
int x=100,y=200;
num(x);
cout<<x<<y<<endl;
num(y,x);
cout<<x<<y<<endl;
}

5. What are the major limitations of default arguments? (2)

6. Discuss how the best match is found when a call to an overloaded function is encountered.
Give examples. (2)

7. The compiler interprets more than one function definition having same name.‖ Write steps
does it follow to distinguish these? (3)

8. Give the output: (3)


#include <iostream.h>
class printData
{
28
public:
void print(int i) {
cout<< "Printing int: " << i <<endl;
}
void print(double f) {
cout<< "Printing float: " << f <<endl;
}
void print(char* c) {
cout<< "Printing character: " << c <<endl;
}
};

int main(void)
{
printData pd; // Call print to print integer
pd.print(5); // Call print to print float
pd.print(500.263);//// Call print to print character
pd.print("Hello C++"); return 0;
}

9. Write a program to display area of a circle, rectangle or a triangle showing polymorphism


implemented using function overloading. (3)

10. Define arguments of function . Give a suitable example. (2)

Topic : Classes and Objects

Object-Oriented Programming groups related data and functions together in a class, generally
making data private and only some functions public. Restricting access decreases coupling and
increases cohesion. It has proven to be very effective in reducing the complexity increase with large
programs. For small programs may be difficult to see the advantage of OOP over, eg, structured
programming because there is little complexity regardless of how it's written.

It helps in programming approach in order to built robust user friendly and efficient software and
provides the efficient way to maintain real world software. OOP is an Object Oriented
Programming language which is the extension of Procedure Oriented Programming language.
OOPs reduce the code of the program because of the extensive feature of Polymorphism. OOPs
have many properties such as DataHiding, Inheritance Data Abstraction, Data Encapsulation and
many more. The main aim is to creating an Object to the Entire program and that to we can control
entire program using the Object. The main features of OOPS is Polymorphism, Multiple
Inheritance, Abstraction and Encapsulation.

Objects:
Object is the basic unit of object-oriented programming. Objects are identified by its unique name.
An object represents a particular instance of a class.

An Object is a collection of data members and associated member functions also known as
methods.
29
Classes:
 Classes are data types based on which objects are created.
 Thus a Class represents a set of individual objects. Characteristics of an object are
represented in a class as Properties. The actions that can be performed by objects become
functions of the class and are referred to as Methods.
 Classes are the blueprints upon which objects are created. E.g when we design a map of the
house, the architect first designs it. Once it is designed, the raw material is used to build the
house. In this example, Design of the house is CLASS (blueprint) and the house built on the
basis of design is an object.

No memory is allocated when a class is created. Memory is allocated only when an object is
created, i.e., when an instance of a class is created.

The major components of Object Oriented Programming are. Classes & Objects
A Class is a group of similar objects. Objects share two characteristics state and behavior (data
members and member functions)

Classes in Programming :
 It is a collection of variables, often of different types and its associated functions.
 Class just binds data and its associated functions under one unit there by enforcing

Encapsulation.
 Classes define types of data structures and the functions that operate on those data
structures.
 A class defines a blueprint for a data type.

Declaration/Definition :
A class definition starts with the keyword class followed by the class name; and the class body,
enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a
list of declarations.
class class_name
{
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
[Note: the default access specifier is private.
Example :
class Box
{
int a;
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
} container; // container is an object of class Box

Access specifiers in Classes:


Access specifiers are used to identify access rights for the data and member functions of the class.
There are three main types of access specifiers in C++ programming language:

30
 private
 public
 protected

Member-Access Control
Type of Access Meaning
Private Class members declared as private can be used only by member functions and friends
(classes or functions) of the class.
Protected Class members declared as protected can be used by member functions and friends
(classes or functions) of the class. Additionally, they can be used by classes derived
from the class.
Public Class members declared as public can be used by any function.

Importance of Access Specifiers


Access control helps prevent you from using objects in ways they were not intended to be
used. Thus it helps in implementing data hiding and data abstraction.

OBJECTS in C++:
Objects represent instances of a class. Objects are basic run time entities in an object
oriented system.
Creating object / defining the object of a class:
The general syntax of defining the object of a class is:-
Class_name object_name;
In C++, a class variable is known as an object. The declaration of an object is similar to that of a
variable of any data type. The members of a class are accessed or referenced using object of a class.
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Both of the objects Box1 and Box2 will have their own copy of data members.

Accessing / calling members of a class. All member of a class are private by default.
 Private member can be accessed only by the function of the class itself.
 Public member of a class can be accessed through any object of the class. They are accessed
or called using object of that class with the help of dot operator (.).
The general syntax for accessing data member of a class is:-
Object_name.Data_member = value;
The general syntax for accessing member function of a class is:-
Object_name.Function_name( actual arguments );

Class methods definitions (Defining the member functions)


Member functions can be defined in two places:-
 Outside the class definition
The member functions of a class can be defined outside the class definitions. It is only declared
inside the class but defined outside the class. The general form of member function definition
outside the class definition is:
Return_type Class_name::function_name (argument list)
{
Function body
}
Where symbol :: is a scope resolution operator.

class sum
{
31
int A, B, Total;
public:
void getdata ();
void display ();
};
void sum:: getdata () // Function definition outside class definition Use of :: operator
{
cout<<‖ \ n enter the value of Aand B‖;
cin>>A>>B;
}
void sum:: display () // Function definition outside class definition Use of :: operator
{
Total =A+B;
cout<<‖\n the sum of A and B=‖<<Total;
}
 Inside the class definition
The member function of a class can be declared and defined inside the class definition.
class sum
{
int A, B, Total;
public:
void getdata ()
{
cout< ‖\n enter the value of A and B‖;
cin>>A>>B;
}
void display ()
{
total = A+B;
cout<<‖\n the sum of A and B=‖<<total;
}
};

Differences between struct and classes in C++


Structure Class
 Defined using struct keyword  Defined using class keyword
 Members are public by default  Members are private by default
 It cannot be inherited  It can be inherited

INLINE FUNCTIONS
 Inline functions definition starts with keyword inline
 The compiler replaces the function call statement with the function code
itself(expansion) and then compiles the entire code.
 They run little faster than normal functions as function calling overheads are saved.
 A function can be declared inline by placing the keyword inline before it.
Example
inline void Square (int a)
{
In place of function call ,
function body is substituted
because Square () is inline
function
cout<<a*a;
32
}
void main()
{.
Square(4); { cout<<4*4;} // { cout<<4*4;}
Square(8) ; { cout<<8*8; } // { cout<<8*8; }
}

Pass Object As An Argument


/*C++ PROGRAM TO PASS OBJECT AS AN ARGUMEMT. The program Adds the two
heights given in feet and inches. */

#include<iostream.h>
#include<conio.h>
class height
{
intfeet,inches;
public:
void getht(intf,int i)
{
feet=f;
inches=i;
}
void putheight()
{
cout<< "\nHeight is:"<< feet<< "feet\t"<< inches<< "inches"<<endl;
}
void sum(height a,height b)
{
height n;
n.feet = a.feet + b.feet;
n.inches = a.inches + b.inches;
if(n.inches ==12)
{
n.feet++;
n.inches = n.inches -12;
}
cout<<endl<< "Height is "<<n.feet<< " feet and "<<n.inches<<endl;
}
};
void main()
{ heighth,d,a;
clrscr();
h.getht(6,5);
a.getht(2,7);
h.putheight();
a.putheight();
d.sum(h,a);
getch();
}
/**********OUTPUT***********
Height is 6feet 5inches
Height is 2feet 7inches
Height is 9 feet and 0
33
Solved Questions
Q 1) Define a class TAXPAYER in C++ with following description:
Private members :
Name of type string
PanNo of type string
Taxabincm (Taxable income) of type float
TotTax of type double
A function CompTax( ) to calculate tax according to the following slab:
Taxable Income Tax%
Up to 160000 0
>160000 and <=300000 5
>300000 and <=500000 10
>500000 15
Public members :
 A parameterized constructor to initialize all the members
 A function INTAX( ) to enter data for the tax payer and call function CompTax( ) to assign
TotTax.
 A function OUTAX( ) to allow user to view the content of all the data members.

Ans.
class TAXPAYER
{
char Name[30],PanNo[30];
float Taxabincm;
double TotTax;
void CompTax()
{
if(Taxabincm>500000)
TotTax= Taxabincm*0.15;
else if(Taxabincm>300000)
TotTax= Taxabincm*0.1;
else if(Taxabincm>160000)
TotTax= Taxabincm*0.05;
else
TotTax=0.0;
}
public:
TAXPAYER(char nm[], char pan[], float tax, double ttax) //parameterized constructor
{
strcpy(Name,nm);
strcpy(PanNo,pan);
Taxabincm=tax;
TotTax=ttax;
}

void INTAX()
{
gets(Name);
cin>>PanNo>>Taxabincm;
CompTax();
}
void OUTAX()
{ cout<<Name<<‘\n‘<<PanNo<<‘\n‘<<Taxabincm<<‘\n‘<<TotTax<<endl; }
34
};
Q 2 :Define a class HOTEL in C++ with the following description:

Private Members
 Rno //Data Member to store Room No
 Name //Data Member to store customer Name
 Tariff //Data Member to store per day charge
 NOD //Data Member to store Number of days
 CALC //A function to calculate and return amount as NOD*Tariff and if the value
of NOD*Tariff is more than 10000 then 1.05*NOD*Tariff
Public Members:
o Checkin( ) //A function to enter the content RNo,Name, Tariff and NOD
o Checkout() //A function to display Rno, Name, Tariff, NOD and Amount (Amount to be
displayed by calling function CALC( )
Solution :

#include<iostream.h>
class HOTEL
{ unsignedint Rno;
char Name[25];
unsignedint Tariff;
unsignedint NOD;
int CALC( )
{
int x;
x=NOD*Tariff;
if( x>10000)
return(1.05*NOD*Tariff);
else
return(NOD*Tariff);
}
public:
void Checkin()
{
cin>>Rno>>Name>>Tariff>>NOD;
}
void Checkout()
{
cout<<Rno<<Name<<Tariff<<NOD<<CALC();
}
};
Unsolved Questions
1. Define a class Applicant in C++ with following description: (4)
Private Members
 A data member ANo ( Admission Number) of type long
 A data member Name of type string
 A data member Agg(Aggregate Marks) of type float
 A data member Grade of type char
 A member function GradeMe( ) to find the Grade as per the Aggregate Marks obtained
by a student. Equivalent Aggregate marks range and the respective Grades are shown as
follows
Aggregate Marks Grade
35
> = 80 A
Less than 80 and > = 65 B
Less than 65 and > = 50 C
Less than 50 D

Public Members
o A function Enter( ) to allow user to enter values for ANo, Name, Agg& call function
GradeMe( ) to find the Grade
o A function Result ( ) to allow user to view the content of all the data members.
2. Define a class ITEM in C++ with following description: (4)
Private members:
 Icode of type integer (Item Code)
 Item of type string (Item Name)
 Price of type Float (Price of each item)
 Qty of type integer (Quantity in stock)
 Discount of type float (Discount percentage on the item)
 A find function finddisc( ) to calculate discount as per the following rule:
If Qty<=50 discount is 0%
If 50 <Qty<=100 discount is 5%
If Qty>100 discount is 10%
Public members :
o A function Buy( ) to allow user to enter values for Icode, Item,Price, Qty and call function
Finddisc ( ) to calculate the discount.
o A function showall ( ) to allow user to view the content of all the data members.

3. Define a class employee with the following specifications : 4


Private members of class employee
 empno integer
 ename 20 characters
 basic, hra, da float
 netpay float
 calculate() A function to calculate basic + hra + da with float return type
Public member function of class employee
o havedata() function to accept values for empno, sname, basic, hra, da and invoke calculate()
to calculate netpay.
o dispdata() function to display all the data members on the screen.

4 Define a class Student with the following specifications : 4


Private members :
 roll_no integer
 name 20 characters
 class 8 characters
 marks[5] integer
 percentage float
 Calculate() a function that calculates overall percentage of marks and return the percentage
of marks.
Public members :
36
o Readmarks() a function that reads marks and invoke the Calculate function.
o Displaymarks() a function that prints the marks.

2 Marks Practice Problems


1. What is relation between class and object?
2. What are inline functions? Give example
3. Difference between private & public access specifiers.
4. How class implements data-hiding & encapsulation?
5. What is the difference between structure and a class?
6. How is inline function different from a normal function?

Topic :Constructors And Destructors

CONSTRUCTORS :
A member function with the same as its class is called Constructor and it is used to initialize
the object of that class with a legal initial value.
Example :
class Student
{
introllno;
float marks;
public:
student( ) //Constructor
{
rollno = 0 ;
marks = 0.0 ;
}
//other public members
};

TYPES OF CONSRUCTORS:
1. Default Constructor:
A constructor that accepts no parameter is called the Default Constructor. If you don't declare a
constructor or a destructor, the compiler makes one for you. The default constructor and destructor
take no arguments and do nothing.
2. Parameterized Constructors:
A constructor that accepts parameters for its invocation is known as parameterized
Constructors , also called as Regular Constructors.

DESTRUCTORS:
A destructor is also a member function whose name is the same as the class name but is
preceded by tilde(―~‖).It is automatically by the compiler when an object is destroyed. Destructors
are usually used to deallocate memory and do other cleanup for a class object and its class members
when the object is destroyed.
A destructor is called for a class object when that object passes out of scope or is explicitly
deleted.
37
Example :
class TEST
{
int Regno,Max,Min,Score;
Public:
TEST( ) // Default Constructor
{ }
TEST (int Pregno,int Pscore) // Parameterized Constructor
{
Regno = Pregno ;Max=100;Max=100;Min=40;Score=Pscore;
}
~ TEST ( ) // Destructor
{ cout<<‖TEST Over‖<<endl;}
};

The following points apply to constructors and destructors:


 Constructors and destructors do not have return type, not even void nor can they return
values.
 References and pointers cannot be used on constructors and destructors because their
addresses cannot be taken.
 Constructors cannot be declared with the keyword virtual.
 Constructors and destructors cannot be declared static, const, or volatile.
 Unions cannot contain class objects that have constructors or destructors.
 The compiler automatically calls constructors when defining class objects and calls
destructors when class objects go out of scope.
 Derived classes do not inherit constructors or destructors from their base classes, but they
do call the constructor and destructor of base classes.
 The default destructor calls the destructors of the base class and members of the derived
class.
 The destructors of base classes and members are called in the reverse order of the
completion of their constructor:
 The destructor for a class object is called before destructors for members and bases are
called.

Copy Constructor
A copy constructor is a special constructor in the C++ programming language used to
create a new object as a copy of an existing object.
A copy constructor is a constructor of the form classname(classname&).The compiler will
use the copy constructors whenever you initialize an instance using values of another instance of
the same type.
Copying of objects is achieved by the use of a copy constructor and assignment operator.
Example :
class Sample{ int i, j;}
public:
Sample(int a, int b) // constructor
{ i=a; j=b; }
38
Sample (Sample & s) //copy constructor
{
j=s.j ; i=s.j;
cout<<‖\n Copy constructor working \n‖;
}
void print (void)
{cout<<i<< j<< ‖\n‖;}
:
};
Note :The argument to a copy constructor is passed by reference, the reason being that whenan
argument is passed by value, a copy of it is constructed. But the copy constructor is creating a
copy of the object for itself, thus, it calls itself. Again the called copy constructor requires
another copy so again it is called.in fact it calls itself again and again until the compiler runs out
of the memory .so, in the copy constructor, the argument must be passed by reference.
The following cases may result in a call to a copy constructor:

When an object is passed by value to a function:


The pass by value method requires a copy of the passed argument to be created for the function to
operate upon .Thus to create the copy of the passed object, copy constructor is invoked

If a function with the following prototype:


void cpyfunc(Sample ); // Sample is a class
Then for the following function call
cpyfunc(obj1); // obj1 is an object of Sample type
The copy constructor would be invoked to create a copy of the obj1 object for use by cpyfunc().

When a function returns an object:


When an object is returned by a function the copy constructor is invoked
Sample cpyfunc(); // Sample is a class and it is return type of cpyfunc()
If funtion cpyfunc() is called by the following statement
obj2 = cpyfunc();
Then the copy constructor would be invoked to create a copy of the value returned by cpyfunc() and
its value would be assigned to obj2. The copy constructor creates a temporary object to hold the
return value of a function returning an object.

1 & 2 Marks Solved Problems:


Q1 :- Answer the questions after going through the following class.
class Exam
{
char Subject[20] ;
int Marks ;
public :
Exam() // Function 1
{
strcpy(Subject, ―Computer‖ ) ; Marks = 0 ;}
Exam(char P[ ]) // Function 2
{
39
strcpy(Subject, P) ;
Marks=0 ;
}
Exam(int M) // Function 3
{
strcpy(Subject, ―Computer‖) ; Marks = M ;
}
Exam(char P[ ], int M) // Function 4
{
strcpy(Subject, P) ; Marks = M ;
}
};
(a) Which feature of the Object Oriented Programming is demonstrated using Function 1,
Function2, Function 3 and Function 4 in the above class Exam?
Ans:- Function Overloading (Constructor overloading)

(b) Write statements in C++ that would execute Function 3 and Function 4 of class Exam.
Ans:- Exam a(10); and Exam b(―Comp‖, 10);

Q2 Consider the following declaration:


class welcome
{
public: welcome (int x, char ch); // constructor with parameter
welcome(); // constructor without parameter
void compute();
private:
int x; char ch;
};
Which of the following are valid statements?
welcome obj (33, ‗a9‘);
welcome obj1(50, ‗9‘);
welcome obj3();
obj1= welcome (45, ‗T‘);
obj3= welcome;
Ans. Valid and invalid statements are
welcome obj (33, ‗a9‘); valid
welcome obj1(50, ‗9‘); valid
welcome obj3(); invalid
obj1= welcome (45, ‗T‘); valid
obj3= welcome; invalid

Q3. class fibonacci


{
private:
int fo,f1,fib;
public:
fibonacci();

40
void increment();
void display();
};
fibonacci::fibonacci()
{
fo=0;
f1=1;
fib=fo+f1;
}
void fibonacci::increment()
{
fo=f1;
f1=fib;
fib=fo+f1; }
void fibonacci:: display()
{
cout<< fib<<―\t‖;
}
void main()
{
clrscr();
fibonacci F;
for(int i=0;i<=15;++i)
{
F.display();
F.increment();
getch();
}
}
Q4.
Answer the following questions after going through the following class:
class Seminar
{
int Time;
public:
Seminar(); //Function 1
void Lecture() //Function 2
{cout<<‖Lectures in the seminar on‖<<end1;}
Seminar(int); //Function 3
Seminar(Seminar &abc); //Function 4
~Seminar() //Function 5
{ cout<<‖Vote of thanks‖<<end1;}
};

(i) In Object Oriented Programming, what is Function 5 referred as and when does it get
invoked/called?
Ans : Function 5 is referred as destructor and it is invoked as soon as the scope of the
object gets over.
(ii) In Object Oriented Programming, which concept is illustrated by Function 1,
Function 3 and Function 4 all together?
Ans : Constructor Overloading (Polymorphism)
(iii) Which category of constructor - Function 1 belongs to? Write an example illustrating

41
the calls for Function 1.
Ans : Default Constructor. Example to invoke function 1  Seminar S;
(iv) Which category of constructor - Function 3 belongs to? Write an example illustrating
the calls for Function 3.
Ans : Parameterised Constructor. Example to invoke function 3  Seminar A(8);
(v) Which category of constructor - Function 4 belongs to? Write an example illustrating
the calls for Function 4.
Ans : Copy Constructor. Example to invoke function 4  Seminar S2(S);
Or Seminar S2 = S;
(vi) Write an example illustrating the calls for Function 3 explicitly.
Ans : Seminar A = Seminar(8);
(vii) Write an example illustrating the calls for Function 4 explicitly.
Ans : Seminar S2 = Seminar(S);
(viii) Write the complete definition for Function 1 to initialize Time as 30.
Ans : Seminar :: Seminar()
{ Time = 30; }
(ix) Write the complete definition for Function 3 to initialize Time with Mytime as
parameter to the Function 3.
Ans : Seminar :: Seminar(int Mytime)
{ Time = Mytime; }
(x) Write the complete definition for Function 4.
Ans : Seminar :: Seminar(Seminar &abc)
{ Time = abc.Time; }

Unsolved Questions
Q1. What do you understand by constructor and destructor functions used in classes? How are these
functions different from other member functions? 2
Q2. What do you understand by default constructor and copy constructor functions used in classes?
How are these functions different from normal constructors? 2
Q3 Given the following C++ code, answer the questions (i) & (ii). 2
class TestMeOut
{ public : ~TestMeOut() // Function 1
{ cout<< "Leaving the examination hall " <<endl; }
TestMeOut() // Function 2
{ cout<< "Appearing for examination " <<endl; }
void MyWork() // Function 3
{ cout<< "Attempting Questions " <<endl; }
};
(i) In Object Oriented Programming, what is Function 1 referred as and when does it get invoked /
called?
(ii) In Object Oriented Programming, what is Function 2 referred as and when does it get invoked /
called?
Q4. Answer the following questions after going through the following class:
class Complex
{
int x; int y;
public:
Complex(); //Function 1
void disp() //Function 2
{cout<<‖The Complex number is : ―<<x<<‖ + ―<<y<<‖i‖<<end1;}

42
Complex(int, int); //Function 3
Complex(Complex &abc); //Function 4
};
(i) Which category of constructor - Function 1 belongs to? Write an example illustrating
the calls for Function 1.
(ii) Which category of constructor - Function 3 belongs to? Write an example illustrating
the calls for Function 3.
(iii) Which category of constructor - Function 4 belongs to? Write an example illustrating
the calls for Function 4.
(v) Write an example illustrating the calls for Function 3 explicitly.
(vi) Write an example illustrating the calls for Function 4 explicitly.
(vii) Write the complete definition for Function 1 to initialize x as 10 and y as 20.
(vii) Write the complete definition for Function 3 to initialize the data members with p
and q as parameters to the Function 3.
(viii) Write the complete definition for Function 4.

Topic : Inheritance

Inheritance -Extending Classes


Inheritance:- Inheritance is the process of creating new classes called derived classes from
existing ones. i.e base classes.
Different form of Inheritance:
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance.
Derived and Base Class:- A derived class extends its features by inheriting the
properties of another class, called base class and adding features of its own.
The general syntax of derived class is :-
class derived _class_name : visibility mode base class name

1. Public Inheritance: When deriving a class from a public base class:


 public members of the base class become public members of the derived class and
 protected members of the base class become protected members of the derived
class.
 A base class's private members are never accessible directly from a derived class,
but can be accessed through calls to the public and protected members of the base class.
2. Protected Inheritance: When deriving from a protected base class, public and protected
members of the base class become protected members of the derived class.
3. Private Inheritance: When deriving from a private base class, public and protected
members of the base class become private members of the derived Class.

Visibility of Class Members


Base class Private Protected Public derivation
Visibility Derivation Derivation
Private Not inherited Not inherited Not inherited
Protected Private Protected Protected
Public Private Protected public-
43
Single Level Inheritance:- Single inheritance is the process of creating new class (derived
class ) from an base class .i.e it creates a copy of base class and can add refinements of its own .

Multilevel Inheritance:
In Multi level inheritance, a subclass inherits from a class that itself inherits from another class

Multiple inheritance
 In Multiple inheritances, a derived class inherits from multiple base classes. It has
properties of both the base classes.

Hierarchical Inheritance: When many derived classes are inherited from single base class
,it is called hierarchical Inheritance

44
Hybrid Inheritance:
 It combines two or more forms of inheritance .In this type of inheritance, we can have
mixture of number of inheritances but this can generate an error of using same name
function from no of classes, which will bother the compiler to how to use the functions.
 Therefore, it will generate errors in the program. This has known as ambiguity or duplicity.
 Ambiguity problem can be solved by using virtual base classes

Solved Questions:
Q1. Write the reasons behind the introduction of inheritance in OOP.
Ans. The major reasons behind the introduction of inheritance in OOP are:(i) It ensures the
closeness with the real world models, (ii) idea of reusability, (iii) transitive nature of
inheritance.
Q2. What are the different forms of inheritance?
Ans. The different forms of inheritance are (i) Single Inheritance, (ii) Multiple Inheritance, (iii)
Hierarchical Inheritance, (iv) Multilevel Inheritance, (v) Hybrid Inheritance.
Q3. How does the access of inherited members depend upon their access specifiers and the
visibility modes of the base class?

Q4. Consider the following declarations and answer the questions given below :
class WORLD
{
int H;
protected :
int S;
public :
void INPUT(int);
void OUTPUT();
};
class COUNTRY : private WORLD // Base class WORLD & Sub class Contry
{
int T;

45
protected :
int U;
public :
void INDATA( int, int)
void OUTDATA();
};
class STATE : public COUNTRY // Base Class COUNTRY & Sub Class STATE
{
int M;
public :
void DISPLAY (void);
};
(i) Name the base class and derived class of the class COUNTRY.
(ii) Name the data member(s) that can be accessed from function DISPLAY().
(iii) Name the member function(s), which can be accessed from the objects of class
STATE.
(iv) Is the member function OUTPUT() accessible by the objects of the class COUNTRY ?

Ans:-
(i) Base class : WORLD
Derived class : STATE
(ii) M.
(iii)DISPLAY(), INDATA() and OUTDATA()
(iv) No

Q5. Consider the following declarations and answer the questions given below :
class living_being
{
char name[20];
protected:
int jaws;
public:
void inputdata(char, int);
void outputdata();
}
class animal : protected living_being
{
int tail;
protected:
int legs;
public:
void readdata(int, int);
void writedata();
};
class cow : private animal
{ char horn_size;
public:
46
void fetchdata(char);
void displaydata();
};
(i) Name the base class and derived class of the class animal.
(ii) Name the data member(s) that can be accessed from function displaydata.
(iii)Name the data member(s) that can be accessed by an object of cow class.
(iv) Is the member function outputdata accessible to the objects of animal class.

Ans:-
(i) Base class : living_being
Derived class : cow
(ii) horn_size, legs, jaws
(iii)fetchdata() and displaydata()
(iv) No

4 marks Practice Problems:


Q1 :- Consider the following declarations and answer the questions given below:
class vehicle
{
int wheels;
protected:
int passenger;
public:
void inputdata( int, int);
void outputdata();
};

class heavyvehicle : protected vehicle


{
int dieselpetrol;
protected:
int load;
public:
void readdata( int, int);
void writedata();
};
class bus:private heavyvehicle
{
char marks[20];
public:
void fetchdata(char);
void displaydata();
};
(i) Name the class and derived class of the class heavyvehicle.
(ii) Name the data members that can be accessed from function displaydata()
(iii)Name the data members that can be accessed by an object of bus class
(iv) Is the member function outputdata() accessible to the objects of heavyvehicle class.
47
Q2:- Consider the following declarations and answer the questions given below:
class book
{
char title[20];
char author[20];
int noof pages;
public:
void read();
void show();
};
class textbook: private textbook
{
int noofchapters, noofassignments;
protected:
int standard;
void readtextbook();
void showtextbook();
};
class physicsbook: public textbook
{
char topic[20];
public:
void readphysicsbook();
void showphysicsbook();
};
(i) Name the members, which can be accessed from the member functions of class
physicsbook.
(ii) Name the members, which can be accessed by an object of Class textbook.
(iii)Name the members, which can be accessed by an object of Class physicsbook.
(iv) What will be the size of an object (in bytes) of class physicsbook.

Q3 Answer the questions (i) to (iv) based on the following: (5)


class One
int A1;
protected:
float A2;
public:
One();
void Get1(); void Show1();
};
class Two : private One
{
int B1;
protected:
float B2;
public:
Two();
void Get2();
48
void Show();
};
class Three : public Two
{
int C1;
public:
Three();
void Get3();
void Show();
};
void main()
{
Three T; //Statement 1
__________________;//Statement 2
}

a) Which type of inheritance is shown?


b) Write the names of all the member functions, which are directly accessible by the
object T of class Three as declared in main() function..
c) Write Statement 2 to call function Show() of class Two from the object T of class
Three.
d) What will be the order of execution of the constructors, when the object T of class
Three is declared inside main()?.
e) How many bytes are occupied with the class Three.

2 marks Practice Problems:

1. What is access specifier ? What is its role ?


2. Which are the types of inheritance ?
3. What is the significance of inheritance ?
4. What is the difference between private and public visibility modes?

Topic : DATA FILE HANDLING IN C++

File:- A file is a stream of bytes stored on some secondary storage devices.


 Text file: A text file stores information in readable and printable form. Each line of text is
terminated with an EOL (End of Line) character.
 Binary file: A binary file contains information in the non-readable form i.e. in the same
format in which it is held in memory.
File Stream
 Stream: A stream is a general term used to name flow of data. Different streams are used to
represent different kinds of data flow.
There are three file I/O classes used for file read / write operations.
o ifstream - can be used for read operations.
o ofstream - can be used for write operations.
o fstream - can be used for both read & write operations.
 fstream.h:-This header file includes the definitions for the stream classes ifstream, ofstream
and fstream. In C++ file input output facilities implemented through fstream.h header file.

49
It contain predefines set of operation for handling file related input and output, fstream class
ties a file to the program for input and output operation.

A file can be opened using:


o By the constructor method. This will use default streams for file input or output. This
method is preferred when file is opened in input or output mode only.
Example : ofstream file (“student.dat”); or ifstream file(“student.dat”);

o By the open() member function of the stream. It will preferred when file is opened in
various modes i.e ios::in, ios::out, ios::app, ios::ate etc.
e.g fstream file;
file.open(“book.dat”, ios::in | ios::out | ios::binary);
File modes:
Open Mode Description

ios::out It open file in output mode (i.e write mode) and place the file pointer in beginning,
if file already exist it will overwrite the file.

ios::in It open file in input mode (read mode) and permit reading from the file.

ios::app It opens the file in write mode, and place file pointer at the end of file

ios::ate It open the file in write or read mode, and place file pointer at the end of file

ios::trunc It truncates the existing file (empties the file).

ios::nocreate If file does not exist this file mode ensures that no file is created and open() fails.

ios::noreplac If file does not exist, a new file gets created but if the file already exists, the open() fails.
e

ios::binary Opens a file in binary mode

eof( ): This function determines the end-of-file by returning true(non-zero) for end of file otherwise
returning false(zero).
close(): This function terminates the connection between the file and stream associated with it.
Stream_object.close();
e.g file.close();

Text File functions:


Char I/O :
 get() – read a single character from text file and store in a buffer. e.g file.get(ch);
 put() - writing a single character in textfile e.g. file.put(ch);

50
 getline() - read a line of text from text file store in a buffer. e.g file.getline(s,80);

 We can also use file>>ch for reading and file<<ch writing in text file.
Binary file functions:
 read()- read a block of binary data or reads a fixed number of bytes from the specified
stream and store in a buffer.
Syntax : Stream_object.read ( ( char * )& Object, sizeof (Object ) ) ;
e.g file.read ( ( char * )&s, sizeof( s ) ) ;
 write() – write a block of binary data or writes fixed number of bytes from a specific
memory location to the specified stream.
Syntax : Stream_object.write((char *)& Object, sizeof(Object));
e.g file.write((char *)&s, sizeof(s));
Note: Both functions take two arguments, Initial address and length of the variable

File Pointer: The file pointer indicates the position in the file at which the next input/output is to
occur. There read pointer and write pointer associated with a file.

Moving the file pointer in a file for various operations viz modification, deletion , searching
etc. Following functions are used:

 seekg(): It places the file pointer to the specified position in input mode of file.
e.g file.seekg(p,ios::beg); or file.seekg(-p,ios::end), or file.seekg(p,ios::cur)
i.e to move to p byte position from beginning, end or current position.

 seekp(): It places the file pointer to the specified position in output mode of file.
e.g file.seekp(p,ios::beg); or file.seekp(-p,ios::end), or file.seekp(p,ios::cur)
i.e to move to p byte position from beginning, end or current position.

 tellg(): This function returns the current working position of the file pointer in the input
mode.
e.g int p=file.tellg( );

 tellp(): This function returns the current working position of the file pointer in the output
mode.
e.f int p=file.tellp( );

Steps To Create A File


 Declare an object of the desired file stream class(ifstream, ofstream, or fstream)
 Open the required file to be processed using constructor or open function.
 Process the file.
 Close the file stream using the object of file stream.

General program structure used for creating a Text File


To create a text file using strings I/O
#include<fstream.h> //header file for file operations
void main()

51
{
char s[80], ch;
ofstream file(―myfile.txt‖); //open myfile.txt in default output mode
do
{ cout<<‖\n enter line of text‖;
gets(s); //standard input
file<<s; // write in a file myfile.txt
cout<<‖\n more input y/n‖;
cin>>ch;
}while( ch != ‘n‘ || ch != ‘N‘ ) ;
file.close();
} //end of main
To create a text file using characters I/O
#include<fstream.h> //header file for file operations
void main()
{
char ch;
ofstream file(―myfile.txt‖); //open myfile.txt in default output mode
do{
ch=getche();
if (ch==13) //check if character is enter key
cout<<‘\n‘;
else
file<<ch; // write a character in text file ‗myfile.txt ‗
} while(ch!=27); // check for escape key
file.close();
} //end of main
Text files in input mode:

To read content of „myfile.txt‟ and display it on monitor.


#include<fstream.h> //header file for file operations
void main()
{
char ch;
ifstream file(―myfile.txt‖); //open myfile.txt in default input mode
while(file)
{
file.get(ch) // read a character from text file ‗ myfile.txt‘
cout<<ch; // write a character in text file ‗myfile.txt ‗
}
file.close();
} //end of main

52
2 Marks Questions:

1. Write a function in a C++ to read the content of a text file “DELHI.TXT” and display
all those lines on screen, which are either starting with „D‟ or starting with „M‟. [CBSE
2012]
void DispDorM()
{
ifstream File(―DELHI.TXT‖)
char str[80];
while(File.getline(str,80))
{
if(str[0] = =‘D‘ || str[0] = =‘M‘)
cout<<str<<endl;
}
File.close(); //Ignore
}

2. Write a function in a C++ to count the number of lowercase alphabets present in a text
file “BOOK.txt”.
int countalpha()
{ ifstream Fin(―BOOK.txt‖);
char ch;
int count=0;
while(!Fin.eof())
{
Fin.get(ch);
if (islower(ch))
count++;
}
Fin.close();
return count;
}

3. Function to calculate the average word size of a text file.


void calculate()
{
fstream File;
File.open(―book.txt‖,ios::in);
char a[20];
char ch;
int i=0,sum=0,n=0;
while(File)
{ File.get(ch);
a[i]=ch;
i++;
if((ch==‘ ‗) || ch(== ‗.‘)||(char==‘,‘)(ch==‘\t‘)||(ch==‘\n‘)
{
53
i --;
sum=sum +i;
i=0; N++;
}
}
cout<<‖average word size is ―<<(sum/n);
}

4. Assume a text file “coordinate.txt” is already created. Using this file create a C++
function to count the number of words having first character capital.
int countword()
{ ifstream Fin(―BOOK.txt‖);
char ch[25];
int count=0;
while(!Fin.eof())
{
Fin>>ch;
if (isupper(ch[0]))
count++;
}
Fin.close();
return count;
}

5. Function to count number of lines from a text files (a line can have maximum 70
characters or ends at „.‟)
int countword()
{
ifstream Fin(―BOOK.txt‖);
char ch[70];
int count=0;
if (!Fin)
{
cout<<‖Error opening file!‖ ;
exit(0);
}
while(1)
{
Fin.getline(ch,70,„.‟);
if (Fin.eof())
break;
count++;
}
Fin.close();
return count;
}
2/3 Marks Practice Questions
54
1. Write a function in C++ to count the number of uppercase alphabets present in a text file
―BOOK.txt‖

2. Write a function in C++ to count the number of alphabets present in a text file ―BOOK.txt‖

3. Write a function in C++ to count the number of digits present in a text file ―BOOK.txt‖

4. Write a function in C++ to count the number of white spaces present in a text file
―BOOK.txt‖

5. Write a function in C++ to count the number of vowels present in a text file ―BOOK.txt‖

6. Assume a text file ―Test.txt‖ is already created. Using this file, write a function to create
three files ―LOWER.TXT‖ which contains all the lowercase vowels and ―UPPER.TXT‖
which contains all the uppercase vowels and ―DIGIT.TXT‖ which contains all digits.

7. Write a function in C++ to count the number of vowels present in a text file ―BOOK.txt‖

8. Write a function in C++ to count the number of words with ―the‖ or ―to‖ present in a text
file ―SOUND.txt‖

9. Write a function in C++ to count the number sentences starting with character with ‗P‘ in a
text file ―BOOK.txt‖

10. Write a function in C++ to count the number of words starting with character ‗M‘ present in
a text file ―BOOK.txt‖

Topic : DATA FILE HANDLNG

DATA FILE HANDLING IN C++


File:-A file is a stream of bytes stored on some secondary storage devices.
 Text file: A text file stores information in readable and printable form. Each line of text is
terminated with an EOL (End of Line) character.
 Binary file: A binary file contains information in the non-readable form i.e. in the same
format in which it is held in memory.
File Stream
 Stream: A stream is a general term used to name flow of data. Different streams are used to
represent different kinds of data flow.
There are three file I/O classes used for file read / write operations.
o ifstream - can be used for read operations.
o ofstream - can be used for write operations.
o fstream - can be used for both read & write operations.
 fstream.h:-This header file includes the definitions for the stream classesifstream, ofstream
and fstream. In C++ file input output facilities implemented through fstream.h header file.

55
It contain predefines set of operation for handling file related input and output, fstream class
ties a file to the program for input and output operation.

A file can be opened using:


o By the constructor method. This will use default streams for file input or output. This
method is preferred when file is opened in input or output mode only.
Example :ofstream file (“student.dat”); or ifstream file(“student.dat”);

o By the open() member function of the stream. It will preferred when file is opened in
various modes i.eios::in, ios::out, ios::app, ios::ate etc.
e.g fstream file;
file.open(“book.dat”, ios::in | ios::out | ios::binary);
File modes:
Open Mode Description

ios::out It open file in output mode (i.e write mode) and place the file pointer in beginning,
if file already exist it will overwrite the file.

ios::in It open file in input mode (read mode) and permit reading from the file.

ios::app It opens the file in write mode, and place file pointer at the end of file

ios::ate It open the file in write or read mode, and place file pointer at the end of file

ios::trunc It truncates the existing file (empties the file).

ios::nocreate If file does not exist this file mode ensures that no file is created and open() fails.

ios::noreplace If file does not exist, a new file gets created but if the file already exists, the open()
fails.

ios::binary Opens a file in binary mode

eof( ): This function determines the end-of-file by returning true(non-zero) for end of file otherwise
returning false(zero).
close(): This function terminates the connection between the file and stream associated with t.
Stream_object.close();
e.gfile.close();

Text File functions:


Char I/O :
 get() – read a single character from text file and store in a buffer. e.gfile.get(ch);
 put() - writing a single character in textfile e.g. file.put(ch);

56
 getline() - read a line of text from text file store in a buffer. e.gfile.getline(s,80);

 We can also use file>>chfor reading and file<<chwriting in text file.


Binary file functions:
 read()- read a block of binary data or reads a fixed number of bytes from the specified
stream and store in a buffer.
Syntax :Stream_object.read ( ( char * )& Object, sizeof (Object ) ) ;
e.gfile.read( ( char * )&s, sizeof( s ) ) ;
 write() – write a block of binary data or writes fixed number of bytes from a specific
memory location to the specified stream.
Syntax :Stream_object.write((char *)& Object, sizeof(Object));
e.gfile.write((char *)&s, sizeof(s));
Note: Both functions take two arguments, Initial address and length of the variable

File Pointer: The file pointer indicates the position in the file at which the next input/output is to
occur. There read pointer and write pointer associated with a file.

Moving the file pointer in a file for various operations viz modification, deletion , searching
etc. Following functions are used:

 seekg(): It places the file pointer to the specified position in input mode of file.
e.gfile.seekg(p,ios::beg); or file.seekg(-p,ios::end), or file.seekg(p,ios::cur)
i.e to move to p byte position from beginning, end or current position.

 seekp(): It places the file pointer to the specified position in output mode of file.
e.gfile.seekp(p,ios::beg); or file.seekp(-p,ios::end), or file.seekp(p,ios::cur)
i.e to move to p byte position from beginning, end or current position.

 tellg(): This function returns the current working position of the file pointer in the input
mode.
e.gint p=file.tellg( );

 tellp(): This function returns the current working position of the file pointer in the output
mode.
e.fint p=file.tellp( );

Steps To Create A File


 Declare an object of the desired file stream class(ifstream, ofstream, or fstream)
 Open the required file to be processed using constructor or open function.
 Process the file.
 Close the file stream using the object of file stream.

General program structure used for creating a Text File


To create a text file using strings I/O
#include<fstream.h>//header file for file operations
void main()

57
{
char s[80], ch;
ofstream file(―myfile.txt‖); //open myfile.txt in default output mode
do
{ cout<<‖\n enter line of text‖;
gets(s); //standard input
file<<s; // write in a file myfile.txt
cout<<‖\n more input y/n‖;
cin>>ch;
}while( ch != ‘n‘ || ch != ‘N‘ ) ;
file.close();
} //end of main
To create a text file using characters I/O
#include<fstream.h>//header file for file operations
void main()
{
char ch;
ofstream file(―myfile.txt‖); //open myfile.txt in default output mode
do{
ch=getche();
if (ch==13) //check if character is enter key
cout<<‘\n‘;
else
file<<ch; // write a character in text file ‗myfile.txt ‗
} while(ch!=27); // check for escape key
file.close();
} //end of main
Text files in input mode: To read content of „myfile.txt‟ and display it on monitor.
#include<fstream.h>//header file for file operations
void main()
{charch;
ifstream file(―myfile.txt‖); //open myfile.txt in default input mode
while(file)
{ file.get(ch) // read a character from text file ‗ myfile.txt‘
cout<<ch; // write a character in text file ‗myfile.txt ‗
}
file.close();
} //end of main

Solved Questions:
2 Marks Questions:

6. Write a function in a C++ to read the content of a text file “DELHI.TXT” and display
all those lines on screen, which are either starting with „D‟ or starting with „M‟. [CBSE
2012]
void DispDorM()
{
58
ifstream File(―DELHI.TXT‖)
charstr[80];
while(File.getline(str,80))
{
if(str[0] = =‘D‘ || str[0] = =‘M‘)
cout<<str<<endl;
}
File.close(); //Ignore
}

7. Write a function in a C++ to count the number of lowercase alphabets present in a text
file “BOOK.txt”.
int countalpha()
{ ifstream Fin(―BOOK.txt‖);
charch;
int count=0;
while(!Fin.eof())
{
Fin.get(ch);
if (islower(ch))
count++;
}
Fin.close();
return count;
}

8. Function to calculate the average word size of a text file.


void calculate()
{
fstream File;
File.open(―book.txt‖,ios::in);
char a[20];
charch;
int i=0,sum=0,n=0;
while(File)
{ File.get(ch);
a[i]=ch;
i++;
if((ch==‘ ‗) || ch(== ‗.‘)||(char==‘,‘)(ch==‘\t‘)||(ch==‘\n‘)
{
i --;
sum=sum +i;
i=0; N++;
}
}
cout<<‖average word size is ―<<(sum/n);
59
}

9. Assume a text file “coordinate.txt” is already created. Using this file create a C++
function to count the number of words having first character capital.
int countword()
{ ifstream Fin(―BOOK.txt‖);
char ch[25];
int count=0;
while(!Fin.eof())
{
Fin>>ch;
if (isupper(ch[0]))
count++;
}
Fin.close();
return count;
}

10. Function to count number of lines from a text files (a line can have maximum 70
characters or ends at „.‟)
int countword()
{
ifstream Fin(―BOOK.txt‖);
charch[70];
int count=0;
if (!Fin)
{
cout<<‖Error opening file!‖ ;
exit(0);
}
while(1)
{
Fin.getline(ch,70,„.‟);
if (Fin.eof())
break;
count++;
}
Fin.close();
return count;
}

General program structure used for operating a Binary File


1. Program to create a binary file „student.dat‟ using structure.
#include<fstream.h>
struct student
{
char name[15];
60
float percent;
};
void main()
{
ofstream fout; // f out is output file stream it will open file in write mode
char ch;
fout.open(―student.dat‖, ios::out | ios:: binary); // student.dat will be
opened in
// binary Mode
clrscr();
student s; //s is a variable of type student that contains name &percent
do
{ // inputting data to record s
cout<<‖\n enter name of student‖;
gets(s);
cout<<‖\n enter persentage‖;
cin>>percent;
//Writing contents of s to file student.dat
fout.write( ( char * ) &s, sizeof ( s ) ) ;
cout<<‖\n more record y/n‖;
cin>>ch;
}while(ch!=‘n‘ || ch!=‘N‘) ;
fout.close();
}

2. Program to read a binary file „student.dat‟ display records on monitor.


#include<fstream.h>
struct student
{
char name[15];
float percent;
};
void main()
{
ifstream fin; //fin is an input file stream that can open a file in read mode
student s; // s is a record of type student
fin.open(―student.dat‖,ios::in | ios:: binary); // opening student.dat in binary
mode
fin.read((char *) &s, sizeof(student)); //read a record from file „student.dat‟
invariable s
while(file) // file will read until end of file does not come.
{
//Displaying the content of s (reord) read from the student.dat
cout<<s.name;
cout<<―\n has the percent: ‖<<s.percent;
fin.read((char *) &s, sizeof(student)); // reading the next record
}
61
fin.close();
}

Binary file using Objects and other file operations:


1. Consider the following class declaration then write c++ function for following file
operations vizcreate_file, read_file, add new records, modify record, delete a record,
search for a record.
#include<iostream.h>
class student
{
intrno;
char name[30];
int age;
public:
void input( ) // function to input values for data member of current
object
{
cout<<‖\n enter roll no‖;
cin>>rno;
cout<<‖\n enter name ―;
gets(name);
cout<<‖\n enter age‖;
cin>>age;
}
void output( ) // function to display contents of current object
{
cout<< ―\n roll no:‖<<rno;
cout<< ―\n name :‖<<name;
cout<< ―\n age:‖<<age;
}
int getrno( ) // function to get the rno from current object
{
returnrno;
}
};

void create_file( ) // function to create a blank file student.dat


{
ofstream fout; // fout is output file stream object that will open a file in write
mode
fout.open(―student‖, ios::out | ios:: binary); // opening file in binary mode
fout.close(); // closing file student.dat
}

void read_file( ) //function to read records from student.dat one by into


record s
{
62
ifstream fin;
student s;
fin.open(―student.dat‖,ios::in | ios:: binary); //opening the file
fin.read((char *) &s,sizeof(student)); //reading first record from file to
record s
while(file)
{
s.output(); // displaying the content of object s (record)
cout<< ―\n‖;
fin.read( ( char * ) &s,sizeof ( student ) ) ; // reading next record
}
fin.close();
}

void modify_record()
{
student s;
fstream file;
file.open(―student.dat‖,ios::in|ios::out|ios::ate|ios::binary); / opening student.dat in read & write
binary mode
int r, pos = -1, f=0;
cout<<‖\n enter the roll no of student whom data to be modified‖;
cin>>r ;
//Searching the record with rno = r
file.read( ( char * )&s, sizeof( s ) ) ;
while(file)
{
if (r == s.getrno( )) // will be true if required record found (rno =
r)
{
f=1; // f = 1 indicate record found
cout<<‖\n record is ―;
s.output();
pos =file.tellg()-size(s); //moving the write pointer one
record back
break;
}
file.read((char *)&s,sizeof(s)); // writing the modified record to
the file
}
if(f == 0 ) // f==0 indicate record did not found
cout<< ―\n record not exist‖;
}

void delete_record()
{
fstream file(―student.dat‖, ios::in|ios::binary);
63
fstream newfile(―newstu.dat‖,ios::out|ios::binary);
student s;
cout<<‖\n enter the rollno no of student whom record to be deleted‖;
cin>>r;
file.read( (char *)&s, sizeof( s ) ) ;
while(file)
{
if (r!=s.getrno())
{
newfile.write((char *)&s,sizeof(s));
}
file.read((char *)&s,sizeof(s));
}
file.close();
newfile.close();
}

void search_record()
{ student s;
fstream file;
file.open(―student.dat‖,ios::in|os::binary);
int r,flag = 0;
cout<<‖\n enter the rollo no of student whom record to be searched‖;
cin>>r;
file.read( ( char * )&s, sizeof( s ) ) ;
while(file)
{
if (r==s.getrno())
{ cout<<‖\n record is ―;
s.output();
flag=1;
break;
}
file.read((char *)&s,sizeof(s));
}
if(flag==0)
cout<< ―\n search unsuccessfull‖;
file.close();
}

1. Observe the program segment carefully and answer the question that follows:
class stock
{
int Ino, Qty; Char Item[20];
public:
void Enter() { cin>>Ino; gets(Item); cin>>Qty;}
void issue(int Q) { Qty+=0;}
64
void Purchase(int Q) {Qty-=Q;}
int GetIno() { return Ino;}
};
void PurchaseItem(intPino, intPQty)
{ fstream File;
File.open(―stock.dat‖, ios::binary|ios::in|ios::out);
Stock s;
int success=0;
while(success= = 0 &&File.read((char *)&s,sizeof(s)))
{
If(Pino= = ss.GetIno())
{
s.Purchase(PQty);
_______________________ // statement 1
_______________________ // statement 2
Success++;
}
}
if (success = =1)
cout<< ―Purchase Updated‖<<endl;
else
cout<< ―Wrong Item No‖<<endl;
File.close() ;
}
Ans.1.
i) Statement 1 to position the file pointer to the appropriate place so that the data updation is done
for the required item.
File.seekp(File.tellg( ) - sizeof(stock);
OR
File.seekp(-sizeof(stock),ios::cur);
ii) Staement 2 to perform write operation so that the updation is done in the binary file.
File.write((char *)&s, sizeof(s));
OR
File.write((char *)&s, sizeof(stock));

3 Marks Question
1. Write a function in c++ to search for details (Phoneno and Calls) of those Phones
which have more than 800 calls from binary file “phones.dat”. Assuming that this
binary file contains records/ objects of class Phone, which is defined below.
class Phone CBSE 2012
{
char Phoneno[10]; int Calls;
public:
void Get() {gets(Phoneno); cin>>Calls;}
void Billing() { cout<<Phoneno<< ―#‖<<Calls<<endl;}
int GetCalls() {return Calls;}
65
};

Ans1 :
void Search()
{
Phone P;
fstream fin;
fin.open( ―Phone.dat‖, ios::binary| ios::in);
while(fin.read((char *)&P, sizeof(P)))
{
if(p.GetCalls() >800)
p.Billing();
}
Fin.close(); //ignore
}};
2. Write a function in C++ to add new objects at the bottom of a binary file
“STUDENT.DAT”, assuming the binary file is containing the objects of the following
class.
class STUD
{intRno;
char Name[20];
public:
void Enter()
{cin>>Rno;gets(Name);}
void Display(){cout<<Rno<<Name<<endl;}
};
Ans.2.
void searchbook(intbookno)
{ifstreamifile(―BOOK.DAT‖,ios::in|ios::binary);
if(!{BOOK b; int found=0;
while(ifile.read((char *)&b, sizeof(b)))
{if(b.RBno()==bookno)
{b.Display(); found=1; break;}
}
if(! found)
cout<<‖record is not found ―;
ifile.close();
}
}

Unsolved Questions:
2/3 Marks Practice Questions

11. Write a function in C++ to count the number of uppercase alphabets present in a text file
―BOOK.txt‖
12. Write a function in C++ to count the number of alphabets present in a text file ―BOOK.txt‖
13. Write a function in C++ to count the number of digits present in a text file ―BOOK.txt‖
66
14. Write a function in C++ to count the number of white spaces present in a text file
―BOOK.txt‖
15. Write a function in C++ to count the number of vowels present in a text file ―BOOK.txt‖
16. Assume a text file ―Test.txt‖ is already created. Using this file, write a function to create
three files ―LOWER.TXT‖ which contains all the lowercase vowels and ―UPPER.TXT‖
which contains all the uppercase vowels and ―DIGIT.TXT‖ which contains all digits.

17. Given a binary file PHONE.DAT, containing records of the following class type
class Phonlist
{
char name[20];
char address[30];
char areacode[5];
char Phoneno[15];
public:
void Register()
void Show();
void CheckCode(char AC[])
{return(strcmp(areacode,AC);
}};
Write a function TRANSFER( ) in C++, that would copy all those records which are having
areacode as ―DEL‖ from PHONE.DAT to PHONBACK.DAT. (3)

18. Find the output of the following C++ code considering that the binary file BOOK.DAT
exists on the hard disk with a data of 200 books. (3)

class BOOK
{
int BID;char BName[20];
public:
void Enter();void Display();
};

void main()
{
fstream InFile;
InFile.open("BOOK.DAT",ios::binary|ios::in);
BOOK B;
InFile.seekg(5*sizeof(B));
InFile.read((char*)&B, sizeof(B));
cout<<"Book Number:"<<InFile.tellg()/sizeof(B) + 1;
InFile.seekg(0,ios::end);
cout<<" of "<<InFile.tellg()/sizeof(B)<<endl;
InFile.close();
}

9) Write a function replace() in C++ to read the contents from a text file and replace all spaces with
character ‗%‘ in the file story.txt (3)

10) Write a function in C++ to search and display details, whose destination is ―Chandigarh‖ from
67
binary file ―Flight.Dat‖. Assuming the binary file is containing the objects of the following class:
(3)
class FLIGHT
{ int Fno; // Flight Number
char From[20]; // Flight Starting Point
char To[20]; // Flight Destination
public:
char * GetFrom ( ); { return from; }
char * GetTo( ); { return To; }
void input() { cin>>Fno>>; gets(From); get(To); }
void show( ) { cout<<Fno<< ―:‖<<From << ―:‖ <<To<<endl; }
};

11) Write a function in C++ to count and display the no of words starting with a character ‗a‘ or
‗p‘ in the file ―STORY.TXT‖. (3)

12) Write a definition for function COUNTDEPT( ) in C++ to read each object of a binary file
TEACHERS.DAT, find and display the total number of teachers in the department MATHS.
Assume that the file TEACHERS.DAT is created with the help of objects of class TEACHERS,
which is defined below: (3)

class TEACHERS
{
int TID; char DEPT[20];
public:
void GET()
{
cin>>TID; gets(DEPT);
}
void SHOW()
{
cout<<TID<<":"<<DEPT<<endl;
}
char *RDEPT() {return DEPT;}
};

Topic :POINTERS

Pointer is a variable that holds a memory address of another variable of same type.
It supports dynamic allocation routines.

C++MemoryMap :
 Program Code : It holds the compiled code of the program.
 Global Variables : They remain in the memory as long as program continues.
 Stack : It is used for holding return addresses at function calls, arguments passed to the
functions, local variables for functions. It also stores the current state of the CPU.
 Heap : It is a region of free memory from which chunks of memory are allocated via DMA
functions.
StaticMemoryAllocation :Allocation of memory at compile time.
e.g. int a; // This will allocate 2 bytes for a during compilation.

68
Dynamic Memory Allocation :allocation of memory at run time using operator new and delete.
e.g int x =new int; // dynamic allocation
float y= new float;
delete x; //dynamic deallocation
delete y;

Free Store :It is a pool of unallocated heap memory given to a program that is used by the program
for dynamic memory allocation during execution.

Declaration and Initialization of Pointers:


Syntax :Datatype *variable_name;
int *p; // p is an integer pointer contains address of an integer variable
float *p1; // p1 is a float pointer contains address of a floating point variable
char *c; // c is a character pointer contains address of a character variable

int a = 10; // a is an integer variable hold value 10


int *p = &a; //pointer initialization [ p is a integer pointer holds address of a]
// &a means address of a

Pointer arithmetic:
Two arithmetic operations, addition and subtraction, may be performed on pointers.
Adding 1 to a pointer actually adds the size of pointer‘s base type.
Base address: The address of the first byte is known as BASE ADDRESS.

Dynamic Allocation Operators:


int * p = new int[10]; this will dynamically allocate 20 bytes (10*2) to integer pointer p

Two dimensional arrays:


int *arr, r, c;
r = 5; c = 5;
arr = new int [r * c];

Now to read the element of array, you can use the following loops :
For (int i = 0; i < r; i++)
{
cout<< ―\n Enter element in row ― << i + 1 << ― : ―;
for (int j=0; j < c; j++)
cin>>arr [ i * c + j];
}

Memory released with delete as below: delete arr;

Pointers and Arrays:


Array of Pointers:
To declare an array holding 5 int pointers –
69
int * ip[5];
That would be allocated for 5 pointers that can point to integers.
ip[0] = &a; ip[1] = &b; ip[2] = &c; ip[3] = &d; ip[4] = &e;

I Address of a Address of b Address of c Address of d Address of e


p

Pointers and Strings:


Pointer is very useful to handle the character array also. E.g :
void main()
{
char str[ ] = ―computer‖;
char *cp;
cp = str; // cp will hold address of first element of array str
cout<<str ; //display string
cout<<cp; // display string
for (cp =str; *cp != ‗\0‘; cp++) // display character by character by character
cout<< ‖--―<<*cp;
}
Output :
Computer
Computer
--c--o--m--p--u--t--e—r

Pointers and CONST :


A constant pointer means that the pointer in consideration will always point to the same address.
Its address cannot be modified.

int n = 20;
int *const c = &n; // a constant pointer c to an integer n

A pointer to a constant refers to a pointer which is pointing to a symbolic constant.


const int b = 10; // a constant integer b
const int *pc = &b; // a pointer to a constant integer b

Pointers and Functions :


Invoking Function by Passing the Pointers:
When the pointers are passed to the function, the addresses of actual arguments in the calling
function
are copied into formal arguments of the called function.
#include<iostream.h>
void swap(int *m, int *n)
{
int temp;

70
temp = *m;
*m = *n;
*n = temp;
}

void main()
{
void swap(int *m, int *n);
int a = 5, b = 6;
cout<< ―\n Value of a :‖ << a << ― and b :‖ << b;
swap(&a, &b);
cout<< ―\n After swapping value of a :‖ << a << ―and b :‖ << b;
}

Input :
Value of a : 5 and b : 6
After swapping value of a : 6 and b : 5

Function returning Pointers :


A function can also returns a pointer.
Syntax:- type * function-name (argument list);

#include <iostream.h>
int *min(int&x, int&y) // function returning int pointer
{
if (x < y )
return (&x);
else
return (&y)
}
void main()
{
int a, b, *c;
cout<< ―\nEnter a :‖; cin>> a;
cout<< ―\nEnter b :‖; cint>> b;
c = min(a, b); // pointer returned from the function min will be assigned to pointer
variable c
cout<< ―\n The minimum no is :‖ << *c;
}
Dynamic structures:
 Dynamic allocation:-
The new operator can be used to create dynamic structures also.
struct student
{
int rno;
char name[20];
};
71
student *s = new student;
To access structure member through structure pointer we use arrow operator(->).
cout<< s ->rno;
cout<< s -> name
 Dynamic deallocation:-
A dynamic structure can be released using the deallocation operator delete as shown below
:
deletes tu;

this Pointer : refers to the address of current object.

Solved Questions
Q1. How is *p different from **p ?
Ans : *p means, it is a pointer pointing to a memory location storing a value in it. But **p means, it
is a pointer pointing to another pointer which in turn points to a memory location storing a value in
it.

Q2. How is &p different from *p ?


Ans :&p gives us the address of variable p and *p. dereferences p and gives us the value stored in
memory location pointed to by p.

Q3. Find the error in following code segment :


Float **p1, p2;
P2 = &p1;
Ans : In code segment, p1 is pointer to pointer, it means it can store the address of another pointer
variable, whereas p2 is a simple pointer that can store the address of a normal variable. So here the
statement p2 = &p1 has error.

Q. 4 What will be the output of the following code segment ?


char C1 = ‗A‘;
char C2 = ‗D‘;
char *i, *j;
i = &C1;
j = &C2;
*i = j;
cout<< C1;
Ans : It will print A.
Q. 5 How does C++ organize memory when a program is run ?
Ans : Once a program is compiled, C++ creates four logically distinct regions of memory :
 area to hold the compiled program code
 area to hold global variables
 the stack area to hold the return addresses of function calls, arguments passed to the
functions, local variables for functions, and the current state of the CPU.
 The heap area from which the memory is dynamically allocated to the program.

Q. 6 Identify and explain the error(s) in the following code segment :


float a[] = { 11.02, 12.13, 19.11, 17.41};
72
float *j, *k;
j = a;
k = a + 4;
j = j * 2;
k = k / 2;
cout<< ― *j = ― << *j << ―, *k = ― << *k << ―\n‖;
Ans : The erroneous statements in the code are :
j = j * 2;
k = k / 2;
Because multiplication and division operations cannot be performed on pointer and j and k are
pointers.

Q7. How does the functioning of a function differ when


(i) an object is passed by value ?
(ii) an object is passed by reference ?

Ans :
(i) When an object is passed by value, the called function creates its own copy of theobject by
just copying the contents of the passed object. It invokes the object‘s copy constructor to
create its copy of the object. However, the called function destroys its copy of the object by
calling the destructor function of the object upon its termination.
(ii) When an object is passed by reference, the called function does not create its own copy of
the passed object. Rather it refers to the original object using its reference or alias name.
Therefore, neither constructor nor destructor function of the object is invoked in such a case.

2 MARKS PRACTICE QUESTIONS


1. Differentiate between static and dynamic allocation of memory.
2. Identify and explain the error in the following program :
#include<iostream.h>
int main()
{int x[] = { 1, 2, 3, 4, 5 };
for (int i = 0; i < 5; i++)
{
cout<< *x;
x++;
}r
return 0;
}
3. Give the output of the following :
char *s = ―computer‖;
for (int x = strlen(s) – 1; x >= 0; x--)
{
for(int y =0; y <= x; y++) cout<< s[y];
cout<<endl;
}
4. Identify the syntax error(s), if any, in the following program. Also give reason for errors.
void main()
73
{const int i = 20;
int *ptr;
ptr = &i;
*ptr++;
int j= 15;
ptr= &j; }

5. What is ‗this‘ pointer? What is its significance?


6. What will be the output of following program ?
#include<iostream.h>
void main()
{
char name1[] = ―ankur‖; char name2[] = ―ankur‖;
if (name1 != name2)
cout<< ―\n both the strings are not equal‖;
else
cout<< ―\n the strings are equal‖; }

7. Give and explain the output of the following code :


void junk (int, int *);
int main() {
int i = 6, j = -4;
junk (i, &j);
cout<< ―i = ― << i << ―, j = ― << j << ―\n‖;
return 0; }
void junk(int a, int *b)
{
a = a* a;
*b = *b * *b; }

Topic :DATA STRUCTURES- 1 (Arrays)

A data structure is a particular way of storing and organizing data in a computer so that it can be
used efficiently. The data structure can be classified into following two types:
 Simple Data Structure: These data structures are normally built from primitive data types
like integers,
floats, characters. For example arrays and structure.
 Compound Data Structure: simple data structures can be combined in various ways to
form more complex structure called compound structures. Linked Lists, Stack, Queues and
Trees are examples of compound data structure.

Data Structure Arrays


Data structure array is defined as linear sequence of finite number of objects of same type with
following set of operation:
 Creating : defining an array of required size
 Insertion: addition of a new data element in the in the array
 Deletion: removal of a data element from the array
74
 Searching: searching for the specified data from the array
 Traversing: processing all the data elements of the array
 Sorting : arranging data elements of the array in increasing or decreasing order
 Merging : combining elements of two similar types of arrays to form a new array of same
type
In C++ an array can be defined as
Datatype arrayname[ size ] ;
Where size defines the maximum number of elements can be hold in the array.
For example
float b[10]; //b is an array which can store maximum 10 float values
int c[5]; //c is an array which can store maximum 5 integer values

Array initialization
void main()
{
int b[10]={3,5,7,8,9}; // array initialization
cout<<b[4]<<endl;
cout<<b[5]<<endl;
}
Output is
9
0

Searching
We can use two different search algorithms for searching a specific data from an array
 Linear search algorithm
 Binary search algorithm
Linear search algorithm
In Linear search, each element of the array is compared with the given item to be searched
for. This method continues until the searched item is found or the last item is compared.
#include<iostream.h>
int linear_search(int a[], int size, int item)
{
int i=0;
while( i<size && a[i] !=item)
i++;
if(i<size)
return ( i); //returns the index number of the item in the array
else
return (-1); //given item is not present in the array so it returns -1
//since -1 is not a legal index number
}
void main()
{
int b[8]={2,4,5,7,8,9,12,15},size=8;
int item;
cout<<‖enter a number to be searched for‖;
75
cin>>item;
int p = linear_search(b, size, item); //search item in the array b
if(p == -1)
cout<<item<<‖ is not present in the array‖<<endl;
else
cout<<item <<‖ is present in the array at index no ―<<p;
}
Binary search algorithm
Binary search algorithm is applicable for already sorted array only. In this algorithm, to
search for the given item from the sorted array (in ascending order),
 The item is compared with the middle element of the array. If the middle element is
equal to the item then index of the middle element is returned
 If item is less than the middle item then the item will be searched in first half
segment of the array for the next iteration.
 If the item is larger than the middle element then the item will be searched in second
half of the array for the next iteration
 The same process continues until either the item is found or the segment is reduced
to the single element and still the item is not found (search unsuccessful).
#include<iostream.h>
int binary_search(int a[ ], int size, int item)
{
int first = 0, last = size-1, middle;
while(first<=last)
{
middle = ( first + last ) / 2;
if( item = = a[middle])
return middle; // item is found
else if(item< a[middle])
last=middle-1; //item is present in left side of the middle
element
else
first=middle+1; // item is present in right side of the middle
element
}
return -1; //given item is not present in the array, here, -1 indicates
unsuccessful search
}
void main()
{
int b[8]={2,4,5,7,8,9,12,15},size=8;
int item;
cout<<‖enter a number to be searched for‖;
cin>>item;
int p=binary_search(b, size, item); //search item in the array b
if(p = = -1)
cout<<item<<‖ is not present in the array‖<<endl;

76
else
cout<<item <<‖ is present in the array at index no ―<<p;
}

Steps to find item 12 in the array b


First Last middle B[middle] = item comment

Item 12 will be
search in array b
{2,4,5,7,9,12,15}
0 7 7/2 = 3 b[3] = 7 Item not found ,
item 12 is greater
than 7
Item 12 will be
search in second
segment array b
{9,12,15}
4 7 11/2 = 5 b[5] = 9 Item not found, 12
is greater than 9

Now Item will be


searched 2nd half of
previous segment
b{12,15}
6 7 13/2 = 6 B[6]=12 Item found &
function will return
6 (position of item
in array b
*if first > last, the
function will return
-1 (item not found)

Output : 12 is present in the array at index no 6

Inserting a new element in an array:-


We can insert a new element in an array in two ways
 If the array is unordered, the new element is inserted at the end of the array
 If the array is sorted then the new element is added at appropriate position without altering
the order. To achieve this, all elements greater than the new element are shifted. For
example, to add 10 in the given array below:

77
Following program implement insertion operation for sorted array
#include<iostream.h>
void insert(int a[ ], int &n, int item) //n is the number of elements already present in
the array
{
int i=n-1;
while (i>=0 && a[i]>item)
{
a[i+1]=a[i]; // shift the ith element one position towards right
i--;
}
a[i+1]=item; //insertion of item at appropriate place
n++; //after insertion, number of elements present in the array is increased by
1
}
void main()
{
int a[10]={2,4,5,7,8,11,12,15},n=8;
int i=0;

cout<<―Original array is:\n‖; // displaying original array


for(i=0;i<n;i++)
cout<<a[i]<<‖, ―;

insert(a,n,10); // inserting new element

cout<<‖\nArray after inserting 10 is:\n‖; // displaying array after


insertion
for(i=0; i<n; i++)
cout<<a[i]<<‖, ―;
}
Output is
Original array is:
2, 4, 5, 7, 8, 11, 12, 15
Array after inserting 10 is:
2, 4, 5, 7, 8, 10, 11, 12, 15

Deletion of an item from a sorted array


In this algorithm the item to be deleted from the sorted array is searched and if the item is
found in the array then the element is removed and the rest of the elements are shifted one position
toward left in the array to keep the ordered array undisturbed. Deletion operation reduces the
number of elements present in the array by1. For example, to remove 11 from the given array
below:

78
Following program implement deletion operation for sorted array
#include<iostream.h>
void delete_item(int a[ ], int &n, int item) //n is the number of elements already present in
the array
{
int i=0;
while(i<n && a[i]<item)
i++;
if (a[i]==item) // given item is found
{
while (i<n)
{
a[i]=a[i+1]; // shift the (i+1 )thelement one position towards left
i++;
}
cout<<‖\n Given item is successfully deleted‖;
}
else
cout<<‖\n Given item is not found in the array‖;
n--;
}

void main()
{
int a[10]={2,4,5,7,8,11,12,15},n=8;
int i=0;

cout<<―Original array is :\n‖; // displaying original arrary


for(i=0;i<n;i++)
cout<<a[i]<<‖, ―;

delete_item(a,n,11); //deleting an item from array

cout<<‖\nArray after deleting 11 is:\n‖; // displaying array after deletion


for(i=0; i<n; i++)
cout<<a[i]<<‖, ―;
79
}
Output is Original array is:
2, 4, 5, 7, 8, 11, 12, 15
Given item is successfully deleted
Array after deleting 11 is:
2, 4, 5, 7, 8, 12, 15

Traversal
Processing of all elements (i.e. from first element to the last element) present in one-
dimensional array is called traversal. For example, printing all elements of an array, finding sum of
all elements present in an array.
#include<iostream.h>
void print_array(int a[ ], int n) //n is the number of elements present in the array
{int i;
cout<<‖\n Given array is :\n‖;
for(i=0; i<n; i++)
cout<<a[i]<<‖, ―;
}
int sum(int a[ ], int n)
{inti,s=0;
for(i=0; i<n; i++)
s=s+a[i];
return s;
}

void main()
{ int b[10]={3,5,6,2,8,4,1,12,25,13},n=10;
int i, s;
print_array(b,n);
s = sum(b,n);
cout<<‖\n Sum of all elements of the given array is : ‖<<s; }
Output is Given array is
3, 5, 6, 2, 8, 4, 1, 12, 25, 13
Sum of all elements of the given array is : 79
Solved Questions

1. Write C++ function to Arrange(int [],int) to arrange all the negative and positive
numbers from left to right. 3
Example : - If an array of 10 elements initially contains { 4,5,6,-7,8,-2,-10,1,13,-20}
. Then the function rearrange them in following manner { -20,-10,-7,-2 1,4,5,6,8,13}

Ans:

void arrange(int a[10],int n)


{
int i,j,temp;
for(i=0;i<n;i++)
{ for(j=0;j<n-1;j++)

80
if(a[j]>a[j+1])
{ temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
for(i=0;i<n;i++)
cout<<a[i]<<" ";
}

2. Write a user defined function in C++ to find and display the row sums of a two
dimensional array. 3

Ans:

void rowsum(int a[10][10],int m,int n)


{
int i,j,rsum;
for(i=0;i<m;i++)
{ rsum=0;
for(j=0;j<n;j++)
rsum+=a[i][j];
cout<<"\nSum of row "<<i+1<<" is -"<<rsum;
}
}

3. Write a user defined function in C++ to find and display the column sums of a two
dimensional array. 3

Ans:

void columnsum(int a[10][10],int m,int n)


{
int i,j,csum;
for(i=0;i<n;i++)
{ csum=0;
for(j=0;j<m;j++)
csum+=a[j][i];
cout<<"\nSum of column "<<i+1<<" is ->"<<csum;
}
}

4. Write a function in C++ to print the product of each row of a two dimensional array
passed as the arguments of the function 3

Ans:

void rowproduct(int a[10][10],int m,int n)


{
int i,j,rp;
for(i=0;i<m;i++)
{ rp=1;
for(j=0;j<n;j++)
rp*=a[j][i];
81
cout<<"\nProduct of row "<<i+1<<" is ->"<<rp;
}
}

5. Write a user defined function in C++ which accepts a squared integer matrix with odd
dimensions (3*3, 5*5..) & display the sum of the middle row & middle column
elements. For ex. : 3

257
372
569

The output should be :


Sum of middle row = 12
Sum of middle column = 18

Ans:

void middlesum(int a[10][10],int m,int n)


{
int i,j,mrsum=0,mcsum=0;
for(i=0;i<n;i++)
mrsum+=a[m/2][i];
cout<<"\nSum of middle row="<<mrsum; for(i=0;i<m;i++)
mcsum+=a[i][n/2];
cout<<"\nSum of middle column="<<mcsum;
}

6. Write a user-defined function named Lower_half() which takes 2D array A, with size N
rows and N columns as argument and prints the lower half of the array. 3
Eg. Input

23150
71531
25781
01501
34915

the output will be

2
71
257
0150
34915

Ans:

void lower_half(int a[10][10],int n)


{
int i,j;

82
for(i=0;i<n;i++)
{ cout<<endl;
for(j=0;j<n;j++)
if(i>=j)
cout<<a[i][j]<<" ";
}
}

Unsolved Question (2/3 Marks)

1. Write a function in C++ which accepts an integer array and its size as arguments and
replaces elements having even values with its half and elements having odd values with
twice its value

2. Write a function in C++ which accepts an integer array and its size as argument and
exchanges the value of first half side elements with the second half side elements of the
array.
Example: If an array of eight elements has initial content as 2,4,1,6,7,9,23,10. The function
should rearrange the array as 7,9,23,10,2,4,1,6.

3. Write a function in C++ to find and display the sum of each row and each column of 2
dimensional array. Use the array and its size as parameters with int as the data type of the
array.

4. Write a function in C++, which accepts an integer array and its size as parameters and
rearrange the array in reverse. Example if an array of five members initially contains the
elements as 6,7,8,13,9,19 Then the function should rearrange the array as 19,9,13,8,7,6

83

Das könnte Ihnen auch gefallen