0% found this document useful (0 votes)
10 views

Computer Science (1) HANDOUT CL 12

Uploaded by

Sneha Malik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Computer Science (1) HANDOUT CL 12

Uploaded by

Sneha Malik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 110

TOPIC : REVIEW OF C++ COVERED IN CLASS XI

GETTING STARTED
A computer cannot understand our language that we use in our day to day conversations, and likewise,
we cannot understand the binary language that the computer uses to do its tasks. It is therefore
necessary for us to write instructions in some specially defined language like C++ which is like natural
language and after converting with the help of compiler the computer can understand it.

C++ COMPILER
A C++ compiler is itself a computer program which’s only job is to convert the C++ program from our
form to a form the computer can read and execute. The original C++ program is called the “source
code”, and the resulting compiled code produced by the compiler is usually called an “object file”.

Before compilation the preprocessor performs preliminary operations on C++ source files.
Preprocessed form of the source code is sent to compiler.

After compilation stage, object files are combined with predefined libraries by a linker, sometimes
called a binder, to produce the final complete file that can be executed by the computer. A library is a
collection of pre-compiled “object code” that provides operations that are done repeatedly by many
computer programs.

XII/Computer Science 1
INTRODUCTION TO C++
C++ is the successor of C language & developed by Bjarne Stroustrup at Bell Laboratories, New
Jersey in 1979.

TOKENS
A token is a group of characters that logically belong together. The programmer can write a program
by using tokens. C++ uses the following types of tokens.
Keywords, Identifiers, Literals, Punctuators, Operators.

1. Keywords
These are some reserved words in C++ which have predefined meaning to compiler called keywords.
Some commonly used Keyword are given below:

Asm auto break case catch


Char class const continue default
Delete do double else enum
Extern inline int float for
Friend goto if long new
Operator private protected public register
Return short signed sizeof static
Struct switch template this Try
Typedef union unsigned virtual void
Volatile while

2. Identifiers
Symbolic names can be used in C++ for various data items used by a programmer in his program. A
symbolic name is generally known as an identifier. The identifier is a sequence of characters taken
from C++ character set. The rules for the formation of an identifier are:
 An identifier can consist of alphabets, digits and/or underscores.
 It must not start with a digit
 C++ is case sensitive that is upper case and lower case letters are considered different
from each other.
 It should not be a reserved word.

3. Literals
Literals (often referred to as constants) are data items that never change their value during the
execution of the program. The following types of literals are available in C++.
 Integer-Constants
 Character-constants
 Floating-constants
 Strings-constants
Integer Constants
Integer constants are whole number without any fractional part. C++ allows three types of integer
constants.
Decimal integer constants : It consists of sequence of digits and should not begin with 0 (zero). For
example 124, - 179, +108.
Octal integer constants: It consists of sequence of digits starting with 0 (zero). For example. 014,
012.
Hexadecimal integer constant: It consists of sequence of digits preceded by ox or OX.
Character constants : A character constant in C++ must contain one or more characters and must
be enclosed in single quotation marks. For example 'A', '9', etc. C++ allows nongraphic characters
which cannot be typed directly from keyboard, e.g., backspace, tab, carriage return etc. These
characters can be represented by using an escape sequence. An escape sequence represents a single
character. The following table gives a listing of common escape sequences.
Escape Sequence Nongraphic Character
\a Bell (beep)
\n Newline
\r Carriage Return
\t Horizontal tab
\0 Null Character

XII/Computer Science 2
Floating constants
They are also called real constants. They are numbers having fractional parts. They may be written in
fractional form or exponent form. A real constant in fractional form consists of signed or unsigned
digits including a decimal point between digits. For example 3.0, -17.0, -0.627 etc.
String Literals
A sequence of character enclosed within double quotes is called a string literal. String literal is by
default (automatically) added with a special character ‘\0' which denotes the end of the string.
Therefore the size of the string is increased by one character. For example "COMPUTER" will re
represented as "COMPUTER\0" in the memory and its size is 9 characters.
4. Punctuators
The following characters are used as punctuators in C++.
Opening and closing brackets indicate single and
Brackets [ ]
multidimensional array subscript.
Parentheses ( Opening and closing brackets indicate functions calls,; function
) parameters for grouping expressions etc.
Opening and closing braces indicate the start and end of a
Braces { }
compound statement.
Comma , It is used as a separator in a function argument list.

Semicolon ; It is used as a statement terminator.

Colon : It indicates a labeled statement or conditional operator symbol.

Asterisk * It is used in pointer declaration or as multiplication operator.

Equal sign = It is used as an assignment operator.

Pound sign # It is used as pre-processor directive.


5. Operators
Operators are special symbols used for specific purposes. C++ provides six types of operators.
Arithmetical operators, Relational operators, Logical operators, Unary operators, Assignment
operators, Conditional operators, Comma operator

BASIC DATA TYPES


C++ supports a large number of data types. The built in or basic data types supported by C++ are
integer, floating point and character. These are summarized in table along with description and
memory requirement
Byt
Type Range Description
e
int 2 -32768 to +32767 Small whole number
-2147483648 to
long int 4 Large whole number
+2147483647
float 4 3.4x10-38 to 3.4x10+38 Small real number
1.7x10-308 to
double 8 Large real number
1.7x10+308
long 3.4x10-4932 to
10 Very Large real number
double 3.4x10+4932
char 1 0 to 255 A Single Character

VARIABLES
It is a location in the computer memory which can store data and is given a symbolic name for easy
reference. The variables can be used to hold different values at different times during the execution of
a program.
To understand more clearly we should study the following statements:
Total = 20.00;In this statement a value 20.00 has been stored in a memory location Total.
Declaration of a variable
Before a variable is used in a program, we must declare it. This activity enables the compiler to make
available the appropriate type of location in the memory.
float Total;
You can declare more than one variable of same type in a single single statement: int x,y;

XII/Computer Science 3
Initialization of variable
When we declare a variable it's default value is undetermined. We can declare a variable with some
initial value.
int a = 20;
INPUT/OUTPUT (I/O) : C++ supports input/output statements which can be used to feed new data
into the computer or obtain output on an output device such as: VDU, printer etc. The following C++
stream objects can be used for the input/output purpose.
cin console input , cout console output.
cout is used in conjuction with << operator, known as insertion or put to operator.
cin is used in conjuction with >> operator, known as extraction or get from operator.
cout << “My first computer";Once the above statement is carried out by the computer, the message
"My first computer" will appear on the screen.
cin can be used to input a value entered by the user from the keyboard. However, the get from
operator>> is also required to get the typed value from cin and store it in the memory location.
Let us consider the following program segment:
int marks;
cin >> marks;In the above segment, the user has defined a variable marks of integer type in the first
statement and in the second statement he is trying to read a value from the keyboard.
Comments are used for better understanding of program statements and escaped by the
compiler to compile e.g. – single line (//) and multi line(/*….*/)
TYPE CONVERSION
The process in which one pre-defined type of expression is converted into another type is called
conversion. There are two types of conversion in C++.
1. Implicit conversion 2. Explicit conversion

Implicit conversion: Data type can be mixed in the expression. For example
double a;
int b = 5;
float c = 8.5;
a = b * c;
When two operands of different type are encountered in the same expression, the lower type variable
is converted to the higher type variable. The following table shows the order of data types.
Order of data types

Data type
order
long double
double
(highest)
float
To
long
int
(lowest)
char
The int value of b is converted to type float and stored in a temporary variable before being multiplied
by the float variable c. The result is then converted to double so that it can be assigned to the double
variable a.

Explicit conversion: It is also called type casting. It temporarily changes a variable data type from its
declared data type to a new one. It may be noted here that type casting can only be done on the right
hand side the assignment statement.
T_Pay = double (salary) + bonus;
Initially variable salary is defined as float but for the above calculation it is first converted to double
data type and then added to the variable bonus.

CONSTANTS
A number which does not change its value during execution of a program is known as a constant. Any
attempt to change the value of a constant will result in an error message. A constant in C++ can be of
any of the basic data types, const qualifier can be used to declare constant as shown below:
const float pi = 3.1415;The above declaration means that Pi is a constant of float types having a value
3.1415.
Examples of valid constant declarations are:
const int rate = 50;
const float pi = 3.1415;
const char ch = 'A';

XII/Computer Science 4
OPERATORS
Operators are special symbols used for specific purposes. C++ provides six types of operators.
Arithmetical operators, Relational operators, Logical operators, Unary operators, Assignment
operators, Conditional operators, Comma operator

Arithmetical operators
Arithmetical operators +, -, *, /, and % are used to performs an arithmetic (numeric) operation. You
can use the operators +, -, *, and / with both integral and floating-point data types. Modulus or
remainder % operator is used only with the integral data type.
Operators that have two operands are called binary operators.

Relational operators
The relational operators are used to test the relation between two values. All relational operators are
binary operators and therefore require two operands. A relational expression returns zero when the
relation is false and a non-zero when it is true. The following table shows the relational operators.

Relational Operators Meaning


< Less than
<= Less than or equal to
== Equal to
> Greater than
>= Greater than or equal to
!= Not equal to

Logical operators
The logical operators are used to combine one or more relational expression. The logical operators are

Operators Meaning
|| OR
&& AND
! NOT

Unary operators
C++ provides two unary operators for which only one variable is required.
For Example a = - 50;
a = + 50;
Here plus sign (+) and minus sign (-) are unary because they are not used between two variables.

Assignment operator
The assignment operator '=' is used for assigning a variable to a value. This operator takes the
expression on its right-hand-side and places it into the variable on its left-hand-side. For example: m =
5;The operator takes the expression on the right, 5, and stores it in the variable on the left, m.x = y =
z = 32;This code stores the value 32 in each of the three variables x, y, and z.
in addition to standard assignment operator shown above, C++ also support compound assignment
operators.
Compound Assignment Operators
Operator Example Equivalent to
+= A+=2 A=A+2
-= A-=2 A=A-2
%= A%=2 A=A%2
/= A/ = 2 A=A/2
*= A*=2 A=A*2

Increment and Decrement Operators


C++ provides two special operators viz '++' and '--' for incrementing and decrementing the value of a
variable by 1. The increment/decrement operator can be used with any type of variable but it cannot
be used with any constant. Increment and decrement operators each have two forms, pre and post.
The syntax of the increment operator is:
Pre-increment: ++variable
Post-increment: variable++

XII/Computer Science 5
The syntax of the decrement operator is:
Pre-decrement: ––variable
Post-decrement: variable––
In Prefix form first variable is first incremented/decremented, then evaluated
In Postfix form first variable is first evaluated, then incremented/decremented
int x,y;
int i=10,j=10;
x = ++i; //add one to i, store the result back in x
y= j++; //store the value of j to y then add one to j
cout<<x; //11
cout<<y; //10

Conditional operator
The conditional operator ?: is called ternary operator as it requires three operands. The format of the
conditional operator is:
Conditional_ expression ? expression1 : expression2;
If the value of conditional expression is true then the expression1 is evaluated, otherwise expression2
is evaluated.
int a = 5, b = 6;
big = (a > b) ? a : b;
The condition evaluates to false, therefore biggets the value from b and it becomes 6.

The comma operator


The comma operator gives left to right evaluation of expressions. When the set of expressions has to
be evaluated for a value, only the rightmost expression is considered.
int a=1, b=2, c=3, i; // comma acts as separator, not as an operator
i = (a, b); // stores b into iWould first assign the value of a to i, and then assign value of b to
variable i. So, at the end, variable i would contain the value 2.
The sizeof operator
As we know that different types of Variables, constant, etc. require different amounts of memory to
store them The sizeof operator can be used to find how many bytes are required for an object to store
in memory. For example
sizeof (char) returns 1, sizeof (int) returns 2, sizeof (float) returns 4
If k is integer variable, the sizeof (k) returns 2.
the sizeof operator determines the amount of memory required for an object at compile time
rather than at run time.
Precedence of operators

++(post increment),--(post decrement) Highest


++(pre increment),--(pre decrement),sizeof !(not),-(unary),+unary plus)
*(multiply), / (divide), %(modulus)
+(add),-(subtract)
<(less than),<=(less than or equal),>(greater than), >=(greater than or equal to)
==(equal),!=(not equal)
&& (logical AND)
||(logical OR)
?:(conditional expression)
=(simple assignment) and other assignment operators(arithmetic assignment operator)
, Comma operator

FLOW OF CONTROL Lowest


Statements
Statements are the instructions given to the computer to perform any kind of action. Action may be in
the form of data movement, decision making etc. Statements form the smallest executable unit within
a C++ program. Statements are always terminated by semicolon.

Compound Statement
A compound statement is a grouping of statements in which each individual statement ends with a
semi-colon. The group of statements is called block. Compound statements are enclosed between the
pair of braces ({}.). The opening brace ({) signifies the beginning and closing brace (}) signifies the
end of the block.

XII/Computer Science 6
Null Statement
Writing only a semicolon indicates a null statement. Thus ';' is a null or empty statement. This is quite
useful when the syntax of the language needs to specify a statement but the logic of the program does
not need any statement. This statement is generally used in for and while looping statements.

Conditional Statements
Sometimes the program needs to be executed depending upon a particular condition. C++ provides
the following statements for implementing the selection control structure.
 if statement
 if else statement
 nested if statement
 switch statement

if statement
syntax of the if statement
if (condition)
{
statement(s);
}

From the flowchart it is clear that if the if condition is true, statement is executed; otherwise it is
skipped. The statement may either be a single or compound statement.

if else statement

syntax of the if - else statement


if (condition)
statement1;
else
statement2;

From the above flowchart it is clear that the given


condition is evaluated first. If the condition is
true, statement1 is executed. If the condition is
false, statement2 is executed. It should be kept in
mind that statement and statement2 can be single
or compound statement.

Nested if statement
The if block may be nested in another if or else
block. This is called nesting of if or else block.
syntax of the nested if statement

if(condition 1) if(condition 1)
{ statement 1;
if(condition 2) else if (condition 2)
{ statement2;
statement(s); else statement3;
}
}

switch statement : The if and if-else statements permit two way branching whereas switch statement
permits multiple branching. The syntax of switch statement is:
switch (var / expression) The execution of switch statement begins
{ with the evaluation of expression. If the
case constant1 : statement 1; value of expression matches with the
break; constant then the statements following this
case constant2 : statement2; statement execute sequentially till it
break; executes break. The break statement
default: statement3; transfers control to the end of the switch
break; statement. If the value of expression does
} not match with any constant, the statement
with default is executed.

XII/Computer Science 7
Some important points about switch
statement
 The expression of switch statement must be of type integer or character
type.
 The default case need not to be used at last case. It can be placed at any
place.
 The case values need not to be in specific order.

Looping statement
It is also called a Repetitive control structure. Sometimes we require a set of statements to be
executed a number of times by changing the value of one or more variables each time to obtain a
different result. This type of program execution is called looping.
While loop: Syntax of while loop
while(condition)
{
statement(s);
}
The flow diagram indicates that a condition is first evaluated. If the condition is true, the loop body is
executed and the condition is re-evaluated. Hence, the loop body is executed repeatedly as long as the
condition remains true. As soon as the condition becomes false, it comes out of the loop and goes to
the statement next to the ‘while’ loop.
do-while loop: Syntax of do-while loop
do
{
statements;
} while (condition);
Note : That the loop body is always
executed at least once. One important
difference between the while loop and the
do-while loop the relative ordering of the
conditional test and loop body execution.
In the while loop, the loop repetition test
is performed before each execution the
loop body; the loop body is not executed
at all if the initial test fail. In the do-while
loop, the loop termination test is
Performed after each execution of the loop
body. hence, the loop body is always
executed least once.

for loop
It is a count controlled loop in the sense that the program knows in advance how many times the loop
is to be executed.
for (initialization; decision; increment/decrement)
{
statement(s);
}
The flow diagram indicates that in for loop three operations take
place:
 Initialization of loop control variable
 Testing of loop control variable
 Update the loop control variable either by incrementing or
decrementing.
Operation (i) is used to initialize the value. On the other hand,
operation (ii) is used to test whether the condition is true or false. If
the condition is false, the program executes the body of the loop and
then the value of loop control variable is updated. Again it checks the
condition and so on. If the condition is true, it gets out of the loop.
Jump Statements

XII/Computer Science 8
The jump statements unconditionally transfer program control within a function.

goto statement
syntax of goto statement
goto pqr:
pqr:
pqr is known as label. It is a user defined identifier. After the execution of goto statement, the control
transfers to the line after label pqr.

break statement
syntax of break statement
The break statement can be used in a switch statement and in any of the loops. It causes program
execution to pass to the next statement following the switch or the loop.

continue statement
The continue statement is used in loops and causes a program to skip the rest of the body of the loop.
while (condition)
{
Statement 1;
If (condition)
continue;
statement;
}
The continue statement skips rest of the loop body and starts a new iteration.

exit ( ) function
The execution of a program can be stopped at any point with exit ( ) and a status code can be
informed to the calling program. The general format is
exit (code) ;
where code is an integer value. The code has a value 0 for correct execution. The value of the code
varies depending upon the operating system. It requires a process.h header file.

FUNCTION
A function is a subprogram that acts on data and often returns a value. A program written with
numerous functions is easier to maintain, update and debug than one very long program. By
programming in a modular (functional) fashion, several programmers can work independently on
separate functions which can be assembled at a later date to create the entire project. Each function
has its own name. When that name is encountered in a program, the execution of the program
branches to the body of that function. When the function is finished, execution returns to the area of
the program code from which it was called, and the program continues on to the next line of code.

Creating User-Defined Functions

Declare the function.


The declaration, called the FUNCTION PROTOTYPE, informs the compiler about the functions to be
used in a program, the argument they take and the type of value they return.

Define the function.


The function definition tells the compiler what task the function will be performing. The function
prototype and the function definition must be same on the return type, the name, and the
parameters. The only difference between the function prototype and the function header is a
semicolon.

The function definition consists of the function header and its body. The header is EXACTLY like the
function prototype, EXCEPT that it contains NO terminating semicolon.
//Prototyping, defining and calling a function
#include <iostream.h>
void starline(); // prototype the function
int main()
{
starline( ); // function call
cout<< "\t\tBjarne Stroustrup\n";
starline( ); // function call

XII/Computer Science 9
return 0;
}

// function definition
void starline()
{
int count; // declaring a LOCAL variable
for(count = 1; count <=65; count++)
cout<< "*";
cout<<endl;
}
ARGUMENT TO A FUNCTION
Sometimes the calling function supplies some values to the called function. These are known as
parameters. The variables which supply the values to a calling function calledactual parameters. The
variable which receive the value from called statement are termed formal parameters.
Consider the following example that evaluates the area of a circle.
#include<iostream.h>
void area(float);
int main()
{
float radius;
cin>>radius;
area(radius);
return 0;
}
void area(float r)
{
cout<< “the area of the circle is”<<3.14*r*r<<”\n”;
}
Here radius is called actual parameter and r is called formal parameter.
RETURN TYPE OF A FUNCTION
// Example program
#include <iostream.h>
int timesTwo(int num); // function prototype
int main()
{
int number, response;
cout<<"Please enter a number:";
cin>>number;
response = timesTwo(number); //function call
cout<< "The answer is "<<response;
return 0;
}
//timesTwo function
int timesTwo (int num)
{
int answer; //local variable
answer = 2 * num;
return (answer);
}
CALLING OF FUNCTION
the function can be called using either of the following methods:
i) call by value
ii) call by reference
CALL BY VALUE
In call by value method, the called function creates its own copies of original values sent to it. Any
changes, that are made, occur on the function’s copy of values and are not reflected back to the calling
function.
CALL BY REFERENCE
In call be reference method, the called function accesses and works with the original values using their
references. Any changes, that occur, take place on the original values are reflected back to the calling
code.
Consider the following program which will swap the value of two variables.

XII/Computer Science 10
using call by reference using call by value

#include<iostream.h> #include<iostream.h>
void swap(int &, int &); void swap(int , int );
int main() int main()
{ {
int a=10,b=20; int a=10,b=20;
swap(a,b); swap(a,b);
cout<<a<<" "<<b; cout<<a<<" "<< b;
return 0; return 0;
} }
void swap(int &c, int &d) void swap(int c, int d)
{ {
int t; int t;
t=c; t=c;
c=d; c=d;
d=t; d=t;
} }

output: 20 10 output: 10 20

Function With Default Arguments


C++ allows to call a function without specifying all its arguments. In such cases, the function assigns a
default value to a parameter which does not have a mathching arguments in the function call. Default
values are specified when the function is declared. The complier knows from the prototype how many
arguments a function uses for calling.
Example :float result(int marks1, int marks2, int marks3=75);a subsequent function call
average = result(60,70);passes the value 60 to marks1, 70 to marks2 and lets the function use default
value of 75 for marks3.
The function callaverage = result(60,70,80);passes the value 80 to marks3.

INLINE FUNCTION
Functions save memory space because all the calls to the function cause the same code to be
executed. The functions body need not be duplicated in memory. When the complier sees a function
call, it normally jumps to the function. At the end of the function. it normally jumps back to the
statement following the call.
While the sequence of events may save memory space, it takes some extra time. To save execution
time in short functions, inline function is used. Each time there is a function call, the actual code from
the function is inserted instead of a jump to the function. The inline function is used only for shorter
code.
inline int cube(int r)
{
return r*r*r;
}
Some important points to be noted
 Function is made inline by putting a word inline in the beginning.
 Inline function should be declared before main() function.
 It does not have function prototype.
 Only shorter code is used in inline function If longer code is made inline then compiler
ignores the request and it will be executed as normal function.

Global Variable And Local Variable

Local Variable : a variable declared within the body of a function will be evaluated only within the
function. The portion of the program in which a variable is retained in memory is known as the scope
of the variable. The scope of the local variable is a function where it is defined. A variable may be
local to function or compound statement.
Global Variable : a variable that is declared outside any function is known as a global variable. The
scope of such a variable extends till the end of the program. these variables are available to all
functions which follow their declaration. So it should be defined at the beginning, before any function is
defined.

Variables and storage Class

XII/Computer Science 11
The storage class of a variable determines which parts of a program can access it and how long it stays
in existence. The storage class can be classified as automatic register static external
Automatic variable
All variables by default are auto i.e. the declarations int a and auto int a are equivalent. Auto variables
retain their scope till the end of the function in which they are defined. An automatic variable is not
created until the function in which it defined is called. When the function exits and control is returned
to the calling program, the variables are destroyed and their values are lost. The name automatic is
used because the variables are automatically created when a function is called and automatically
destroyed when it returns.
Register variable
A register declaration is an auto declaration. A register variable has all the characteristics of an auto
variable. The difference is that register variable provides fast access as they are stored inside CPU
registers rather than in memory.
Static variable
A static variable has the visibility of a local variable but the lifetime of an external variable. Thus it is
visible only inside the function in which it is defined, but it remains in existence for the life of the
program.
External variable
A large program may be written by a number of persons in different files. A variable declared global in
one file will not be available to a function in another file. Such a variable, if required by functions in
both the files, should be declared global in one file and at the same time declared external in the
second file.
ARRAY
An array is a collection of data elements of same data type. It is described by a single name and each
element of an array is referenced by using array name and its subscript no.

Declaration of Array
Type arrayName[numberOfElements];

For example,
int Age[5] ;
float cost[30];

Initialization of One Dimensional Array


An array can be initialized along with declaration. For array initialization it is required to place the
elements separated by commas enclosed within braces.int A[5] = {11,2,23,4,15};It is possible to
leave the array size open. The compiler will count the array size.int B[] = {6,7,8,9,15,12};

Referring to Array Elements


In any point of a program in which an array is visible, we can access the value of any of its elements
individually as if it was a normal variable, thus being able to both read and modify its value. The
format is as simple as: name[index]

Examples:
cout<<age[4]; //print an array element
age[4]=55; // assign value to an array element
cin>>age[4]; //input element 4

Using Loop to input an Array from user


int age [10], i ;
for (i=0 ; i<10; i++)
{
cin>>age[i];
}
Arrays as Parameters
XII/Computer Science 12
At some moment we may need to pass an array to a function as a parameter. In C++ it is not possible
to pass a complete block of memory by value as a parameter to a function, but we are allowed to pass
its address.
For example, the following function: void print(int A[])accepts a parameter of type "array of int"
called A.
In order to pass to this function an array declared as: int arr[20];we need to write a call like this:
print(arr);
Here is a complete example: Function to Read elements of the array A
#include <iostream.h> void Input(int A[], int n)
void print(int A[], int length) {
{ cout<<"Enter the elements:";
for (int n=0; n<length; n++) for(int i=0;i<n;i++)
cout << A[n] << " "; cin>>A[i];
cout << "\n"; }
} Function to Search for an element from A
int main () by Linear Search
{ int Lsearch(int A[], int n, int Data)
int arr[] = {5, 10, 15}; {
print(arr,3); int I;
return 0; for(I=0; I<n; I++)
} {
BASIC OPERATION ON ONE DIMENSIONAL if(A[I]==Data)
ARRAY {
Function to traverse the array A cout<<"Data Found at : "<<I;
void display(int A[], int n) return;
{ }
cout<<"The elements of the array are:\ }
n"; cout<<"Data Not Found in the
for(int i=0;i<n;i++) array"<<endl;
cout<<A[i]; }
}

TWO DIMENSIONAL ARRAY


It is a collection of data elements of same data type arranged in rows and columns (that is, in two
dimensions).

Declaration of Two-Dimensional Array


Type arrayName[numberOfRows][numberOfColumn];
For example, int Sales[3][5];

Initialization of Two-Dimensional Array


An two-dimensional array can be initialized along with declaration. For two-dimensional array
initialization, elements of each row are enclosed within curly braces and separated
by commas. All rows are enclosed within curly braces.int A[4][3] = {{22, 23, 10},
{15, 25, 13},
{20, 74, 67},
{11, 18, 14}};

Referring to Array Elements


To access the elements of a two-dimensional array, we need a pair of indices: one for
the row position and one for the column position. The format is as simple as:
name[rowIndex][columnIndex]
Examples:cout<<A[1][2]; //print an array elementA[1][2]=13; // assign value to an array
element
cin>>A[1][2]; //input element
Using Loop to input an Two-Dimensional Array from user

XII/Computer Science 13
int mat[3][5], row, col ;
for (row = 0; row < 3; row++)
for (col = 0; col < 5; col++)
cin >> mat[row][col];
Arrays as Parameters
Two-dimensional arrays can be passed as parameters to a function, and they are passed by reference.
When declaring a two-dimensional array as a formal parameter, we can omit the size of the first
dimension, but not the second; that is, we must specify the number of columns. For example: void
print(int A[][3],int N, int M)In order to pass to this function an array declared as: int arr[4][3];we
need to write a call like this: print(arr);
Here is a complete example:
#include <iostream.h> {
void print(int A[][3],int N, int M) for(int R=0;R<N;R++)
{ for(int C=0;C<M;C++)
for (R = 0; R < N; R++) {
for (C = 0; C < M; C++) C[R][C]=0;
cin >> A[R][C]; for(int T=0;T<L;T++)
} C[R][C]+=A[R][T]*B[T][C];
int main () }
{ }
int arr[4][3] ={{12, 29, 11}, Function to find & display sum of rows &
{25, 25, 13}, sum of cols. of a 2 dim. array A
{24, 64, 67}, void SumRowCol(int A[][20], int N, int M)
{11, 18, 14}}; {
print(arr,4,3); for(int R=0;R<N;R++)
return 0; {
} int SumR=0;
for(int C=0;C<M;C++)
Function to read the array A SumR+=A[R][C];
void Read(int A[][20], int N, int M)
{ cout<<"Row("<<R<<")="<<SumR<<endl;
for(int R=0;R<N;R++) }
for(int C=0;C<M;C++) for(int R=0;R<N;R++)
{ {
cout<<"(R<<','<<")?"; int SumR=0;
cin>>A[R][C]; for(int C=0;C<M;C++)
} SumR+=A[R][C];
} cout<<"Row("<<R<<")="<<SumR<<endl
;
Function to display content of a two }
dimensional array A }
void Display(int A[][20],int N, int M) Function to find sum of diagonal elements
{ of a square matrix A
for(int R=0;R<N;R++) void Diagonal(int A[][20], int N, int &Rdiag,
{ int &LDiag)
for(int C=0;C<M;C++) {
cout<<setw(10)<<A[R][C]; for(int I=0,Rdiag=0;I<N;I++)
cout<<endl; Rdiag+=A[I][I];
} for(int I=0,Ldiag=0;I<N;I++)
} Ldiag+=A[N-I-1][I];
Function to find the sum of two }
dimensional arrays A and B Function to find out transpose of a two
void Addition(int A[][20], int B[][20],int N, int dimensional array A
M) void Transpose(int A[][20], int B[][20],int N,
{ int M)
for(int R=0;R<N;R++) {
for(int C=0;C<M;C++) for(int R=0;R<N;R++)
C[R][C]=A[R][C]+B[R][C]; for(int C=0;C<M;C++)
} B[R][C]=A[C][R];
Function to multiply two dimensional }
arrays A and B of order NxL and LxM
void Multiply(int A[][20], int B[][20], int C[]
[20],int N, int L, int M)

XII/Computer Science 14
STRINGS (Character Arrays)
STRING: It is an array of type char.
Syntax for declaration
char <array/string name> [max. number of characters to be stored +1];
The number of elements that can be stored in a string is always n-1, if the size of the array specified is
n. This is because 1 byte is reserved for the NULL character '\0' i.e. backslash zero. A string is always
terminated with the NULL character.
Example:char str[80];In the above example, str can be used to store a string with 79 characters.
Initializing a string
A string can be initialized to a constant value when it is declared.
char str[ ] = "Good"; Orchar str[]={'G','o','o','d','\0'};
Here. 'G' will be stored in str[0], 'o' in str[1] and so on.
Note: When the value is assigned to the complete string at once, the computer automatically inserts
the NULL character at the end of the string. But, if it is done character by character, then we have to
insert it at the end of the string.
Reading strings with/without embedded blanks
To read a string without blanks cin can be usedcin>>str;To read a string with blanks cin.getline() or
gets() can be used.cin.getline(str,80); -Or-gets(str);
Printing strings
cout and puts() can be used to print a string.
cout<<str: Or puts(str);
Note: For gets( ) and puts(), the header file stdio.h has to be included. puts() can be used to display
only strings. It takes a line feed after printing the string.
cin gets()

It can be used to take input of a It can be used to take input of a


value of any data type. string.

It takes the white space i.e. a blank, It does not take the white space i.e.
a tab, or a new line character as a a blank, a tab, or a new line
string terminator. character, as a string terminator.

It requires header file iostream.h It requires the header file stdio.h

Example: Example:
char S[80]; char S[80];
cout<<"Enter a string:”; cout<<"Enter a string:";
cin>>S; gets(S);

cout puts()

It can be used to display the value It can be used to display the value
of any data type. of a string.

It does not take a line feed after It takes a line feed after displaying
displaying the string. the string.

It requires the header file iostream.h It requires the header file stdio.h

Example: Example:
char S[80]="Computers"; char S[80]="Computers";
cout<<S<<S; puts(S);
puts(S);
Output:
ComputersComputers Output:
Computers
Computers

Counting the number of characters in a string and cout<<"Enter a string:";


printing it backwards gets(str);
#include<iostream.h> for(int l=0; str[l]!='\0';l++); //Loop to find length
#include<stdio.h> cout<<"The length of the string is : "<<l<<endl ;
void main( ) for(int i=l-1;i>=0;i--) //Loop to display the string backwards
{ char str[80];

XII/Computer Science 15
cout<<str[i]; return (C==L/2)?1:0; //Returns 1 if Palindrome else 0
} }
Function to count the number of words in a string Function to change the case of string S to uppercase
void count(char S[]) void Upper(char S[])
{ { for(int i=0;S[i]!='\0';i++)
int words=0; S[i] = (S[i]>='a' && S[i]<='z')?(S[i]-32):S[i];
for(int i=0;S[i]!='\0';i++) }
{ Function to change the case of string S to lower case
if (S[i]==' ') void Lower(char S[])
words++; //Checking for spaces {
} for(int i=0;S[i]!='\0';i++)
cout<<"The number of words="<<words+1<<endl; S[i] = (S[i]>='A' && S[i]<='Z')?(S[i]+32):S[i];
} }
Function to find the length of a string Function to extract n characters from left side of the
int length(char S[ ]) string and store it in a different string. Example: 4
{ characters from ENVIRONMENT=ENVI
for(int i=0;S[i]!='\0';i++); int SLeft(char S[ ], int n, char result[ ])
return i; {
} for(int l=0;S[l]!='\0';l++);
Function to copy the contents of string S2 to S1 if(n<=I) //characters extracted should be <=length
void copy(char S1[ ], char S2[ ]) {
{ for(int i=0;i<n;i++)
for(int i=0;S2[i]!='\0';i++) result[i]=S[i];
S1[i]=S2[i]; result[i]='\0';
S1[i]='\0'; return 1;
} }
Function to concatenate the contents of string S2 to S1 else
void concat(char S1[ ], char S2[ ]) return 0;
{ }
for(int l=0;S1[l]!='\0';l++); Function to extract n characters from right side of the
for(int i=0;S2[i]!='\0';i++) string and store it in a different string. Example: 4
S1[l++]=S2[i]; characters from ENVIRONMENT=MENT
S1[l]='\0'; int SRight(char S[ ], int n, char result[ ])
} { for(int l=0;S[l]!='\0';l++);
Function to compare strings STR1 to STR2. The function if(n<=I) //characters extracted should be <=length
returns a value>0 if //STR1>STR2, a value<0 if {
STR1<STR2, and value 0 if STR1=STR2 for(int j=0;i=l-n;S[i]!=’/0’;i++,j++)
int compare(char STR1[ ],char STR2[]) result[j]=S[i];
{ result[j]='\0';
for(int I=0;STR1[I]==STR2[I] && STR1[I]!='\0'&&STR2[I]! return 1;
='\0'; I++); }
return STR1[I]-STR2[I]; else
} return 0;
To reverse the contents of string S and store it in string }
Rev Function to extract n characters from specified location
void Reverse(char S[], char Rev[]) loc of the string and store it in a different string.
{ Example: 4 characters from third location in string
for(int C1=0; S[C1]!='\0'; C1++); ENVIRONMENT= VIRO
C1--; int substring(char S[ ], int n, int loc, char result[ ])
for(int C2=0;C1>=0;C2++,C1--) { for(int l=0;S[l]!='\0';l++);
Rev[C2]=S[C1]; if(n<=I) //characters extracted should be <=length
Rev[C2]='\0'; { for(int j=0;i=l-n;S[i]!=’/0’;i++,j++)
} result[j]=S[i];
Function to check whether a string S is a palindrome or result[j]='\0';
not return 1;
int Palin(char S[]) }
{ for(int L=0;S[L]!='\0';L++); //To find length else
for(int C=0;(C<L/2) && (S[C]==S[L-C-1]);C++); return 0;
}

INBUILT FUNCTIONS

Head
Function
er
Name
Description Example
File

XII/Computer Science 16
 reads a single character directly from the
keyboard, without echoing to the screen. char ch = getch();
conio.h getch()
 returns the character read from the keyboard. cout<<ch;
 It can also be used to freeze screen
clrscr()  clears the text mode screen clrscr()

getchar()  Reads a character from the keyboard Ch = getchar();

putchar()  Displays a charcter on the screen putchar(ch);


stdio.h

 Gets a string from Keyboard.


char str[25];
gets()  gets allows input strings to contain certain
gets(str);
whitespace characters (spaces, tabs).
 Outputs a string to VDU and moves the cursor to
puts() puts(str)
next line.
 Checks whether the argument passed is char Ch; cin>>ch;
if (isalnum(ch))
alphanumeric (A to Z or a to z or 0 to 9).
isalnum() cout<<”Alphanumeric”;
 Returns a non-zero value if the argument is else
alphanumeric. cout<<”Not alphanumeric”;
 Checks whether the argument passed is an char Ch; cin>>ch;
if (isalpha(ch))
alphabet or not.
isalpha() cout<<”Alphabet”;
 Returns a non-zero value if the argument is an else
alphabet. cout<<”Not an alphabet”;
 Checks whether the argument passed is a digit (0 char Ch; cin>>ch;
if (isdigit(ch))
to 9) or not.
isdigit() cout<<”Digit”;
 Returns a non-zero value if the argument is a else
digit. cout<<”Not a digit”;
(Character Functions)

char Ch; cin>>ch;


 Checks whether the argument passed is a if (isalpha(ch))
lowercase alphabet (a to z) or not. cout<<”Lowercase Alphabet”;
islower()
ctype.h

 Returns a non-zero value if the argument is a else


lowercase alphabet. cout<<”Not a lowercase
alphabet”;
char Ch; cin>>ch;
 Checks whether the argument passed is a if (isalpha(ch))
uppercase alphabet (A to Z) or not. cout<<”Uppercase Alphabet”;
isupper()
 Returns a non-zero value if the argument is an else
uppercase alphabet. cout<<”Not an uppercase
alphabet”;
char Ch; cin>>ch;
 Converts the argument passed to a lowercase ch = tolower(ch);
alphabet (a to z) if it is an uppercase alphabet cout<<ch;
tolower()
otherwise argument remains unchanged. /*if user enters an uppercase
 Returns the converted letter. alphabet like ‘A’ then ‘a’ will be
displayed on screen*/
char Ch; cin>>ch;
 Converts the argument passed to an uppercase ch = toupper(ch);
alphabet (A to Z) if it is a lowercase alphabet cout<<ch;
toupper()
otherwise argument remains unchanged. /*if user enters a lowercase
 Returns the converted letter. alphabet like ‘a’ then ‘A’ will be
displayed on screen*/
 Copies one string into another. strcpy(destination, source);
strcpy()
//Copies source into destination
string.h(String Functions)

strcpy(first, second);
strcat()  Joins two strings //Joins second at the end of
first
strlen()  Finds length of a string int len = strlen(str);

strcmp(“anil”,”ANIL”);
 Compares two strings for equality.
strcmp() //It would return a non-zero
 Returns 0 if two strings are same. value
strcmpi()  Compares two strings for equality (Ignoring strcmp(“anil”,”ANIL”);
case). //It would return zero
 Returns 0 if two strings are same.

XII/Computer Science 17
 Reverses a string.
 strrev changes all characters in a string to strrev(“string”);
strrev() reverse order, except the terminating null // it would change “string” to
character. “gnirts”)

 Converts lowercase letters in a string to uppercase.


 The conversion is from lowercase letters (a to z) to strupr(“Anil”);
strupr()
uppercase letters (A to Z). No other characters are //Will return “ANIL”
changed.
 Converts uppercase letters in a string to
lowercase.
strupr(“Anil”);
strlwr()  The conversion is from lowercase letters (A to Z)
//Will return “anil”
to uppercase letters (a to z). No other characters
are changed.
 Returns the absolute value of a floating-point double x = fabs(-2.3);
fabs()
number. //it would return 2.3
(Mathematical Functions)

 double pow(double x, double y) cout<<pow(2,3);


pow()
 Calculates & returns x to the power of y. //Will display 8.
 calculates the positive square root of the cout<<sqrt(9); //Will display
sqrt()
math.h

argument 3.
double pi = 22.0/7;
 computes the sine of the angle passed as
sin() cout<<sin(pi/2);
argument. Angles are specified in radians. //would return 1
 computes the cosine of the angle passed as cout<<cos(0);
cos()
argument. Angles are specified in radians. //would return 1
 returns the absolute value of the integer int x = fabs(-2);//it would
abs()
argument return 2
randomiz  initializes the random number generator with a
randomize();
e() random value.
 int random(int num); cout<<random(2);
random()
 returns a random number between 0 and (num-1). //would display either 0 or 1.
 itoa(int value, char string[], int radix);
char str[17];
(Other Functions)

 Converts an integer to a string.


itoa(7,str,2);
 itoa converts value to a null-terminated string and
cout<<str;
itoa() stores the result in string. With itoa, value is an
stdlib.h

integer. radix specifies the base to be used in //would display 111 (Binary
converting value; it must be between 2 and 36, equivalent of 7 as the base is 2
inclusive.
(i) char str[]= "111";
 Converts a string to an integer. int x = atoi(str);
cout<<x;
 atoi returns the converted value of the input
atoi() //would display 111
string. If the string cannot be converted to an (ii) char str[]= "abc";
integer, atoi returns 0. int x = atoi(str);
cout<<x; //would display 0

typedef

It is used to define new data type for an existing data type. It provides and alternative name for
standard data type. It is used for self documenting the code by allowing descriptive name for the
standard data type. The general format is:
typedef existing datatype new datatype
for example: typedef float real;
Now, in a program one can use datatype real instead of float.
Therefore, the following statement is valid: real amount;

Enumerated data type


The enum specifier defines the set of names which are stored internally as integer constant. The first
name was given the integer value 0, the second value 1 and so on. for example:
enum months{jan, feb, mar, apr, may} ;
It has the following features:

It is user defined.
It works if you know in advance a finite list of values that a data type can take.

XII/Computer Science 18
The list cannot be input by the user or output on the screen.

# Include Directive
The # include directive instructs the compiler to read and include another file in the current file.
The compiler compiles the entire code. A header file may be included in one of two ways.
# include <iostream.h>
or
#include "iostream.h"
The header file in angle brackets means that file reside in standard include directory. The header
file in double quotes means that file reside in current directory.

#define preprocessor directive

The #define preprocessor allows to define symbolic names and constants e.g.
#define pi 3.14159
This statement will translate every occurrence of PI in the program to 3.14159

Macros

Macros are built on the #define preprocessor. Normally a macro would look like:
#define square(x) x*x
Its arguments substituted for replacement text, when the macro is expanded.

STRUCTURE
A structure is a collection of variable which can be same or different types. You can refer to a
structure as a single variable, and to its parts as members of that variable by using the dot (.)
operator. The power of structures lies in the fact that once defined, the structure name becomes a
user-defined data type and may be used the same way as other built-in data types, such as int,
double, char.

struct STUDENT
{
int rollno, age; char
name[80]; float marks;
};
void main()
{
STUDENT s1, s3; // declare two variables of the new type
cin>>s1.rollno>>s1.age>>s1.name>>s1.marks;//accessing of data members
cout<<s1.rollno<<s1.age<<s1.name<<s1.marks;
STUDENT s2 = {100,17,”Aniket”,92}; //initialization of structure variable
cout<<s2.rollno<<s2.age<<s2.name<<s2.marks;
s3=s2; //structure variable in assignment statement
cout<<s3.rollno<<s3.age<<s3.name<<s3.marks;
}

Defining a structure

When dealing with the students in a school, many variables of different types are needed. It may be
necessary to keep track of name, age, Rollno, and marks point for example.

struct STUDENT
{
int rollno, age; char
name[80]; float marks;
};

STUDENT is called the structure tag, and is your brand new data type, like int, double or char.
rollno, name, age, and marks are structure members.

Declaring Variables of Type struct

The most efficient method of dealing with structure variables is to define the

XII/Computer Science 19
structure globally. This tells "the whole world", namely main and any functions in the program, that
a new data type exists. To declare a structure globally, place it BEFORE void main(). The structure
variables can then be defined locally in main, for example…

struct STUDENT
{
int rollno, age; char
name[80]; float marks;
};

void main()
{
// declare two variables of the new type
STUDENT s1, s3;
………
}

Alternate method of declaring variables of type struct:

struct STUDENT
{
int rollno, age; char
name[80]; float marks;
} s1, s3;

Accessing of data members


The accessing of data members is done by using the following format:
structure variable.member name for example
cin>>s1.rollno>>s1.age>>s1.name>>s1.marks;

Initialization of structure variable


Initialization is done at the time of declaration of a variable. For example
STUDENT s2 = {100,17,”Aniket”,92};

Structure variable in assignment statement


The statement
s3=s2;
assigns the value of each member of s2 to the corresponding member of s3. Note that one
structure variable can be assigned to another only when they are of the same structure type,
otherwise complier will give an error.
Nested structure (Structure within structure)

It is possible to use a structure to define another structure. This is called nesting of structure.
consider the following program

struct DAY
{int month, date, year;
};
struct STUDENT
{
int rollno, age; char
name[80]; day
date_of_birth; float marks;
};

IMPORTANT QUESTIONS (SOLVED)

Q1. What is the difference between Global Variable and Local Variable?
Answer:
Global Variable Local Variable

XII/Computer Science 20
 It is a variable, which is declared outside all  It is a variable, which is declared with
the functions in a function or with in a compound
statement
 It is accessible throughout the program  It is accessible only within a
function/compound statement in
which it is declared
#include <iostream.h>
float NUM=900; //NUM is a global variable
void LOCAL(int T)
{ int Total=0; //Total is a local variable
for (int I=0;I<T;I++)
Total+=I;
cout<<NUM+Total;
}
void main()
{ LOCAL(45);}
Q2. What is the difference between logical and syntax errors?
Ans. Logical Error: Error occurred due to incorrect logic applied by the programmer.
Syntax Error: Error occurred due to not following the proper grammar/syntax of the language
OR Error occurred due to violating rules of the programming language
Example:
//Program to find area and perimeter of rectangle
void main()
{int A,B,AR,P;
A=10;
B=20;
AR=2*(A*B); //Logical Error – Wrong Formula
P=2*(A+B);
cout<<A<<P>>endl; //Syntax Error – Use of >> with cout
}
Q3. What is the difference between Run Time and syntax errors?
Ans. Run Time Error : Error occurring in a program during its execution. Program execution halts
when such an error is encountered.
Example:
int A,B,C;
cin>>A>>B;
C=A/B;//Runtime error if value of B is zero.
Syntax Error: Error occurred due to wrong syntax of language detected by the compiler during
compilation.
Example: cout>>”A C++ Program”;
Q4. Differentiate between type casting and type promotion with suitable example.
Ans. Type Promotion : Automatic conversion of a lower data type to the highest data type in an
expression is known as type promotion. It is done by the compiler.
Example : int a = 5; float b = 10.5; float c = a + b;
In the above expression first integer ‘a’ will be converted to float and then addition will be carried out.
Type Casting : Conversion of one data type into another by the programmer is called type casting. It
can be from lower to upper or vice versa.
Example : float x = 10.5; cout<<(int)x;
Q5. What is the difference between #define and const? Explain with suitable example.
Ans: #define: It is a preprocessor directive in C++ for creating a Macro ( a constant number or
function). Example: #define SIZE 5
const: It is an Access Modifier in C++ that assigns a constant (non modifiable) value to a variable.
Any attempt in modifying the value assigned to such a variable is
reported as an error by the compiler.
Example: const float Pi = 3.14;

XII/Computer Science 21
Q6. What is the purpose of using a typedef command in C++. Explain with suitable
example.
Ans: Typedef: This keyword allows creating synonyms or aliases for previously defined dataTypes OR
typedef is used for renaming a data type.The general form of typedef is
typedef old_name new_name;
Example:
typedef char STR [80];
OR
typedef signed char SMALLNUM;
OR
typedef float REAL;
OR
typedef long int BIGNUM;
OR
typedef int MAT[2][3] ;
Q7. What is the difference between call by value and call by reference? Give an example in
C++ to illustrate both.
Ans Call by value is used to create a temporary copy of the data coming from the actual parameter
into the formal parameter. The changes done in the function in formal parameter are not reflected
back in the calling environment. It does not use ‘&’ sign.
Call by reference is used to share the same memory location for actual and formal parameters and so
changes done in the function are reflected back in the calling environment. It uses ‘&’ sign.
void Compute(int A, int &B)
{A++; B++;
cout<<”In the function”<<endl;
cout<<”A=”<<A<<“&”<<“B=”<<B<<endl;}
void main ()
{int I=50,J=25;
cout<<”Before function call “<<endl;
cout<<”I=”<<I<<”&”<<”J=”<<J <<endl;
Compute (I,J) ;
cout<<”After function call “<<endl;
cout<<I=”<<I<<”&”<<”J=”<<J <<endl;}
OUTPUT
Before function call
I=50&J=25
In the function
A=51&B=26
After function call I=50&J=26
Q8. What is the difference between Actual Parameter and Formal Parameter? Give an
example in C++ to illustrate both types of parameters.
Ans A parameter used in the function call is known as Actual Parameter. It is used to send the data to
function.
A parameter used in the function definition is known as Formal Parameter, It is used to accept the data
from actual parameter.
void Seventimes(int A)//A is formal parameter
{ cout<<7*A;}
void main ()
{int P=6;
Seventimes(P);//p is actual parameter }

XII/Computer Science 22
HOME ASSIGNMENT – 1
REVIEW OF CLASS- XI

1. Name the basic data types in C+ 11. What is the use of goto statement
+.Why char is treated as integer in C++? Explain with suitable
data type? example. Why programmers avoid
2. What is # in C++? Differentiate the use of go to statement?
between #include and # define 12. What is function prototype? Give
with suitable C++ code. an example of a function prototype
3. Differentiate between # define and with default value of one of the two
const with suitable C++ code. parameters.
4. Differentiate between type casting 13. Why main() is a special function?
and type promotion with suitable 14. Differentiate between actual and
C++ code. formal parameters with suitable C+
5. Differentiate between while and + code.
do-while loops with suitable C++ 15. Differentiate between call by value
code. and call by reference with suitable
6. Give limitations of switch C++ code.
statement. 16. What is an inline function?
7. Give limitations of conditional 17. Differentiate between global and
operator. local variable with suitable C++
8. What are increment and decrement code.
operators in C++? Explain with 18. Differentiate between an array and
suitable examples. a structure.
9. Differentiate between break and 19. What is a nested structure? Explain
continue with suitable C++ code. with suitable example.
10. Differentiate between break and 20. Explain the use of typedef with
exit with suitable C++ code. suitable example.

IMPORTANT QUESTIONS

1. Observe the following program and }


find out, which output(s} out if (i) to }
(iv) will not be expected from the (i) 9#6# (ii) 19#17#
program? What will be the minimum (iii) 19#16# (iv) 20#16#
and the maximum value assigned to
the variable Chance? 2. In the following program, if the value
#include <iostream.h> of N given by the user is 15, what
#include <stdlib.h> maximum and minimum values the
void main ( ) program could possibly display?
{ #include <iostream.h>
randomize( ) ; #include <stdlib.h>
int Arr[]={9,6}, N; void main()
int Chance=random(2) + 10 ; { int N,Guessme;
for (int C=0;C<2;C++) randomize();
{ cin>>N;
N=random (2) ; Guessme=random(N)+10;
cout<<Arr [N] + Chance«"#"; cout<<Guessme<<endl;
}

XII/Computer Science 23
3. In the following program, find the Encrypt(Text);
correct possible output(s) from the cout<<Text<<endl;
options }
#include<stdlib.h> (c) int A[][3] = {{1,2,3}, {5,6,7}};
#include<iostream.h> for (int i = 1; i<2; i++)
void main( ) for (int j = 0; j<3; j++)
{ randomize( ); cout<<A[i][j]<<"*\n";
char City [ ] [10] = {“DEL”,
“CHN”, “KOL”, “BOM”, “BNG”}; (d)
int Fly;
int a = 3;
for (int I=0;1<3;1++)
void demo(int x, int y, int &z)
{ Fly = random(2)+1;
{ a += x+y;
cout<<City [Fly]<<”:”;
z = a+y;
}
y += x;
}
cout<<x<<'*'<<y<<'*'<<z<<endl;
(i) DEL:CHN:KOL: (ii) CHN:KOL:CHN:
(iii) KOL:BOM:BNG: (iv) KOL:CHN:KOL: }
void main()
4. Find the output { int a = 2, b = 5;
(a) #include<iostream.h> demo(::a,a,b);
#include<string.h> demo(::a,a,b);
#include<ctype.h> }
void main ( )
{
char str[]=”Good@luck10!”; 5. Write the prototype of a function named
for( int c=0; c<strlen(str); c++) Percent, which takes an integer as value
{ parameter and return a float type value.
if(islower(str[c])) The parameter should have a default
str[c]=toupper(str[c]); value 10.
else if(isupper(str[c]))
str[c]=tolower(str[c]); 6. Write the names of header files, which
else if(isdigit(str[c])) are NOT necessary to run the following
str[c]=str[c] + 1; program:
else #include <iostream.h>
str[c]=’*’; #include <stdio.h>
} cout<<str; #include <string.h>
} #include <math.h>
(b) #include <iostream.h> void main()
#include <ctype.h> {
void Encrypt(char T[]) char STR[80];
{ gets(STR);
for (int i=0;T[i]!='\0';i+=2) puts(strrev(STR));
if (T[i]=='A' || T[i]=='E') }
T[i]='#';
else if (islower(T[i])) 7. Tarunaj has just started working as
T[i]=toupper(T[i]); programmer in the JAGAT WORLD
else SOFTWARE company. In the company,
T[i]='@'; he has got his first assignment to
} develop a small C++ module to find
void main() the biggest number out of a given set
{ char Text[]="SaVE EArtH”; of numbers stored in a one
XII/Computer Science 24
dimensional array. Somehow he has void main()
committed a few logical mistakes while {PLAY PL={10,15};
writing this code and so he is not Calculate(PL,5);
getting the desired result from the cout<<PL.Score<<”:”<<PL.Bonus<<endl;
code. Find out the mistakes and Calculate(PL);
correct this C++ code so that it cout<<PL.Score<<”:”<<PL.Bonus<<endl;
provides the desired result (do not add Calculate(PL,15);
any new statement in the code). cout<<PL.Score<<”:”<<PL.Bonus<<endl;}
Underline each correction made:
int BIGFIND(int ARR[],int Size) 10. Find the output:
{ int BIG=ARR[1]; struct MyBox
for (int C=2;C<Size;C++) { int Length, Breadth, Height;};
if (ARR[C]<BIG) void Dimension (MyBox M)
ARR[C]=BIG; {cout<<M.Length<<"x"<<M.Breadth<<"x";
return BIG; } cout<<M.Height<<endl;}
void main ()
8. Give the output {
#include<iostream.h>
MyBox B1={10,15,5}, B2, B3;
struct Pixel
++B1.Height;
{ int C,R;};
Dimension(B1);
void Display(Pixel P)
B3 = B1;
{cout<<"Col”<<P.C<<"Row"<<P.R<<endl;
++B3.Length;
}
B3.Breadth++;
void main()
Dimension(B3);
{ Pixel X={40,50},Y,Z;
B2 = B3;
Z=X;
B2.Height+=5;
X.C+=10;
B2.Length--;
Y=Z;
Dimension(B2);
Y.C+=10;
}
Y.R+=20;
Z.C-=15;
Display(X); 11. Rewrite the following program after
Display(Y); removing the syntactical errors (if any).
Display(Z); struct Pixels
} { int Color, Style;}
void ShowPoint(Pixels P)
9. Find the output { cout<<P.Color, P.Style<<endl;}
struct PLAY void main()
{ { Pixels Point1=(5,3);
int Score, Bonus; ShowPoint(Point1);
}; Pixels Point2=Point1;
void Calculate(PLAY &P, int N=10) Color.Point1+=2;
{ ShowPoint(Point2);
P.Score++; }
P.Bonus+=N;
}
LAB EXERCISES – 1
REVIEW OF CLASS- XI

XII/Computer Science 25
LAB 1.1- Write a function to check whether a number is prime or not. The prototype of
the function is : char prime( int N );
Now use this function to display first 20 prime numbers.

LAB 1.2- Write a function to check whether a string is palindrome or not. The function will
return ‘y’ if the passed string is a palindrome otherwise ‘n’ will be returned. The prototype of
the function is : char palindrome( char string[] );
Now write main() function to declare and obtain a string from the user. Call the above
function ( pass the string as an argument) and display the result.

AB 1.3- Write a function to count number of multiples of 7 in an integer array of N


numbers. The prototype of the function is : unsigned int Count( int list[], int N = 10 );
Now write main() function to declare and obtain an integer array from the user. Call the
above function and display the result.

LAB 1.4 Write a function to display all the elements which lie on two diagonals of a
square array. The array and its size will be passed as arguments. Also find and return the
sum of these elements. Now write main() function to declare and obtain the values of an
array of marks from the user. Call the above functions and display the result.

LAB 1.5 (a) Define a structure TIME having 3 members hh,mm and ss of integer type.
(b) Write a function to add two objects of time and also return the added time. The prototype
of the function is given below: TIME ADD(TIME A, TIME B);
(c) Write another function two return the greater object out of the two objects passed to
them. The prototype of the function is given below:
TIME GREATER(TIME A, TIME B);
(d) Now write main function to
1) create 2 objects of type TIME.
2) Obtain the values of these variables from the user.
3) Call the function to add these two objects and display the addition.
Example: Time1 : 2 h 50 m 35 sec and time2 : 3 h 40 m 30 s
Total time : 6 h 31 m 5
4) Call greater function and display the greater TIME. If two times are equal, display
an appropriate message.

XII/Computer Science 26
BASIC CONCEPTS OF OOPS

Paradigm-: It means organizing principle of does not model real world well.
a program. It is an approach to
programming. Object Oriented programming
The OBJECT ORIENTED PROGRAMMING
Procedural Paradigm PARADIGM models the real world well and
In PROCEDURAL PROGRAMMING overcomes the shortcomings of procedural
PARADIGM, the emphasis is on doing things paradigm. It views a problem in terms of
i.e., the procedure or the algorithm. The objects and thus emphasizes on both
data takes the back seat in procedural procedures as well as data.
programming paradigm. Also, this paradigm

Differences between Object Oriented Programming and Procedural Programming


Object Oriented Programming Procedural Programming
 Emphasis on Data  Emphasis on doing things (functions)
 Follows Bottom-Up approach in program  Follows Top-down approach in program
design design
 Data hiding feature prevents accidental  Presence of Global variables increase
change in data chances of accidental change in data
 Features like data encapsulation,  Such features are not available
polymorphism, inheritance are present

The following are the basic concepts used in object-oriented programming.


Object-: An object is an identifiable entity
with some characteristics and behavior. Base and sub classes-: The class whose
properties are inherited is called base class
(or superclass) and the class that inherits
the properties is known as derived class(or
subclass).

Derived Class :- The class, which inherits


from other classes is called derived class or
Subclass.

Class-: A class represents a group of objects Abstract class : An abstract class is a class
that share common properties, behavior and that that cannot be used to create objects.
relationships. An abstract class is meant to be used as the
base class from which other classes are
Data Abstraction-: Abstraction refers to act derived.
of representing essential features without
including the background details or Concrete class: A concrete class is a class
explanations. that can be used to create objects.

Encapsulation-: The wrapping up of data Advantages of Object oriented


and associated functions into a single unit is programming.
known as Encapsulation. Encapsulation  Software complexity can be easily
implements data abstraction. managed
 Object-oriented systems can be easily
Modularity-: Modularity is the property of a upgraded.
system that has been decomposed into a set  It is quite easy to partition the work in a
of cohesive and loosely coupled modules. project based on object.
Inheritance-: It is the capability of one
class of things to inherit capabilities or
properties from another class.
CLASS ENFORCE DATA-HIDING, ABSTRACTION & ENCAPSULATION
A class groups its members into three sections : private, protected, and public. The private and
protected members remain hidden from outside world. Thus through private and protected
members, a class enforces data-hiding.
The outside world is given only the essential and necessary information through public
members, rest of the things remain hidden, which is nothing but abstraction. Abstraction means
representation of essential features without including the background details and explanation.

XII/Computer Science 27
Polymorphism-: It is the ability for a message or data to be processed in more than one form.
Polymorphism is a property by which the same message can be sent to objects of several
different classes. Polymorphism is implemented in C++ through virtual functions and
overloading- function overloading and operator overloading.
FUNCTION OVERLOADING

Let us start this with a question! either having different number of parameters
or having parameters of different types.
All of you know that we cannot have two
variables of the same name, but can we have Example 1: Overloading Functions that differ
two Functions having the same name. in terms of NUMBER OF PARAMETERS

The answer is YES, we can have two //Example Program in C++


functions of the same name by a method #include<iostream.h>
known as function overloading and the
functions having the same name are known
//FUNTION PROTOTYPES
as overloaded functions.
int func(int i);
int func(int i, int j);
So, what’s the use of Function
Overloading
void main(void)
Function overloading is one of the most {
powerful features of C++ programming cout<<func(10);//func(int i)is called
language. It forms the basis of polymorphism
(compile-time polymorphism). cout<<func(10,10);//func(int i, int j)
The biggest advantage of overloading is that is called
it helps us to perform same operations on }
different datatypes without having the need
to use separate names for each version. Most
int func(int i)
of the time you’ll be overloading the
{
constructor function of a class.
return i;
}
How function overloading is achieved?
One thing that might be coming to your mind
is, how will the compiler know when to call int func(int i, int j)
which function, if there are more than one {
function of the same name. return i+j;
}
The answer is, you have to declare functions Example 2: Overloading Functions that differ
in such a way that they differ either in terms in terms of TYPE OF PARAMETERS
of the number of parameters or in terms of #include<iostream.h>
the type of parameters they take.
//FUNTION PROTOTYPES
This process of using two or more functions int func(int i);
with the same name but differing in the double func(double i);
signature is called function overloading.
void main(void)
But overloading of functions with different
{
return types is not allowed.
cout<<func(10);//func(int i)is called

In overloaded functions , the function call


cout<<func(10.201);//func(double i)
determines which function definition will be is called
executed. }
What that means is, nothing special needs to
be done, you just need to declare two or int func(int i)
more functions having the same name but {
return i;

XII/Computer Science 28
} {
return i;
double func(double i) }

One more Question, is the program below, valid?

//FUNTION PROTOTYPES
int func(int i);
double func(int i);

No, because you can’t overload functions if they differ only in terms of the data type they
return.

IMPLEMENTATION OF CLASSES & OBJECTS


The mechanism that allows you to combine data and the function in a single unit is called a class.
Once a class is defined, you can declare variables of that type. A class variable is called object or
instance. In other words, a class would be the data type, and an object would be the variable.
Classes are generally declared using the keyword class, with the following format:
class class_name
{
private:
members1;
protected:
members2;
public:
members3;
};
Where class_name is a valid identifier for the class.
The body of the declaration can contain members, that can be either data or function
declarations, The members of a class are classified into three categories: private, public, and
protected. Private, protected, and public are reserved words and are called member access
specifiers. These specifiers modify the access rights that the members following them acquire.

private members of a class are accessible only from within other members of the same class.
You cannot access it outside of the class.

protected members are accessible from members of their same class and also from members
of their derived classes.

Finally, public members are accessible from anywhere where the object is visible.
By default, all members of a class declared with the class keyword have private access for all its
members. Therefore, any member that is declared before one other class specifier automatically
has private access.
Here is a complete example :
class student
{
private :
int rollno;
float marks;
public:
void getdata()
{
cout<<"Enter Roll Number : ";
cin>>rollno;
cout<<"Enter Marks : ";
cin>>marks;
}
void displaydata()
{
cout<<"Roll number : "<<rollno<<"\nMarks :
"<<marks;

XII/Computer Science 29
}
};
Object Declaration
Once a class is defined, you can declare objects of that type. The syntax for declaring a object is
the same as that for declaring any other variable. The following statements declare two objects
of type student:
student st1, st2;
Accessing Class Members
Once an object of a class is declared, it can access the public members of the class.
st1.getdata();
Defining Member function of class
You can define Functions inside the class as shown in above example. Member functions defined
inside a class this way are created as inline functions by default. It is also possible to declare a
function within a class but define it elsewhere. Functions defined outside the class are not
normally inline.
INLINE FUNCTIONS: In inline functions, the compiler replaces the function call
statement with the function code itself and then compiles the entire code. Since, the
copiler does not have to jump to another location to execute the function and then jump
back to the original location, inline functions run a little faster than the normal functions.
However, the memory used will be more. For example if 10 times an inline function is
called, there will be 10 copies of the function inserted into the code. Therefore, the
function should be made inline only when they are small. Also, inlining does not work for
functions having a loop, a switch, a goto or a return statement.
A function can be made inline by placing the keyword inline before it. For example:
inline void display()
{ cout<<”This is inline function”;}
When we define a function outside the class we cannot reference them (directly) outside of the
class. In order to reference these, we use the scope resolution operator, ::(double colon). In this
example, we are defining function getdata outside the class:
void student :: getdata()
{ cout<<"Enter Roll Number : ";
cin>>rollno;
cout<<"Enter Marks : ";
cin>>marks;
}

The following program demostrates the general features of classes. Member function initdata() is
defined inside the class. Member funcitons getdata() and showdata() defined outside the class.
class student //specify a class
{
private :
int rollno; //class data
members
void student :: showdata()
float marks;
{
public:
cout<<"Roll number : "<<rollno<<"\
void initdata(int r, int m)
nMarks : "<<marks;
{
}
rollno=r;
marks=m;
void main()
}
{
void getdata();// member function student st1, st2; //define two
void showdata(); objects of class student
}; st1.initdata(5,78); //call member
void student :: getdata() function to initialize
{ st1.showdata();
cout<<"Enter Roll Number : "; st2.getdata(); //call member
cin>>rollno; function to input data
cout<<"Enter Marks : "; st2.showdata(); //call member
cin>>marks; function to display data
} }

Difference between structures and classes:

XII/Computer Science 30
The only difference between a structure and a class in C++ is that by default
, members are public in structs whereas by default they are private in
classes.

Array of Objects: An array having class type elements is known as array of objects. It is
defined in the same way as any other type of array is defined. Considering the class student
declared in the previous example:

void main()
{ student obj[10]; // Array obj contains 10 objects of type
student.
for (int k = 0; k < 10; k++)
{ obj[k].getdata();} //invoking getdata() for a
particular object
for (int k = 0; k < 10; k++)
{ obj[k].showdata();} //invoking showdata() for a
particular object
}

Objects as Function arguments: Just like any other data type of C++, an object may also be
passed as a functions’s argument in two ways (i) By value and (ii) By Reference.
When an object is passed by value, the function creates its own copy of the object and works
with its own copy. Therefore any changes made to the object inside the function do not affect the
original object. On the other hand when an object is passed by reference its memory address is
passed to the function so that the called function works directly on the original object used in the
function call. Thus, any changes made to the object inside the function are reflected in the
original object as function is making changes in the original object itself.
Objects can not only be passed to functions but functions can also return an an object.
Let us understand these concepts with the help of a question:

Q. Write the definition for a class called complex that has floating point data members for
storing real and imaginary parts. The class has the following member functions:
void set(float, float) to set the specified value in object
void disp() to display complex number object
complex sum(complex) to sum two complex numbers & return complex number

#include<iostream.h>
#include<conio.h> void complex::disp()
class complex {
{ cout<<x<<" + j"<<y<<endl;
private: }
float x;
float y; void main()
public: {
void set(float real, float img) complex C1,C2,C3;
{
x=real; y=img; C1.set(2.5,7.1);
} C2.set(4.2,5.5);
complex sum(complex); C3=C1.sum(C2);
void disp();
}; cout<<"\n complex Number 1 =
complex complex::sum(complex C) ";
{ C1.disp();
complex t; cout<<"\n complex Number 2 =
t.x = x + C.x; ";
t.y = y + C.y; C2.disp();
return t; cout<<"\n complex Number 3 =
";
}
C3.disp();
}

XII/Computer Science 31
XII/Computer Science 32
IMPORTANT QUESTIONS
Q1. What is the difference between Object Oriented Programming and Procedural
Programming?
Ans.
Object Oriented Programming Procedural Programming
 Emphasis on Data  Emphasis on doing things
 Follows Bottom-Up approach in (functions)
program design  Follows Top-down approach in
 Data hiding feature prevents program design
accidental change in data  Presence of Global variables
 Features like data encapsulation, increase chances of accidental
polymorphism, inheritance are change in data
present  Such features are not available
Q2. What do you understand by Data Encapsulation and Data Hiding?

Answer:
Data Encapsulation: Wrapping up of data and function together in a single unit is known as
Data Encapsulation. In a class, we wrap up the data and function together in a single unit.
Data Hiding: Keeping the data in private visibility mode of the class to prevent it from
accidental change is known as Data Hiding.
class Computer Data Hiding
{
char CPU[10];int RAM;
public: Data Encapsulation
void STOCK();
void SHOW();
};
Q3. What do you understand by Polymorphism? Give a suitable example of the same.
Answer:
Polymorphism: It is a method of using the same operator or function (method) to work using
different sets of input. Function overloading is one of the example of polymorphism, where
more than one function carrying same name behave differently with different set of parameters
passed to them.
void Display()
{ cout<<”Hello!”<<endl;}
void Display(int N)
{
cout<<2*N+5<<endl;
}
Q4. Differentiate between public and private visibility modes in context of Object Oriented
Programming using a suitable example illustrating each.
Ans: public visibility mode: Members of a class declared under this visibility are accessible inside the
class (in member functions of the class) as well as by the Objects of that class (in any non
member function of the program, prototyped / defined after the class declaration).
private visibility mode: Members of a class declared under this visibility are accessible only
inside the class (in member functions of the class). They can not be accessed outside the class.
class Example
{ int Priv;
public:
void Assign ( )
{ Priv =10; //private member accessible only inside class }
};
void main ( )
{ Example E;
E.Assign( ); //public member accessible by Object
}
Q5. How are data abstraction and data encapsulation inter-related?
Ans. Abstraction refers to the act of representing essential features without including the
background details or explanations and encapsulation is wrapping up of data and function together
in a single unit. We can say that encapsulation is way of achieving abstraction.

XII/Computer Science 33
HOME ASSIGNMENT – 2
TOPIC : & Object Oriented Programming

Q 2.1 Define a class TEST in C++ with following description:


Private Members
TestCode of type integer
Description of type string
NoCandidate of type integer
CenterReqd (number of centers required) of type integer
A member function CALCNTR() to calculate and return the number of centers as
(NoCandidates/100+1)
Public Members
 A function SCHEDULE() to allow user to enter values for TestCode, Description, NoCandidate
& call function CALCNTR() to calculate the number of Centres
 A function DISPTEST() to allow user to view the content of all the data members

Q2.2 Define a class REPORT with the following specification:


Private members :
adno 4 digit admission number
name 20 characters
marks an array of 5 floating point values
average average marks obtained
GETAVG() a function to compute the average obtained in five subject
Public members:
READINFO() function to accept values for adno, name, marks. Invoke the function
GETAVG()
DISPLAYINFO() function to display all data members of report on the screen.
You should give function definitions

Q2.3 Define a class BOOK with the following specifications :


Private members of the class BOOK are
BOOK NO integer type
BOOKTITLE 20 characters
PRICE float (price per copy)
TOTAL_COST() A function to calculate the total cost for N number of copies where N is
passed to the function as argument.
Public members of the class BOOK are
INPUT() function to read BOOK_NO. BOOKTITLE, PRICE
PURCHASE() function to ask the user to input the number of copies to be purchased. It
invokes TOTAL_COST() and prints the total cost to be paid by the user.
Note : You are also required to give detailed function definitions.

Q2.4 Write the definition for a class called time that has hours and minutes as integer. The class has
the following member functions:
void settime(int, int) to set the specified value in object
void showtime() to display time object
time sum(time) to sum two time object & return time
1. Write the definitions for each of the above member functions.
2. Write main function to create three time objects. Set the value in two objects and
call sum() to calculate sum and assign it in third object. Display all time objects.

XII/Computer Science 34
LAB EXERCISES – 2
TOPIC : Object Oriented Programming
LAB 2.1 Define a class in C++ with following description:

Private Members
 A data member Flight number of type integer
 A data member Destination of type string
 A data member Distance of type float
 A data member Fuel of type float
 A member function CALFUEL() to calculate the value of Fuel as per the following criteria
Distance Fuel
<=1000 500
more than 1000 and <=2000 1100
more than 2000 2200
Public Members
 A function FEEDINFO() to allow user to enter values for Flight Number,
Destination, Distance & call function CALFUEL() to calculate the quantity of Fuel
 A function SHOWINFO() to allow user to view the content of all the data
members
Write main function to execute the class.

LAB 2.2 Define a class Garments in C++ with the following descriptions:
Private Members:
 GCode of type string
 GType of type string
 GSize of type integer
 GFabric of type string
 GPrice of type float
 A function Assign ( ) which calculates and assigns the value of GPrice as
follows
For the value ofGFabric as “COTTON”,
GType GPrice(Rs)
TROUSER 1300
SHIRT 1100
For GFabric other than “COTTON” the above mentioned GPrice gets reduced by
10%.
Public Members:
 A function Input ( ) to input the values of the data members GCode, GType,
GSize and GFabricl and invoke the Assign ( ) function.
 A function Display ( ) which displays the content of all the data members for a
Garment.
Write main function to execute the above class.

LAB 2.3 Write the definition for a class called Distance that has data member feet as integer and
inches as float. The class has the following member functions:
void set(int, float) to give value to object
void disp() to display distance in feet and inches
Distance add(Distance) to sum two distances & return distance
1. Write the definitions for each of the above member functions.
2. Write main function to create three Distance objects. Set the value in two objects
and call add() to calculate sum and assign it in third object. Display all distances.

XII/Computer Science 35
CONSTRUCTORS AND DESTRUCTORS

CONSTRUCTOR
Aa member function with the same name as its class is called constructor and it is used to initialize the objects of
that class type with legal initial values. Constructor is automatically called when an object is created of that class.
Need for Constructors
A structure or an array can be initializes at the time of their declaration. For example:
struct STUDENT
{
int RollNo;
float marks;
};
void main()
{
STUDENT A = {0, 0.0}; It is perfectly valid.
…………………
………………….
}
But if student is a class
class STUDENT
{
int RollNo;
float marks;
public :
…………………………..;
};
void main()
{
STUDENT A = {0, 0.0}; It is invalid because private data members are
inaccrssible from main()
…………………
………………….
}

Therefore to initialize data members at the time of declaration/creation of an object, we require a special function
called CONSTRUCTOR.

Characteristics of Constructor

 Name of the constructor function is same as the name of the class


 No return type required for constructor function.
 Constructor functions are called automatically at the time of creation of the object
 Constructors can be overloaded
 Constructor functions are defined in public section of the class.

Declaration and Definition of constructor

class STUDENT
{
int RollNo;
public :
student() This is a constructor.
{ Note that the function name is same as
RollNo = 0; class name and there is no return type (not
even void).
}
……….;
………..;
};

XII/Computer Science 36
Difference between the constructor and normal function

Constructor Normal Function


1. Constructor has same name as class name. 1. A normal function can have any legal name but
2. Constructor can not have any return type value not class name.
not even void. 2. A function should have any return type value.
3. Constructor is automatically called. 3. A function is explicitly called.
4. Constructor can not be static. 4. A Function can be static.

Types of Constructors

1. Default Constructor-: A constructor that accepts no parameters is known as default


constructor. For example default constructor of class student can be defined as:
class STUDENT
{
int RollNo;
public :
student() This is default constructor.
{
RollNo = 0;
}
……….;
………..;
};
void main()
{
STUDENT X ; Object X is created and default constructor is
automatically called to initialize RollNo with 0.
…………………
………………….
}
If no constructor is defined then the compiler supplies a default constructor.

2. Parameterized Constructor -: A constructor that receives arguments/parameters is called


parameterized constructor. For example Parameterized constructor of class student can be
defined as:
class STUDENT
{
int RollNo;
public :
student(int R) This is Parameterized constructor.
{
RollNo = R;
}
……….;
………..;
};
void main()
{
STUDENT X(10); Object X is created and Parameterized
………………… constructor is automatically called to initialize
RollNo with 10.
………………….
}

3. Copy Constructor-: A constructor that initializes data members of an object with values of
another object of the same class (passed as parameter) is called copy constructor. The argument
of a copy constructor is always an object of the same class and it is passed by reference method
only. It creates the copy of the passed object. For Example :
XII/Computer Science 37
class STUDENT
{
int RollNo;
public :
student(int R) This is Parameterized constructor.
{
RollNo = R;
}

student(student Y ) This is Copy constructor.


{
RollNo = Y.RollNo;
}
……….;
………..;
};
void main()
{
STUDENT A(10); A is created using Parameterized constructor and RollNo is initialized to 10.

STUDENT B(A); B is created and using Copy constructor RollNo is initialized to 10.

STUDENT C = A; Another way of calling copy constructor. Here Copy constructor is called
………………… again and RollNo of object C is initialized to 10.
………………….
}
Remember that a copy constructor may be called
 When an object is defined and initialized with another object.
 When an object is passed by value.
 When a function returns an object.

Why the argument to a copy constructor is passed by reference?


When an object is passed by value, a copy of it is created. To crate a copy of the object, copy
constructor is called, thus it calls itself. Again the called copy constructor requires another copy of the
object so again it is called. In fact it calls itself again and again until the compiler runs out of memory.
So, in the copy constructor, the argument must be passed by reference, to avoid creation of infinite
copies of the passed object.

There can be multiple constructors in the same class, provided they have different signatures i.e. r
they have either difeerent types of arguments or difeerent number of arguments. This feature is called
constructor overloading.(Example is given above)

CONSTRUCTOR WITH DEFAULT ARGUMENTS


Just like any other function, a parameterized constructor can also have default arguments. For
example:
class STUDENT
{
int RollNo;
public :
student(int R = 100) This is Parameterized constructor having
{ a default value for its parameter.
RollNo = R;
}
……….;
………..;
};

XII/Computer Science 38
void main()
{
STUDENT X(10); X is created and RollNo is initialized to 10 with Parameterized constructor.

STUDENT Y; Object Y is created and RollNo is initialized to the default value 100 using
………………… Parameterized constructor.
We can see that a constructor with default argument is equivalent to a
………………….
default constructor.
}

DESTRUCTOR

A destructor is a member function having same name as that of its class preceded by ~(tilde) sign and which is
used to destroy the objects that have been created by a constructor. It gets invoked when an object’s scope is
over.

Need for Destructors


During construction of an object by the constructor, resources may be allocated for use. For example . a
constructor may have opened a file and a memory area may be allotted to it. These allocated resources must be
deallocated before the object is destroyed. A destructor performs all clean-up tasks (like closing a file, deallocating
and releasing memory area) automatically.

Declaration and Definition of destructor


For example destructor of class student can be defined as :
class STUDENT
{
int RollNo;
public :
student()
{
RollNo = 0;
}
……….;
………..;
~student()
{
cout<< “This is destructor”; This is denstructor.
}

};

Characteristics of Destructors:
 Name of the destructor is same as the name of the class preceded by ~
 No return type required for destructor function.
 Destructor functions are called automatically when the scope of the object gets over
 Destructor can not be overloaded
 Destructor function is defined in public.

Difference between constructor and destructor

Constructor Destructor
1. Constructor has same name as class name. 1 Name of the destructor is also same as the
2. Constructor can have arguments. name of the class but preceded by ~
3. Constructor is automatically called at the 2. Destructor doesnot have arguments..
time of creation of an object. 3. Destructor is called automatically when the
4. Constructor overloading is possible. scope of the object gets over
4. Destructor can not be overloaded.

XII/Computer Science 39
Example : In the following program constructors, destructor and other member functions are defined
inside class definitions. Since we are using multiple constructor in class so this example also illustrates the
concept of constructor overloading
#include<iostream.h>

class student //specify a class


{
private :
int rollno; //class data members
float marks;
public:
student() //default constructor
{
rollno=0;
marks=0.0;
}
student(int r, int m) //parameterized constructor
{
rollno=r;
marks=m;
}
student(student &t) //copy constructor
{
rollno=t.rollno;
marks=t.marks;
}
void getdata() //member function to get data from user
{
cout<<"Enter Roll Number : ";
cin>>rollno;
cout<<"Enter Marks : ";
cin>>marks;
}
void showdata() // member function to show data
{
cout<<"\nRoll number: "<<rollno<<"\nMarks: "<<marks;
}
~student() //destructor
{}
};

int main()
{
student st1; //defalut constructor invoked
student st2(5,78); //parmeterized constructor invoked
student st3(st2); //copy constructor invoked
st1.showdata(); //display data members of object st1
st2.showdata(); //display data members of object st2
st3.showdata(); //display data members of object st3
return 0;
}

XII/Computer Science 40
HOME ASSIGNMENT – 3
3.1 What is a constructor? Write its characteristics.
3.2 What is a destructor? Write its characteristics.
3.3 How many types of constructors are there? Explain with suitable example.
3.4 In copy constructor, object is passed by reference only. Why?
3.5 Answer the questions (i) and (ii) after going through the following class:
class Seminar
{ int Time;
public:
Seminar() //Function 1
{ Time=30;cout<<”Seminar starts now”<<endl; }
void Lecture() //Function 2
{ cout<<”Lectures in the seminar on”<<endl; }
Seminar(int Duration) //Function 3
{ Time=Duration;cout<<”Seminar starts now”<<endl; }
~Seminar() //Function 4
{ cout<<”Vote of thanks”<<end1; }
};
i) In Object Oriented Programming, what is Function 4 referred as and when does it get
invoked/called?
ii) In Object Oriented Programming, which concept is illustrated by Function 1 and Function
3 together? Write an example illustrating the calls for these functions.
3.6 Answer the questions (i) and (ii) after going through the following program:
class Match
{ int Time;
public:
Match() //Function 1
{ Time=0;
cout<<”Match commences”<<endl;}
void Details() //Function 2
{ cout<<”Inter Section Basketball Match”<<endl; }
Match(int Duration) //Function 3
{ Time=Duration;
cout<<”Another Match begins now”<<endl; }
Match(Match &M) //Function 4
{ Time=M.Duration;
cout<<”Like Previous Match ”<<end1; }
};
i) Which category of constructor - Function 4 belongs to and what is the purpose of using it?
ii) Write statements that would call the member Functions 1 and 3.

CHALLENGING QUESTION

3.7. Define a class named Admission in C++ with following description?


Private members:
admno integer (ranges 10-1500)
name string of 20 characters
cls integer
fees float
Public members:
A constructor which initialized admno with 10, name with “NULL”, cls with 0 & fees with 0
Function getdata() to read the object of Admission type.
Function putdata() to print the details of object of admission type.
Function draw_nos() to generate the admission no. randomly to match with admno and display
the detail of object.

XII/Computer Science 41
LAB EXERCISES – 3
TOPIC : ARRAY OF OBJECTS, CONSTRUCTOR & DESTRUCTOR

LAB 3.1 Define a class Candidate in C++ with the following descriptions:
Private Members:
 RNo of type long
 Name of type string
 Score of type float
 Remarks of type string
 A function AssignRem( ) to assign Remarks as per the Score obtained by a candidate.
Score range and the respective Remarks are shown as follows:
SCORE REMARKS
>=50 Selected
Less than 50 Not
selected
Public Members:
 A function Enter( ) to allow user to enter values for RNo, Name, Score and call function
AssignRem() to assign the Remarks.
 A function DISPLAY( ) to view the content of all the data members.
 A function Return_Score() to return the score
Now write main function to do the following:
i) To create an array of 5 candidates
ii) To obtain values of the data members of all candidates by calling Enter() function
repeatedly
iii) To show details of all the data members by calling Display() function repeatedly
iv) To display the details of the candidates who were selected. (Add appropriate function in
the class)
v) To display the details of a candidate whose name is entered by the user. (Add
appropriate function in the class)

LAB 3.2 Define a class outfit with the following specifications:-


Private Members:
 O_Type of type string
 O_Code of type string
 O_Size of type int
 O_Fabric of type string
 O_Price of type float
 A function int_price() which calculates and assigns value of O_Price as follows:
For the value of O_Fabric=”DENIM”:
O_Type O_Price
TROUSER 1500
JACKET 2500
For O_Fabric other than “DENIM” the above price gets reduced by 25%.
Public Members:
 Constructor to assign initial values of O_Code,O_Type and O_Fabric with the word
“NOT INITIALISED” and O_Size and O_Price with 0.
 A function Input() to input the values of O_Code,O_Type,O_Size and O_Fabric and
invoke the function int_price().
 A function Display() to Display the contents of all data members.
Now write main function() to do the following:
i) To create an array of 5 objects of class Outfit
ii) To enter the values in all the data members of the objects
iii) To display the list of only those objects whose fabric is “DENIM”
iv) To display the details of all the objects

XII/Computer Science 42
TOPIC : INHERITANCE
What is Inheritance?
Inheritance is the process by which new classes called derived classes are created from existing classes
called base classes. The derived classes have all the features of the base class and the programmer can choose to
add new features specific to the newly created derived class.

More Examples:
For example, a programmer can create a base class named fruit and define derived classes
as mango,orange, banana, etc. Each of these derived classes, (mango, orange, banana, etc.) has all the features of
the base class (fruit) with additional attributes or features specific to these newly created derived
classes. Mango would have its own defined features, orange would have its own defined features, banana would
have its own defined features, etc.
Features or Advantages of Inheritance:
1. Reusability:
Inheritance helps the code to be reused in many situations. The base class is defined and once it is compiled, it need
not be reworked. Using the concept of inheritance, the programmer can create as many derived classes from the
base class as needed while adding specific features to each derived class as needed.
2. Saves Time and Effort:
The above concept of reusability achieved by inheritance saves the programmer time and effort. Since the main code
written can be reused in various situations as needed.
3. Increases Program Structure which results in greater reliability.
General Format for implementing the concept of Inheritance:
class derived_classname: access specifier baseclassname
For example, if the base class is tafs and the derived class is sample it is specified as:

class sample: public tafs

The above makes sample have access to both public and protected variables of base class tafs.
Reminder about public, private and protected access specifiers:
1. If a member or variables defined in a class is private, then they are accessible by members of the same class only
and cannot be accessed from outside the class..
2. Public members and variables are accessible from outside the class. .
XII/Computer Science 43
3. Protected access specifier is a stage between private and public. If a member functions or variables defined in a
class are protected, then they cannot be accessed from outside the class but can be accessed from the derived
class.
Types of Inheritance
There are five different inheritances supported in C++:

(1) Simple / Single – When a class is derived or inherits from a single base class, it is single inheritance.
(2) Multilevel – When a class is derived or inherits from a class which has been derived from another class, it is
multilevel inheritance.
(3) Hierarchical- When several classes are derived or inherit from the same base class, it is Hierarchical
inheritance.
(4) Multiple – When a class is derived or inherits from multiple base classes, it is multiple inheritance.
(5) Hybrid – When two or more types of inheritance are used to derive a class, it is hybrid inheritance.

Modes of Inheritance
Private Inheritance:It is the inheritance facilitated by private visibility mode.In private inheritance ,the protected and
public members of base class become private members of the derived class.
Public Inheritance:It is the inheritance facilitated by public visibility mode.In public inheritance ,the protected
members of base class become protected members of the derived class and public members of the base class
become public members of derived class.
Protected Inheritance:It is the inheritance facilitated by protected visibility mode.In protected inheritance ,the
protected and public members of base class become protected members of the derived class.
Base Class Derived class visibility
Members
Public Private Protected
derivation derivation derivation
Private

Protected
Protected Private Protected
Public
Public Private Protected

XII/Computer Science 44
Containership:When a class contains objects of other class types as its members, it is called containership.It is also
called containment,composition, aggregation.

Execution of base class constructor

Method of inheritace Order of execution


A(); base constructor
class B : public A { }; B(); derived constructor

B();base (first)
class A : public B, public C C();base (second)
A();derived constructor

When both derived and base class contains constructors, the base constructor is executed first and then the
constructor in the derived class is executed. In case of multiple inheritances, the base classes are constructed in the
order in which they appear in the declaration of the derived class.

Overriding of method(function) in inheritance

We may face a problem in multiple inheritance, when a function with the same name appears in more than one base
class. Compiler shows ambiguous error when derived class inherited by these classes uses this function.
We can solve this problem, by defining a named instance within the derived class, using the class resolution operator
with the function.

XII/Computer Science 45
HOME ASSIGNMENT – 4
4.1 What do you understand by the term Inheritance? Explain with suitable example.
4.2 How many types of Inheritance is possible? Explain each of them with suitable examples.
4.3 Answer the questions (i) to (iv) based on the following:
class PUBLISHER
{ char Pub[12]; double Turnover;
protected:
void Register();
public:
PUBLISHER();
void Enter(); void Display();
};
class BRANCH
{ char CITY[20];
protected:
float Employees;
public:
BRANCH();
void Haveit(); void Giveit();
};
class AUTHOR:private BRANCH,public PUBLISHER
{ int Acode;char Aname[20]; float Amount;
public:
AUTHOR();
void Start(); void Show();
};
(i) Write the names of data members, which are accessible from objects belonging to class AUTHOR.
(ii) Write the names of all the member functions which are accessible from objects belonging to class
BRANCH.
(iii) Write the names of all the members which are accessible from member functions of class AUTHOR.
(iv) How many bytes will be required by an object belonging to class AUTHOR?
4.4 Answer the questions (i) to (iv) based on the following: class
CUSTOMER
{ int Cust_no; char Cust_Name[20];
protected:
void Register();
public:
CUSTOMER();
void Status();
};
class SALESMAN
{ int Salesman_no; char Salesman_Name[20];
protected:
float Salary;
public:
SALESMAN();
void Enter(); void Show();
};
class SHOP : private CUSTOMER , public SALESMAN
{ char Voucher_No[10]; char Sales_Date[8];
public:
SHOP();
void Sales_Entry();void Sales_Detail();
};
(i) Write the names of data members which are accessible from objects belonging to class CUSTOMER.
(ii) Write the names of all the member functions which are accessible from objects belonging to class
SALESMAN.
(iii) Write the names of all the members which are accessible from member functions of class SHOP.
(v) How many bytes will be required by an object belonging to class SHOP?

XII/Computer Science 46
LAB EXERCISES – 4
TOPIC : INHERITANCE
LAB 4.1 Imagine a publishing company that markets both books and audio-cassette versions of its
works. Create a class publication that stores the title (a string) and price (type float) of a
publication. From this class, derive two class: book, which adds a page count (type int) and
tape, which adds a playing time in minutes (type float). Each of these three classes should
have a getdata() function to get its data from the user at the keyboard, and a putdata()
function to display its data.
Write a main() program to test the book and tape classes by creating instances of them,
asking the user to fill in their data with getdata(), and then displaying the data with
putdata().

LAB 4.2 (i) Define a class STUDENT with the following specifications:-
Private Members:
 Name of type string
 RollNo of type unsigned int
Protected Members:
 Class of type unsigned int
Public Members:
 Constructor to assign initial values of Name with “Not Assigned”, RollNo & Class with 0.
 A function Input() to input the values all data members
 A function Display() to Display the contents of all data members.

(ii) Define another class TEST which is publicly derived from class STUDENT with the
following specifications:-
Private Members:
 English , Maths, Physics , Chemistry , ComputerScience of type float
 A function Calculate_Total() to calculate TotalMarks
Protected Members:
 TotalMarks of type float
Public Members:
 Constructor to assign initial values of all data members with 0.
 A function getData() to input the values all data members & call Calculate_Total()
 A function displayData() to display the contents of all data members.

(iii) Define one more class RESULT which is publicly derived from class TEST with the
following specifications:-
Private Members:
 Percentage of type float
 Grade of type string
Public Members:
 Constructor to assign initial values of percentage with 0 and grade with ‘E’
 A function calcPercentage()
 A function calcGrade() according to the following criteria:
%age of Marks Grade
>= 90 A
>= 75 and <90 B
>= 60 and <75 C
>= 40 and <60 D
< 40 E
 A function displayResult() to display the values of percentage and grade
Now, write the main function to :
 Create an object of class RESULT
 To obtain all the values required to display the result of a student
 Display the result with all the details

XII/Computer Science 47
DATA FILE HANDLING IN C++
Input-Output
Input – Output is a process of transfer of data from one computer device to another or from one part of the
computer to another.
IO in C++ is done through stream classes, which are having the following inheritance hierarchy:

We can use the ifstream, ofstream and fstream classes to perform file IO. (cin is an object of class istream and
cout is an object of class ostream.)
File IO means transfer of data from secondary memory (hard disk) to main memory or vice-versa. A schematic
showing the flow of data and classes involved is as follows:

Note: The arrows indicate the flow of data.

Console-program-file interaction. A program typically involves either or both of the following kinds of data
communication:
1. Data transfer between the console unit(keyboard, monitor) & the program.
2. Data transfer between the program and a disk file.

EXTERNAL MEMORY
DATA FILES

Write data Read data


(to files) (from files)
Program-file
interaction
INTERNAL MEMORY

PROGRAM + DATA

Cout<< Console-
Cin>> CONSOLE UNIT (put data program
(get data to monitor) interaction
from key- MONITOR
board)

KEYBOARD

Need for data files. Many real life problems handle large volumes of data and, in such situations we need to use
devices such as floppy disk or hard disk to store the data. The data is stored in these devices using the concept of
files. A file is a collection of related data stored in a particular area on the disk. Programs can be designed to perform
the read and write operations on these files.

XII/Computer Science 48
Types of data files. Data files can be classified into two basic types :
1. Text Files. When data is stored in the form of readable and printable characters(ASCII Format) then the file is
known as a text file. In this format each character occupies 1 byte. For example the word “AMIT” will occupy 4
bytes , as it consists of 4 characters. Similarly the number 32455 will occupy 5 bytes. These files can be created or
viewed through text editor or a program. For instance, the program files (.cpp) created by an editor are stored as
text files.
2. Binary Files. If a file contains data in binary code (machine language format) then the file is known as a
binary file. This means that the values are stored in the disk file in the same format in which they are stored in the
internal memory. An int takes two bytes to store its value in the binary form, irrespective of its size. For example
32455 will take two bytes in binary form. The binary format is more accurate for storing the numbers as they are
stored in the exact internal representation. There are no conversions while saving the data and therefore saving is
much faster. Unlike text files they cannot be created or viewed through text editor. They can only be created or
viewed through programs. For example, the executable files generated by a compiler are stored as binary files.

Note. 1. The data on which the user operates is always in ASCII format.
2. The data on which the computer operates(internally) is always in Binary format
3. When you use statements like cin>>age; then user gives the data in ASCII format but the operator >>
converts it to binary format and stores it in the variable age.
4. Similarly when you use the statement like cout<<age; then the operator << takes binary data (stored in
age variable) and converts it to ASCII format.

File Access. In programming terminology, using the file for reading or writing is often called accessing the file. There
are two ways of accessing the file in C++ :
1.Sequential Access. In this you access the records of the file sequentially. That means you cannot read a record
from the file, unless you have read all the records that exist prior to this record. For example, to read the sixth record
from the file, you will have to first read initial five records of the file then only you will be able to read the sixth
record.
2.Random Access. In this you can access the records in any order. For example you can read the sixth record first
and then read the third record, then tenth record and then the first record.

Operating upon files. The following activities need to be performed for operating upon files :
1) Opening the file 2) Writing in the file 3) Reading from the file4) Closing the file.

Classes and Libraries for file handling. As you know C++ is object oriented programming language and all the
operations are performed through member functions of the classes. So you have to have classes defined for
performing the above listed file operations. Now question arises, do we have to write our own classes for these
operations? The answer is no. C++ provides various libraries which contain all required classes in them. The only
thing which you have to do is to include these libraries in your program. When you include these libraries in your
program, all the classes defind in them become accessible to you. Now you have to simply create the objects and
make use of member functions.
Header File. All those classes that are required to deal with files in C++ program have been declared in a file called
fstream.h. Therefore, you must include this file in any program that uses files. Note that all fstream.h classes are
derived from iostream.h classes. So when you include fstream.h in your program, there is no need to include
iostream.h in the program.
Classes. There are mainly three classes, using which you operate upon files :
1. ifstream class. Often we deal with the files that would be only used for input operations i.e. we would only
read the data from them. Such files are called input files. All those functions that are required to operate
upon input files are defined in ifstream class. Some of the important functions of this class are open(),
close(), eof(), get(), getline(), read(), seekg() and tellg().
2. ofstream class. Often we would require files, which would we exclusively, utilized, for writing data in them
i.e. for output operations. Such files are called output files. All those functions that are required to operate
upon output files are defined in ofstream class. Some of the important functions of this class are open(),
close(), put(), seekp(), tellp() and write().
3. fstream class. This class provides support for simultaneous input and output operations i.e. we will read the
data from the files and also write the data in them. This class contains all the functions of ifstream and
ofstream classes.

XII/Computer Science 49
Opening a file. Be it any file , text or data , if you wish to perform read or write operation on it, you have to open it
first. For opening a file we must create an object (also called file stream) using any one of the classes ifstream,
ofstream and fstream and then link it to the filename. The class to be used depends upon the purpose, whether we
want to read data from the file or write data to it. A file can be opened in two ways :
1. Using the constructor function of the class. We know that a constructor is used to initialize an object while it
is being created. Here a filename is used to initialize the file stream object. Thus the syntax for opening the
file would be as follows :
Class_name object_name(“file_name”);
Here the class_name will either be ifstream, ofstream or fstream. If you wish to open the file for reading, the
class_name would be ifstream. If you wish to open the file for writing then the class_name would be ofstream
and if you want to open the the file, both, for reading and writing then the class name would be fstream.
Object_name is the name of the object you would like to create. Note that after creating the object, file would
be reffered with this name for all practical puposes.

For example, the following statement opens a file named “tafs” for output:
Ofstream outfile(“tafs”); // output only
This creates outfile as an ofstream object that will mange the output operations. This object can be any valid
C++ name such as ofile, myfile or yourfile. This statement also opens the file tafs and attaches it to the object
outfile.
Similarly, the following statement declares infile as an ifstream object and attaches it to the file data for
reading (input):
Ifstream infile(“data”); // input only

2. Opening the file using open() function. In C++ , file can also be opened explicitly, using the function open(),
instead of a constructor. Basically this is a two step process. In the first step, you create the object and in the
second step, you access member function, named open() through the object. Generel syntax is :
Class_name object_name;
Object_name.open(“file_name”);
Example :
Ofstream outfile; // create object for output
Outfile.open(“tafs”); //connect object to tafs

Caution: When a file is opened for writing only, a new file is created if there is no file of that name. If a file by
that name exists already, then its contents are deleted and the file is presented as a clean file.

File opening modes. To open an existing file for updating it without losing its original content, we have to use file
modes. A file mode specifies the purpose for which a file is opened.
S.No File Mode Meaning
.
1. ios::in Open file for reading only
2. ios::out Open file for writing only. Delete contents of the file if it exists.
3. ios::app Append(add) data to end of file.
4. ios::ate Go to end of file on opening. It permits us to add or to modify the
existing data anywhere in the file.
5. Ios::binary Binary file
6. Ios::nocreate Open fails if the file does not exist
7. Ios::noreplace Open fails if the file already exists
8. Ios::trunc Delete contents of the file if it exists.

INPUT AND OUTPUT OPERATION

put() and get() function


the function put() writes a single character to the associated stream. Similarly, the function get() reads a single
character form the associated stream.
example :
file.get(ch);
file.put(ch);

XII/Computer Science 50
write() and read() function (
write() and read() functions write and read blocks of binary data.
example:
file.read((char *)&obj, sizeof(obj));
file.write((char *)&obj, sizeof(obj));

By default, C++ opens the files in text mode. In the tables below we will see the various steps and operations
that can (or must) be performed to use files in C++:
1)Creating or opening a file

 For writing data


Text Files Binary Files
ofstream out (“myfile.txt”); ofstream out (“myfile.txt”,ios::binary);
or or
ofstream out; ofstream out;
out.open(“myfile.txt”); out.open(“myfile.txt”, ios::binary);

 For Appending (adding text at the end of the existing file)


Binary Files
Text Files
ofstream out
ofstream
(“myfile.txt”,ios::app|ios::binary);
out(“myfile.txt”,ios::app);
or
or
ofstream out;
ofstream out;
out.open(“myfile.txt”, ios::app |
out.open(“myfile.txt”,
ios::binary);
ios::app);

 For reading data


Text Files Binary Files
ifstream in (“myfile.txt”); ifstream in (“myfile.txt”, ios::binary);
or or
ifstream in ; ifstream in ;
in.open(“myfile.txt”); in.open(“myfile.txt”, ios::binary);

2) Closing Files (after reading or writing)

ofstream object Ifstream object


“out” “in”
out.close(); in.close();

3) Reading / Writing Data to and from files

Data Functions for reading file Function for writing into file
char get(); put();
1 word >> (extraction operator) << (insertion operator)
>=1 word getline(); << (insertion operator)
Objects read() write()

XII/Computer Science 51
Binary data Same as above Same as above

Operation function Description

Checking end of eof() Used to check eof during


file. the reading of file
Random access In case of binary files random access
seekg()
(only for is performed using these functions.
binary files). seekp() They either give or set the position
of get and put pointers on the
tellg()
particular location
tellp()

FILE POINTERS AND THEIR MANIPULATION


All i/o streams objects have, at least, one internal stream pointer:
ifstream, like istream, has a pointer known as the get pointer that points to the element to be read in the next
input operation.
ofstream, like ostream, has a pointer known as the put pointer that points to the location where the next
element has to be written.
Finally, fstream, inherits both, the get and the put pointers, from iostream (which is itself derived from both
istream and ostream).
These internal stream pointers that point to the reading or writing locations within a stream can be manipulated
using the following member functions:

seekg() moves get pointer(input) to a specified location

seekp() moves put pointer (output) to a specified location

tellg() gives the current position of the get pointer

tellp() gives the current position of the put pointer

The other prototype for these functions is:


seekg(offset, refposition );
seekp(offset, refposition );
The parameter offset represents the number of bytes the file pointer is to be moved from the location specified by
the parameter refposition. The refposition takes one of the following three constants defined in the ios class.
ios::beg start of the file
ios::cur current position of the pointer
ios::end end of the file
example: file.seekg(-10, ios::cur);

XII/Computer Science 52
IMPORTANT PROGRAMS (TEXT FILES)
Program to write only one record in a text
file Program to write many records in a text file
#include<fstream.h> #include<fstream.h>
void main() void main()
{ ofstream myfile; { ofstream myfile("A.txt", ios::app);
//creating an object for output file int rno;
myfile.open("A.txt", ios::app); char name[20];
//linking file with the object char ans = 'y';
int rno; do
//memory variable to store roll number { cout<<"Enter Roll Number : ";
char name[20]; cin>>rno;
//memory variable to store name
cout<<"Enter Name : ";
//Asking the user to enter Roll No & name
cin>>name;
cout<<"Enter Roll Number : ";
myfile<<rno;
cin>>rno;
myfile<<name<<"\n";
cout<<"Enter Name : ";
cout<<"Do yoy want to enter
cin>>name; more records ? : ";
//Now writing roll no. & name in the file cin>>ans;
myfile<<rno; }while (ans == 'y');
myfile<<name; myfile.close();
myfile.close(); //closing the file }
} Program to read all records from a text file &
display them on screen
Program to write 5 records in a text file #include<fstream.h>
#include<fstream.h> void main()
void main() { int rno;
{ ofstream myfile; char name[20];
//creating an object for output file
ifstream datafile;
myfile.open("A.txt", ios::app); //linking //creating an object for input file
file with the object
datafile.open("A.txt");
int rno; //linking file with the object
//memory variable to store roll number
while(!datafile.eof())
char name[20];
//creating a loop which will run until end-of-file
//memory variable to store name
{ datafile>>rno;
int k = 0;
//reading data & storing in memory variable
//Variable to count number of records
cout<<rno<<"\t";
while (k < 5 )
//displaying data on screen from the memory variable
{
datafile>>name;
//Asking the user to enter Roll No & name
cout<<name<<"\n";
cout<<"Enter Roll Number : ";
}
cin>>rno;
datafile.close();
cout<<"Enter Name : ";
}
cin>>name;
//Now writing roll no. & name in the file Program to read from text file and display it
myfile<<rno; #include<fstream.h>
myfile<<name<<”\n”; #include<conio.h>
k++; //increment K void main()
} {ifstream fin; fin.open("out.txt"); char ch; while(!
myfile.close(); fin.eof())
//closing the file { fin.get(ch);
cout<<ch;
}
}

XII/Computer Science 53
fin.close(); getch(); ifstream fin;
} fin.open(out.txt);
Program to count number of characters ofstream fout;
#include<fstream.h> fout.open("sample.txt");
#include<conio.h> char ch;
void main() while(!fin.eof())
{ {
ifstream fin; fin.open("out.txt"); clrscr(); fin.get(ch);
char ch; int count=0; fout<<ch;
while(!fin.eof()) }
{ fin.close();
fin.get(ch); }
count++;
} Function to count the number of alphabets
cout<<"Number of characters in file is "<<count; present in a text file “NOTES.TXT”.
fin.close(); getch(); void CountAlphabet()
} {
ifstream FIL(“NOTES.TXT”);
Program to count number of words int CALPHA=0;
#include<fstream.h> char CH=FIL.get();
#include<conio.h> while (!FIL.eof())
void main() {
{ if (isalpha(CH)) CALPHA++;
ifstream fin; CH=FIL.get();
fin.open("out.txt"); }
char word[30]; int count=0; cout<<”No. of Alphabets:”<<CALPHA<<endl;
while(!fin.eof()) FIL.close();
{ }
fin>>word; Function to count the words “to” and “the”
count++; present in a text file “story.txt”.
}
cout<<"Number of words in file is "<<count; void COUNT()
fin.close(); getch(); {
} ifstream Fil(“story.txt”);
char Word[80];
int C = 0;
Program to count number of lines while( !Fil.eof())
#include<fstream.h> {
#include<conio.h> Fil>>Word;
void main() if (strcmp(Word, “to”) == 0 ||
{ strcmp(Word, “the”) == 0)
ifstream fin; C++;
fin.open("out.txt"); }
char str[80]; int count=0; cout<<” Count of –to- and –the- in file :
while(!fin.eof()) “<<C;
{ Fil.close();
fin.getline(str,80); }
count++; Function to count and display the number of
} words starting with alphabet ‘A’ present in a
cout<<"Number of lines in file is "<<count; text file “story.txt”.
fin.close(); getch();
} void wordcount()
{ char word[80];
Program to copy contents of file to another file. int cnt=0;
#include<fstream.h> ifstream f1;
void main() f1.open(“story.txt”);
{ while(!f1.eof())

XII/Computer Science 54
{ f1>>word; {
if(word[0]=’A’) ifstream FIL(“STORY.TXT”);
cnt++; int LINES=0;
} char STR[80];
cout<<” number of words starting while (FIL.getline(STR,80))
with A “<<cnt; LINES++;
f1.close(); cout<<”No. of
} Lines:”<<LINES<<endl;
FIL.close();
Function in C++ to count the number of lines }
present in a text file “STORY.TXT”.

void CountLine()

HOME ASSIGNMENT – 5 A
TOPIC : TEXT FILES

5.1. W r i te a function in a C++ to count the number For example, if the content of the file STORY.TXT is
of uppercase alphabets present in a text file There was a monkey in the zoo. The monkey was very
“BOOK.txt” naughty.
5.2. Write a function in a C++ to count the number of Then the output of the program should be 2.
alphabets present in a text file “BOOK.txt” 5.8. Assume a text file “Test.txt” is already created.
5.3. Write a function in a C++ to count the number of Using this file, write a function to create three files
digits present in a text file “BOOK.txt” “LOWER.TXT” which contains all the lowercase
5.4. Write a function in a C++ to count the number of vowels and “UPPER.TXT” which contains all the
white spaces present in a text file “BOOK.txt” uppercase vowels and “DIGIT.TXT” which contains all
5.5. Write a function in a C++ to count the number of digits.
vowels present in a text file “BOOK.txt” 5.9. Create a function FileLowerShow() in c++ which
5.6. Write a function in a C++ to count the average take file name(text files)as a argument and display
word size in a text file “BOOK.txt” its all data into lower case
5.7. Write a function in C++ to print the count of 5.10. Write a function in C++ to count the number of
the word “the” as an independent word in a text lines present in a text file “Story.txt”.
file STORY.TXT.

LAB EXERCISES – 5 A
TOPIC : TEXT FILES

LAB 5.1. Write a program in a C++ to write few lines of text in a text file “Try.txt”and then write different
functions to do the following:
(i) to count the number of consonants present in the file.
(ii) to count the number of uppercase vowels present in the file.
(iii) to count the number of words
(iv) to count number of lines.
(v) to print the count of the word “the” as an independent word in the file.
CHALLENGING QUESTION
LAB 5.2 Write a program in a C++ to write few lines of text in a text file “Number.txt”including numbers
and then write different functions to do the following:
(i) To count the number of digits present in the file
(ii) to display the sum & product of digits present
(iii) to find the largest digit present in a text file “Marks.txt”

XII/Computer Science 55
(iv) 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.

XII/Computer Science 56
BASIC OPERATIONS ON BINARY FILES
The following class will be used in all the void display()
programs explaining the basic operations on files: {
class student student obj;
{ ifstream fp1;
int admno; fp1.open("student.dat",ios::binary);
char name[20]; while(fp1.read((char*)&obj,sizeof(obj)))
public: {
void getdata() obj.showdata();
{ }
cout<<"\nEnter The admission no. "; fp.close();
cin>>admno; }
cout<<"\n\nEnter The Name of The Student ";
gets(name); Function to search and display from binary file
}
void showdata() void search (int n)
{ {
cout<<"\nAdmission no. : "<<admno; cout<<"\ student obj;
nStudent Name : "; puts(name); ifstream fp1;
} fp1.open("student.dat",ios::binary);
int retadmno() int found = 0;
{ while(fp1.read((char*)&obj,sizeof(obj)))
return admno; {
if(obj.retadmno()==n)
{ obj.showdata();
Function to write or add an object in a binary file found = 1;
}
void write_data() }
{ fp1.close();
student obj; if (found==0)
ofstream fp2; cout<<”Record is not present in file”;
fp2.open("student.dat",ios::binary|ios::app);
obj.getdata(); }
fp2.write((char*)&obj,sizeof(obj));
fp2.close(); Function to search and delete a record from
} binary file
void Delete_Record(int madmno)
Function to write or add many objects in a binary {
file ifstream FIL1;
FIL1.open("STUDENT.DAT",ios::binary);
void write_manydata() ofstream FIL2;
{ FIL2.open("TEMP.DAT",ios::binary);
student obj;
student S;
ofstream fp2;
while(FIL1.read((char*)&S,sizeof(S)))
fp2.open("student.dat",ios::binary|ios::app);
char CH; {
do if (madmno != S.retadmno())
{
obj.getdata(); FIL2.write((char*)&S,sizeof(S));
fp2.write((char*)&obj,sizeof(obj)); }
cout<<”More(Y/N)?”; FIL1.close();
cin>>CH; FIL2.close();
} while(CH == ’Y’); remove("STUDENT.DAT");
fp2.close(); rename("TEMP.DAT","STUDENT.DAT");
} }
Function to display all the records of a file Function to search and modify a record from

XII/Computer Science 57
binary file }
Function in C++ to add new objects at the bottom of
void MODIFY (int n) a binary file “STUDENT.DAT”, assuming the binary
{ file is containing the objects of the following class.
student obj;
fstream fp;
fp.open("student.dat",ios::binary|ios:in|ios::out);
int found = 0; class STUD
while(fp.read((char*)&obj,sizeof(obj))) {
{ int Rno;
if(obj.retadmno()==n) char Name[20];
{ public:
obj.showdata(); //to display the current data void Enter(){cin>>Rno;gets(Name);}
obj.getdata(); // to obtain new data void Display(){cout<<Rno<<Name<<endl;}
int s = sizeof(obj); //to get the size of object in bytes };
fp.seekp(-s, ios::cur); //to move the pointer to the beginning of the
current record void Addnew()
fp.write((char*)&obj,sizeof(obj)); {
//to write the modified data fstream FIL;
found++; FIL.open(“STUDENT.DAT”,ios::binary|ios::app);
//to indicate that the record has been found STUD S;
} char CH;
} do
fp1.close(); {
if (found==0) S.Enter();
cout<<”Record is not present in file”; FIL.write((char*)&S,sizeof(S));
} cout<<”More(Y/N)?”;
Function to search for a BookNo from a binary file cin>>CH;
“BOOK.DAT”, assuming the binary file is containing }
the objects of the following class: while(CH==’Y’);
class BOOK FIL.close();
{ }
int Bno; Given a binary file SPORTS.DAT, containing records
char Title[20]; of the following structure type :
public: struct Sports
int RBno(){return Bno;} {
void Enter(){cin>>Bno;gets(Title);} char Event[20];
void Display(){cout<<Bno<<Title<<endl;} char Participant[10][30];
}; };
void BookSearch() Write a function in C++ that would read contents
{ from the file SPORTS.DAT and creates a file named
fstream FIL; ATHLETIC.DAT copying only those records from
FIL.open(“BOOK.DAT”,ios::binary|ios::in); SPORTS.DAT where the event name is “Athletics”.
BOOK B; void SP2AT()
int bn,Found=0; { fstream IS,OA;
cout<<”Enter Book Num to search…”; Sports S;
cin>>bn; IS.open(“SPORTS.DAT”,ios::binary|ios::in);
while (FIL.read((char*)&S,sizeof(S))) OA.open(“ATHLETIC.DAT”,ios::binary|ios::out);
if (B.RBno()==bn) while(IS.read((char*) &S,sizeof(S)))
{ {
B.Display(); if(strcmp(S.Event,”Athletics”)==0)
Found++; OA.write((char *)&S,sizeof(S));
} }
if (Found==0) cout<<”Sorry! Book not IS.close();
found!!!”<<endl; OA.close();
FIL.close(); }

XII/Computer Science 58
IMPORTANT QUESTIONS

Q. What is the difference between a binary file and a text file?


Ans. When a file is opened in text mode, various character translation may take place, such as the conversion of
carriage return & linefeed sequences into newlines. Binary files are faster to read & write than text files.

Q. What is the difference between app mode and ate mode in file operation?
Ans:In app mode, the record pointer will always be at end of file when we open a file and the records will be always
added at end. In ate mode, though the record pointer will always at end of file when we open a file, the record
pointer can be changed to any position and record can be added at any position also. ate mode is required when we
modify a record.

Q. Observe the program segment given below carefully and fill the blanks marked as Statement 1 and
Statement 2 using seekg() and tellg() functions for performing the required task.

#include <fstream.h>
class Employee
{
int Eno;char Ename[20];
public:
//Function to count the total number of records
int Countrec();
};
int Item::Countrec()
{
fstream File;
File.open(“EMP.DAT”,ios::binary|ios::in);
______________________ //Statement 1

int Bytes = ______________________ //Statement 2

int Count = Bytes / sizeof(Item);


File.close();
return Count;
}

Answer:
File.seekg(0,ios::end); //Statement 1
File.tellg(); //Statement 2
Q. Observe the program segment given below carefully and fill the blanks marked as Statement 1
and Statement 2 using seekp() and seekg() functions for performing the required task.
#include <fstream.h>
class Item
{ int Ino;
char Item[20];
public:
//Function to search and display the content from a particular
//record number
void Search(int );
//Function to modify the content of a particular record number
void Modify(int);
};
void Item::Search(int RecNo)
{ fstream File;
File.open(“STOCK.DAT”,ios::binary|ios::in);
______________________ //Statement 1
File.read((char*)this,sizeof(Item));
cout<<Ino<<”==>”<<Item<<endl;
File.close();
}

void Item::Modify(int RecNo)


{
fstream File;
File.open(“STOCK.DAT”,ios::binary|ios::in|ios::out);

XII/Computer Science 59
cout>>Ino;cin.getline(Item,20);
______________________ //Statement 2
File.write((char*)this,sizeof(Item));
File.close();
}

Answer:
File.seekg(RecNo*sizeof(Item)); //Statement 1
File.seekp(RecNo*sizeof(Item)); //Statement 2
Q. Observe the program segment given below carefully, and answer the question that follows:
class PracFile
{
intPracno;
char PracName[20];
int TimeTaken;
int Marks;
public:
void EnterPrac( ); // function to enter PracFile details
void ShowPrac( ): // function to display PracFile details
// function to return TimeTaken
int RTime() {return TimeTaken;}
// function to assign Marks
void Assignmarks (int M)
{ Marks = M;}
};
void AllocateMarks( )
{
fstreamFile;
File.open(“MARKS.DAT”,ios::binary|ios::in|ios::out);
PracFile P;
int Record = 0;
while (File.read(( char*) &P, sizeof(P)))
{
if(P.RTime()>50)
P.Assignmarks(0)
else
P.Assignmarks(10)
______________ //statement 1
______________ //statement 2
Record + + ;
}
File.close();
}
If the function AllocateMarks () is supposed to Allocate Marks for the records in the file MARKS.DAT based on their
value of the member TimeTaken. Write C++ statements for the statement 1 and statement 2, where, statement 1 is
required to position the file write pointer to an appropriate place in the file and statement 2 is to perform the write
operation with the modified record.
Answer:
Statement 1:
File.seekg(-1*sizeof(L),ios::cur);OR File.seekg(Rec*sizeof(L)); OR File.seekp(-1*sizeof(L),ios::cur);OR File.seekp(Rec*sizeof(L));
Statement 2:
File.write((char *) &L,sizeof(L));

XII/Computer Science 60
HOME ASSIGNMENT – 5 B
TOPIC : BINARY FILES
5B.1Assuming the class EMPLOYEE given below, write functions in C++ to perform following:
(i) Write the objects of EMPLOYEE to a binary file.
(ii) Read the objects of EMPLOYEE from binary file and display them on screen.
class EMPLOYEE
{ int ENO;
char ENAME[10];
public :
void GETIT()
{ cin >> ENO; gets (ENAME); }
void SHOWIT()
{ cout <<ENO << ENAME <<endl; }
};
5B.2Assuming the class Computer as follows :
class computer
{ char chiptype[10];
int speed;
public:
void getdetails()
{ gets(chiptype);
cin>>speed;
}
void showdetails()
{ cout<<“Chip”<<chiptype<<“ Speed= “<<speed; }
};
Write a function readfile( ) to read all the records present in an already existing binary file
SHIP.DAT and display them on the screen, also count the number of records present in the file.
5B.3Given a binary file STUDENT.DAT, containing records of the following class
Student type
class Student
{ char S_Admno[lO]; //Admission number of student
char S_Name[30]; //Name of student
int Percentage; //Marks Percentage of student
public:
void EnterData()
{ gets(S_Admno);
gets(S_Name);
cin>>Percentage;
}
void DisplayData()
{ cout<<setw(12)<<S_Admno;
cout<<setw(32)<<S_Name;
cout<<setw(3)<<Percentage<<endl;
}
int ReturnPercentage()
{return Percentage;}
};
Write a function in C++, that would read contents of file STUDENT.DAT and display the details
of those Students whose Percentage is above 75.

5B.4Observe the program segment given below carefully and fill the blanks marked as Statement 1
and Statement 2 using seekg() and tellg() functions for performing the required task.

#include <fstream.h>
class Employee
{ int Eno;
char Ename[20];
public:
//Function to count the total number of records
int Countrec();
};

XII/Computer Science 61
int Item::Countrec()
{ fstream File;
File.open("EMP.DAT",ios::binary|ios::in);
______________________ //Statement 1
int Bytes =
______________________ //Statement 2
int Count = Bytes / sizeof(Item);
File.close();
return Count;
}

5B.5 Observe the program segment given below carefully and fill the blanks marked as
Statement 1 and Statement 2 using seekp() and seekg() functions for performing the
required task.
#include <fstream.h>
class Item
{ int Ino;
char Item[20];
public:
//Function to search and display the content from a particular
//record number
void Search(int );
//Function to modify the content of a particular record number
void Modify(int);
};
void Item::Search(int RecNo)
{ fstream File;
File.open(“STOCK.DAT”,ios::binary|ios::in);
______________________ //Statement 1
File.read((char*)this,sizeof(Item));
cout<<Ino<<”==>”<<Item<<endl;
File.close();
}
void Item::Modify(int RecNo)
{ fstream File;
File.open(“STOCK.DAT”,ios::binary|ios::in|ios::out);
cout>>Ino;
cin.getline(Item,20);
______________________ //Statement 2
File.write((char*)this,sizeof(Item));
File.close();
}
----------------------------------------------------------------------------------------------------------------

XII/Computer Science 62
LAB EXERCISES – 5 B

TOPIC : FILE HANDLING - BINARY FILES

LAB 5B.1 Define a class Travel in C++ with the following descriptions:
Private Members :
TravelCode of type long
Place of type character array (string)
No_of_travellers of type integer
No_of_buses of type integer
Public Members :
A constructor to assign initial values of TravelCode as 201, Place as “Nainital”,
No_of_travellers as 10, No_of_buses as 1
A function NewTravel() which allows user to enter TravelCode, Place and No_of_travellers.
Also, assign the value of No_of_buses as per the following conditions :
No_of_travellers No_of_buses
Less than 20 1
Equal to or more than 20 and less than 40 2
Equal to 40 or more than 40 3
A function ShowTravel( ) to display the content from all the data members on screen.
A destructor to display “Object is being destroyed…..”.

(a) Write function ADD_ONE_RECORD() to add an object of class Travel in a binary file TRAVEL.DAT
(b) Write function ADD_MANY_RECORD() to add ‘n’ objects of class Travel in a binary file TRAVEL.DAT
(c) Write function ADD_RECORD() to add as many objects as the user wants (using do-while loop)in binary
file TRAVEL.DAT
(d) Write function DISPLAY_ALL_RECORD() to display all the objects of class Travel from TRAVEL.DAT
(e) Write function DISPLAY_ RECORD() to display all the objects from TRAVEL.DAT where more than 2 buses
are required
Also write main function to call & execute above function (Preferably menu driven).

LAB 5B.2 Define a class named Admission in C++ with following description?
Private members:
admno integer (ranges 10-1500)
name string of 20 characters
cls integer
fees float
Public members:
A constructor which initialized admno with 10, name with “NULL”, cls with 0 & fees with 0
Function getdata() to read the object of Admission type.
Function putdata() to print the details of object of admission type.
Function Return_admno() to return admno.
Function Return_Fees() to return fees.
(a) Write function ADD_RECORD() to add as many objects as the user wants (using do-while
loop)in binary file STUDENT.DAT
(b Write function DISPLAY_ RECORD() to display all the objects from STUDENT.DAT where fees is
between 1000 & 3000
(c)Write function DELETE_ONE_RECORD() to search & delete details of the object whose admno is
entered by the user
(d) Write function MODIFY_ONE_RECORD() to search & modify details of the object whose admno
is entered by the user
(e) Write function COPY_ RECORD() to copy all the objects from STUDENT.DAT where fees is less
than 1000 to another file EWS.DAT
Also write main function to call & execute above function (Preferably menu driven).

XII/Computer Science 63
POINTERS
C++ Memory Map - Integers can be added to or subtracted
Once a program is compiled, C++ creates from
four logically distinct regions of memory: pointers using the operators +, -, +=, and
Code Area : Area to hold the compiled -=
program code Each time a pointer is incremented by 1, it
Data Area : Area to hold global variables points to the memory location of the next
Stack Area : Area to hold the return element of its base type.
address of function calls, argument passed If “p” is a character pointer then “p++” will
to the functions, local variables for increment “p” by 1 byte.
functions and the current state of the CPU. If “p” were an integer pointer its value on “p+
Heap : Area from which the memory is +” would be incremented by 2 bytes.
dynamically allocated to the program. Pointers and Arrays
Array name is base address of array
Accessing address of a variable int vals[] = {4, 7, 11};
Computer’s memory is organized as a linear cout << vals; // displays 0x4a00
collection of bytes. Every byte in the computer’s cout << vals[0]; // displays 4
memory has an address. Each variable in Lets takes an example:
program is stored at a unique address. We can int arr[]={4,7,11};
use address operator & to get address of a int *ptr = arr;
variable: What is ptr + 1?
int num = 23; It means (address in ptr) + (1 * size of an int)
cout << &num; // prints address in cout << *(ptr+1); // displays 7
hexadecimal cout << *(ptr+2); // displays 11
POINTER Array Access
A pointer is a variable that holds a Array notation arr[i] is equivalent to the
memory address, usually the location of pointer notation *(arr + i)
another variable in memory. Assume the variable definitions
int arr[]={4,7,11};
int *ptr = arr;
Defining a Pointer Variable
Examples of use of ++ and --
int *iptr;
ptr++; // points at 7
iptr can hold the address of an int
ptr--; // now points at 4
Pointer Variables Assignment:
Character Pointers and Strings
int num = 25;
Initialize to a character string.
int *iptr;
char* a = “Hello”;
iptr = &num;
a is pointer to the memory location where ‘H’ is
Memory layout
stored. Here “a” can be viewed as a character
array of size 6, the only difference being that a
can be reassigned another memory location.
char* a = “Hello”;
To access num using iptr and indirection a gives address of ‘H’
operator * *a gives ‘H’
cout << iptr; // prints 0x4a00 a[0] gives ‘H’
cout << *itptr; // prints 25 a++ gives address of ‘e’
Similary, following declaration shows: *a++ gives ‘e’
char *cptr; Pointers as Function Parameters
float *fptr; A pointer can be a parameter. It works like a
cptr is a pointer to character and fptr is a reference parameter to allow change to
pointer to float value. argument from within function
Pointer Arithmetic Pointers as Function Parameters
Some arithmetic operators can be used with void swap(int *x, int *y)
pointers: {
- Increment and decrement operators ++, -- int temp;

XII/Computer Science 64
temp = *x; To free dynamic array memory
*x = *y; delete [] dptr;
*y = temp;
To free dynamic structure
}
swap(&num1, &num2); delete Student;
Pointers to Constants and Constant Memory Leak
Pointers
If the objects, that are allocated memory
Pointer to a constant: cannot change the
value that is pointed at dynamically, are not deleted using delete, the
Constant pointer: address in pointer cannot memory block remains occupied even at the
change once pointer is initialized
end of the program. Such memory blocks are
Pointers to Structures
We can create pointers to structure variables known as orphaned memory blocks. These
struct Student {int rollno; float fees;}; orphaned memory blocks when increase in
Student stu1; number, bring adverse effect on the system.
Student *stuPtr = &stu1;
(*stuPtr).rollno= 104; This situation is called memory leak
-or- Self Referential Structure
Use the form ptr->member: The self referential structures are structures
stuPtr->rollno = 104;
that include an element that is a pointer to
Static allocation of memory
In the static memory allocation, the amount of another structure of the same type.
memory to be allocated is predicted and struct node
preknown. This memory is allocated during the {
compilation itself. All the declared variables int data;
declared normally, are allocated memory node* next;
statically. }
Dynamic allocation of memory
What is “this” pointer? Give an example to
In the dynamic memory allocation, the amount
illustrate the use of it in C++.
of memory to be allocated is not known. This
memory is allocated during run-time as and
Ans: A special pointer known as this pointer
when required. The memory is dynamically
stores the address of the object that is
allocated using new operator.
currently invoking a member function. The this
Free store
pointer is implicitly passed to the member
Free store is a pool of unallocated heap
functions of a class whenever they are invoked.
memory given to a program that is used by the
(As soon as you define a class, the member
program for dynamic allocation during
functions are created and placed in the memory
execution. space only once. That is, only one copy of
Dynamic Memory Allocation member functions is maintained that is shared
We can allocate storage for a variable while by all the objects of the class. Only space for
program is running by using new operator data members is allocated separately for each
object.When a member function is called, it is
To allocate memory of type integer
automatically passed an implicit(in built)
int *iptr=new int; argument that is a pointer to the object that
To allocate array invoked the function. This pointer is called this.
If an object is invoking a member function,
double *dptr = new double[25];
then an implicit argument is passed to that
To allocate dynamic structure variables or member function that points to (that) object.
objects The programmer also can explicitly specify ‘this’
in the program if he desires.)
Student *sptr = new Student; //Student is
tag name of structure Eg: Example program to demonstrate the
Releasing Dynamic Memory usage of this pointer.

Use delete to free dynamic memory


#include<iostream.h>
delete iptr; #include<conio.h>

XII/Computer Science 65
class Rectangle {
{ float area,len,bre; int a[] = {10,20,30,40},*p;
public: p = a;
void input( )
{ cout<<"\nEnter the length and breadth: "; cout<<"Display using array and pointer....."<<endl;
cin>>this->len>>this->bre; for (int I = 0; I < 4 ; I++)
} cout<<a[I]<<" "<<*(p+I)<<endl;
void calculate( ) }
{ area=len*bre;
//Here Implicit 'this' pointer will be worked. /* O U T P U T
}
void output( ) Display using array and pointer.....
{ 10 10
cout<<"\nThe Area of the Rectangle: "<<this- 20 20
>area; 30 30
} 40 40
};
void main( ) */
{
Rectangle R; EXAMPLE 7.3
clrscr( ); #include<iostream.h>
R.input( ); #include<conio.h>
R.calculate( ); void main()
R.output( ); {
getch(); int a[] = {5,4,3,7,2},*p, *q, I;
} p = a;
q = a;
EXAMPLE 7.1 cout<<"Display before changes are
made"<<endl;
#include<iostream.h> for ( I = 0; I < 5 ; I++)
#include<conio.h> cout<<a[I]<<" "<<*(p+I)<<endl;
void main() for ( I = 0; I < 5 ; I++, p++)
{ { if (*p % 2 == 0)
int a , b, *p, *q; *p = *p**p;
p = &a; else
q = &b; *p = *p**p**p;
*p = 10; }
*q = 20; cout<<"Display after changes are
cout<<"Before swapping....."<<endl; made..."<<endl;
cout<<"a = "<<a<<" b = "<<b<<endl; for ( I = 0; I < 5 ; I++)
cout<<"a = "<<*p<<" b = "<<*q<<endl; cout<<a[I]<<" "<<*(q+I)<<endl;
int t = *p; }
*p = *q; /* O U T P U T
*q=t; Display before changes are made.....
cout<<"After swapping....."<<endl; 5 5
cout<<"a = "<<a<<" b = "<<b<<endl; 4 4
cout<<"a = "<<*p<<" b = "<<*q<<endl; 3 3
} 7 7
2 2
/* O U T P U T Display after changes are made.....
Before swapping..... 125 125
a = 10 b = 20 16 16
a = 10 b = 20 27 27
After swapping..... 343 343
a = 20 b = 10 4 4
a = 20 b = 10 */
*/ EXAMPLE 7.4
#include<iostream.h>
EXAMPLE 7.2 #include<conio.h>
include<iostream.h> #include<ctype.h>
#include<conio.h>
void main() void main()

XII/Computer Science 66
{ for (char *p=a; *p != '\0' ; p++)
char a[] = "AMIT"; { switch(toupper(*p))
char *p; {
p = a; case 'A':
cout<<"Display using array and case 'E':
pointer ....."<<endl; case 'I':
cout<<a<<" "<<p<<" "<<a[0]<<" case 'O':
"<<*p<<endl; case 'U': vowel++;
}
} }
cout<<"No. of vowels are =
/* O U T P U T "<<vowel<<endl;
Display using array and pointer ..... }
AMIT AMIT A A /* O U T P U T
No. of vowels are = 2
*/ No. of vowels are = 2
EXAMPLE 7.5 */
#include<iostream.h>
#include<conio.h> EXAMPLE 7.7
#include<ctype.h> #include<iostream.h>
void main() #include<conio.h>
{ #include<ctype.h>
char a[] = "AMIT"; void main()
char *p; {
p = a; char a[] = "Amit Kumar 12 B";
//to find length of string using array char *p;
int len = 0; p = a;
for (int I = 0; a[I] != '\0' ; I++) cout<<"Display before changes are
len++; made"<<endl;
cout<<"length of string is = "<<len<<endl; cout<<a<<" "<<p<<endl;
//to find length of string using pointer
len = 0; //to change lowercase into uppercase and vice versa
for ( p = a; *p != '\0' ; p++) using array
len++; for (int I = 0; a[I] != '\0' ; I++)
cout<<"length of string is = "<<len<<endl; { if (islower(a[I]))
} a[I] = toupper(a[I]);
/* O U T P U T else if (isupper(a[I]))
length of string is = 4 a[I] = tolower(a[I]);
length of string is = 4 }
*/ cout<<"Display after changes are
EXAMPLE 7.6 made..."<<endl;
#include<iostream.h> cout<<a<<" "<<p<<endl;
#include<conio.h>
#include<ctype.h> //to change lowercase into uppercase and vice versa
void main() using pointer
{ char a[] = "AMIT"; for (p=a; *p != '\0' ; p++)
//to count number of vowels in a string using array {
int vowel = 0; if (islower(*p))
for (int I = 0; a[I] != '\0' ; I++) *p = toupper(*p);
{ switch(toupper(a[I])) else if (isupper(*p))
{ *p = tolower(*p);
case 'A': }
case 'E': cout<<"Display using array and pointer
case 'I': after changes are made....."<<endl;
case 'O': cout<<a<<" "<<p<<endl;
case 'U': vowel++; }
}
} /* O U T P U T
cout<<"No. of vowels are = Display using array and pointer before changes are
"<<vowel<<endl; made.....
// number of vowels in a string using pointer Amit Kumar 12 B Amit Kumar 12 B
vowel = 0;

XII/Computer Science 67
Display using array and pointer after changes are
made..... int length( char *ptr)
aMIT kUMAR 12 b aMIT kUMAR 12 b {
Display using array and pointer after changes are for (int len = 0; *ptr != '\0'; len++, ptr++);
made..... return len;
Amit Kumar 12 B }

*/ void main()
{
char a[30];
char *p;
EXAMPLE 7.8 p = a;
include<iostream.h> cout<<"Enter String : ";
#include<conio.h> gets(p);
#include<ctype.h> //to check whether a string is palindrome (using
//Function to find length of string using pointer array)
int length( char *ptr) int len,I,J;
{ len = length(p); //Pointer as an argument
for (int len = 0; *ptr != '\0'; len++, ptr++); int pal = 1;
return len; for (I = 0,J = len-1; I< len/2 ; I++, J--)
} {
void main() if ( a[I] != a[J])
{ {
char a[] = "AMIT"; pal = 0;
char *p; break;
p = a; }
cout<<"Original string is : "<<p<<endl; }
//to find length of string using pointer if (pal == 1)
int len,I,J; cout<<a<<" is a palindrome.....
len = length(p); //Pointer as an argument (using array) "<<endl;
//to reverse a string using array else
for (I = 0,J = len-1; I< len/2 ; I++, J--) cout<<a<<" is not a palindrome.....
{ (using array)"<<endl;
char temp = a[I];
a[I] = a[J]; //to check whether a string is palindrome (using
a[J]= temp; pointer)
} p = a;
cout<<"Reversed string is : "<<a<<endl; pal = 1;
//to reverse a string using pointer for (I = 0,J = len-1; I< len/2 ; I++, J--)
p = a; {
for (I = 0,J = len-1; I< len/2 ; I++, J--) if ( *(p+I) != *(p+J))
{ {
char temp = *(p+I); pal = 0;
*(p+I) = *(p+J); break;
*(p+J)= temp; }
} }
cout<<"Again the Reversed string is : if (pal == 1)
"<<p<<endl; cout<<p<<" is a palindrome.....
} (using pointer) "<<endl;
else
/* O U T P U T cout<<p<<" is not a palindrome.....
Original string is : AMIT (using pointer) "<<endl;
Reversed string is : TIMA
Again the Reversed string is : AMIT }
*/
/* O U T P U T
Enter String : AMITABH
EXAMPLE 7.9 AMITABH is not a palindrome..... (using array)
#include<iostream.h> AMITABH is not a palindrome.....(using pointer)
#include<stdio.h>
Enter String : NITIN
//Function to find length of string using pointer NITIN is a palindrome.....(using array)

XII/Computer Science 68
NITIN is a palindrome.....(using pointer) EXAMPLE 7.12
*/ #include<iostream.h>
#include<stdio.h>
struct student
EXAMPLE 7.10 { int rno;
/EXAMPLE - ARRAY OF POINTERS char name[30];
#include<iostream.h> float marks;
#include<stdio.h> };
int length( char *ptr) void main()
{ for (int len = 0; *ptr != '\0'; len++, ptr++); { student A;
return len; cout<<"Enter Roll Number : ";
} cin>>A.rno;
void main() cout<<"Enter name : ";
{ char *p[] = { "AMIT", gets(A.name);
"SUMITA", cout<<"Enter marks : ";
"VIJAY", cin>>A.marks;
"GOPALDAS"}; cout<<A.rno<<" "<<A.name<<"
cout<<"Strings in original order : "<<endl; "<<A.marks<<endl;
for (int I = 0; I < 4; I++) //Same thing can be done using pointers
cout<<p[I]<<endl; student *p;
cout<<"Strings in reverse order : "<<endl; p = &A;
for (I = 3; I >= 0; I--) cout<<p->rno<<" "<<p->name<<" "<<p-
cout<<p[I]<<endl; >marks<<endl;
cout<<"Length of each string : "<<endl; }
for ( I = 0; I < 4; I++) /* O U T P U T
cout<<"Length of "<<p[I]<<" is = Enter Roll Number : 1
"<<length(p[I])<<endl; Enter name : amit
} Enter marks : 50
/* O U T P U T 1 amit 50
Strings in original order : 1 amit 50
AMIT */
SUMITA EXAMPLE 7.13
VIJAY #include<iostream.h>
GOPALDAS #include<stdio.h>
Strings in reverse order : void main()
GOPALDAS { student A,B;
VIJAY student *p, *q;
SUMITA p = &A;
AMIT q = &B;
Length of each string : cout<<"Enter Roll Number : ";
Length of AMIT is = 4 cin>>p->rno;
Length of SUMITA is = 6 cout<<"Enter name : ";
Length of VIJAY is = 5 gets(p->name);
Length of GOPALDAS is = 8 cout<<"Enter marks : ";
*/ cin>>p->marks;
EXAMPLE 7.11 cout<<p->rno<<" "<<p->name<<" "<<p-
#include<iostream.h> >marks<<endl;
void main() cout<<"Enter Roll Number : ";
{ char a[3][10] = {"Amit", "Sumit", "Tohit"}; cin>>q->rno;
for ( int I=0 ; I < 3 ; I++) cout<<"Enter name : ";
if(a[I][0] == 'S') gets(q->name);
cout<<a[I]<<endl; cout<<"Enter marks : ";
//using pointers cin>>q->marks;
char *b[3] = {"Amit", "Sumit", "Tohit"}; cout<<q->rno<<" "<<q->name<<" "<<q-
for ( I = 0 ; I < 3 ; I++) >marks<<endl;
if (*b[I] == 'S') cout<<"Details of student who scored higher
cout<<b[I]<<endl; marks : ";
} if (p->marks > q->marks)
/************************* cout<<p->rno<<" "<<p->name<<" "<<p-
Sumit >marks<<endl;
Sumit else
**************************/

XII/Computer Science 69
cout<<q->rno<<" "<<q->name<<" "<<q- }
>marks<<endl; /* O U T P U T
}
/* O U T P U T Enter first value :20
Enter Roll Number : 1 Enter second value :10
Enter name : amit First is greater
Enter marks : 55
1 amit 55 */
Enter Roll Number : 2
Enter name : sumit EXAMPLE 7.16
Enter marks : 35 //Dynamic allocation of memory for an array
2 sumit 35 //To find maximum value from an array of n
Details of student who has scored higher marks : elements
1 amit 55
*/ #include<iostream.h>
} void main()
EXAMPLE 7.14 {
// P O I N T E R S & S T R U C T U R E S int *p,n,i;
#include<iostream.h> cout<<"Enter the size of the array : ";
struct Package cin>>n;
{ int Length, Breadth, Height;}; p = new int[n]; //Dynamic allocation
void main() cout<<"Enter values :";
{ Package P1; for (i = 0 ; i < n; i++)
P1.Length = 10; cin>>*(p+i);
P1.Breadth = 20; cout<<"Values entered are :";
P1.Height = 30; for (i = 0 ; i < n; i++)
cout<<*(p+i)<<endl;
cout<<P1.Length<<P1.Breadth<<P1.Height<<endl; int max = -32768;
//Using pointers for (i = 0 ; i < n; i++)
Package *P2; {
P2 = &P1; if ( *(p+i) > max)
cout<<P2->Length<<P2->Breadth<<P2- max = *(p+i);
>Height<<endl; }
P2->Length = 40; cout<<"Maximum value is = "<<max<<endl;
P2->Breadth = 50; delete[] p; //Deallocation of memory
P2->Height = 80; }
cout<<P2->Length<<P2->Breadth<<P2-
>Height<<endl; /* O U T P U T
} Enter the size of the array : 4
/*** O U T P U T ************ Enter values :45
102030 89
102030 12
405080 50
*************************/ Values entered are :45
EXAMPLE 7.15 89
//Dynamic allocation of memory 12
#include<iostream.h> 50
void main() Maximum value is = 89
{ int *p, *q;; */
p = new int; //Dynamic allocation
q = new int; //Dynamic allocation Important Note :
cout<<"Enter first value :"; variables and arrays which are created using
cin>>*p; new must be destroyed using delete
cout<<"Enter second value :";
cin>>*q;
if (*p > *q)
cout<<"First is greater";
else if (*p < *q)
cout<<"Second is greater";
else EXAMPLE 7.17
cout<<"Both are equal"; //Dynamic allocation of memory for structures
delete p,q; //Deallocation of memory

XII/Computer Science 70
//Program to enter and display the details of
two //students EXAMPLE 7.18
//Dynamic array of structures
#include<iostream.h> #include<iostream.h>
#include<stdio.h> #include<stdio.h>
struct GAME
struct student { long Pno; //Player Number
{ int rno; char Pname[20];
char name[30]; float Points;
float marks; };
};
void main()
void main() {
{ student *p, *q; int n;
p = new student; //Dynamic allocationof cout<<"Enter value of n : ";
memory cin>>n;
q = new student;//Dynamic allocation of GAME *p;
memory p = new GAME[n]; //Dynamic allocation of
cout<<"Enter Roll Number : "; memory
cin>>p->rno; for ( int i = 0; i < n; i++)
cout<<"Enter name : "; {
gets(p->name); cout<<"Enter Player Number : ";
cout<<"Enter marks : "; cin>>(p+i)->Pno;
cin>>p->marks; cout<<"Enter name : ";
cout<<p->rno<<""<<p->name<<""<<p- gets((p+i)->Pname);
>marks<<endl; cout<<"Enter Points : ";
cout<<"Enter Roll Number : "; cin>>(p+i)->Points;
cin>>q->rno; }
cout<<"Enter name : "; cout<<"Displaying values : "<<endl;
gets(q->name); for ( i = 0; i < n; i++)
cout<<"Enter marks : "; {
cin>>q->marks; cout<<"Player Number:"<<(p+i)->Pno<<endl;
cout<<q->rno<<" "<<q->name<<" "<<q- cout<<"Player Name :"<<(p+i)->Pname<<endl;
>marks<<endl; cout<<"Player Points:"<<(p+i)->Points<<endl;
cout<<"Details of student who scored higher }
marks : "; delete[] p; //Deallocation of memory;
if (p->marks > q->marks) }
cout<<p->rno<<" "<<p->name<<" "<<p-
>marks; /* O U T P U T
else Enter value of n : 2
cout<<q->rno<<" "<<q->name<<" "<<q- Enter Player Number : 1
>marks; Enter name : amit
delete p, q; //Deallocation of memory; Enter Points : 20
} Enter Player Number : 2
Enter name : sumit
/* O U T P U T Enter Points : 40
Displaying the values:
Enter Roll Number : 1 Player Number : 1
Enter name : amit Player Name : amit
Enter marks : 70 Player Points : 20
1 amit 70 Player Number : 2
Enter Roll Number : 2 Player Name : sumit
Enter name : sumit Player Points : 40
Enter marks : 80
2 sumit 80 */
Details of student who has scored higher
marks :
2 sumit 80

*/

XII/Computer Science 71
PREVIOUS YEAR CBSE QUESTIONS FOR +++++++++++++++++++++++++++++
PRACTICE ++++++
Find the output of the following programs: #include <iostream.h>
#include<iostream.h> struct Game
void main( ) {char Magic[20];int Score;};
{ int Numbers[]={2,4,8,10}; void main()
int *ptr=Numbers; {Game M={"Tiger",500};
for(int C=1;C<3;C++) char *Choice;
{ cout<<*ptr<<”@”; Choice=M.Magic;
ptr++; Choice[4]='P';
} Choice[2]='L';
cout<<endl; M.Score+=50;
for(C=0;C<4;C++) cout<<M.Magic<<M.Score<<endl;
{ (*ptr)*=2; Game N=M;
--ptr; N.Magic[0]='A';N.Magic[3]='J';
} N.Score-=120;
for(C=0;C<4;C++) cout<<N.Magic<<N.Score<<endl;
cout<<Numbers[C]<<”#”; }
cout<<endl; } +++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++ ++++++
+++++++ #include<iostream.h>
#include<iostream.h>#include<string.h> void main()
class student {int X[]={10,25,30,55,110};
{ char *name; int *p=X;
int I; while(*p<110)
public: { if(*p%3!=0)
student( ) *p=*p+1;
{ I=0; else
name=new char[I+1];} *p=*p+2;
student(char *s) { I=strlen(s); p++;
name=new char[I+1]; }
strcpy(name,s); } for(int I=4;I>=1;I--)
void display( ) {cout<<X[I]<<"*";
{ cout<<name<<endl; } if(I%3==0) cout<<endl;
void manipulate(student &a, student &b) }
{I=a.I+b.I; cout<<X[0]*3<<endl;
delete name; }
name=new char[I+1]; +++++++++++++++++++++++++++++
strcpy(name,a.name); ++++++
strcat(name,b.name); #include<iostream.h>
}}; #include<conio.h>
void main( ) int a=3;
{ char *temp=”Jack”; void demo(int &x, int y, int *z)
Student name1(temp),name2(“Jill”),name3 { a +=x;
(“John”) ,S1,S2; y *=a;
S1.manipulate(name1,name2); *z = a+y;
S2.manipulate(S1,name3); cout<<x<<y<<*z<<endl;
S1.display( );S2.display( ); } }
+++++++++++++++++++++++++++++ void main()
++++++++++++++++ { int a=2, b=5;
# include <iostream.h> demo(::a, a, &b);
void main ( ) cout<<::a<<a<<b<<endl;
{int Track [] = {10,20,30,40,}, *Striker ; }
Striker=Track ;
Track [1] += 30 ;
cout<<"Striker"<<*Striker<<endl ;
*Striker -=10 ;
Striker++;
cout<<"Next @"<<*Striker <<endl ;
Striker +=2 ;
cout<<"last @"<<*Striker<<endl ;
cout<<"Reset To"<<Track [0] <<endl ;
}

XII/Computer Science 72
HOME ASSIGNMENT – 7 state
state1(temp),state2("Mumbai"),state3("Nagpur
TOPIC : POINTERS
"),S1,S2;
S1.Replace(state1,state2);
7.1 What is a Pointer? Why do we need
pointers? S2.Replace(S1,state3);
7.2 What do you understand by the terms S1.display( );
Dynamic & static memory allocation? S2.display( );
7.3 What is the use of new & delete }
operators? Explain with suitable 7.7
example. #include<iostream.h>
7.4 What is the use of * and & operators? #include<conio.h>
Explain with suitable example.
#include<ctype.h>
Find the output of the following programs:
7.5 #include<string.h>
#include<iostream.h> void ChangeString(char Text[],int&Counter)
void main( ) {
{ int Array[]={4,6,10,12}; char *Ptr=Text;
int *pointer=Array; int Length=strlen(Text);
for(int I=1;I<=3;I++) for(;Counter<Length-
{ cout<<*pointer<<”#”; 2;Counter+=2,Ptr++)
pointer++; {
}
cout<<endl;
for(I=1;I<=4;I++)
*(Ptr+Counter)=toupper(*(Ptr+Counter));
{ (*pointer)*=3;
}
--pointer;
} }
for(I=1;I<5;I++) void main( )
cout<<Array[I-1]<<”@”; {
cout<<endl; clrscr( );
} int Position=0;
7.6 char Message[]="Pointers Fun";
#include<iostream.h>
ChangeString(Message,Position);
#include<string.h>
cout<<Message<<"@"<<Position;
class state
{ }
char *state_name; LAB EXERCISES – 7
int size; 7.1 Write a program to swap two variables
public: using pointers.
state( )
{ size=0; 7.2 Program using pointers to find the
state_name=new char[size+1]; square of even numbers and cube of
} odd numbers present in an array.
state(char *s) 7.3 Write a program to find whether a
{ size=strlen(s); string is palindrome or not using
state_name=new char[size+1]; pointers.
strcpy(state_name,s); 7.4 Write a program to create an integer
} array of n elements dynamically and
void display( ) display the highest & lowest values with
{ cout<<state_name<<endl;} their positions. Also delete the entire
void Replace(state &a, state &b) array
{ size=a.size+b.size; 7.5. Create an object of structure GAME
delete state_name; dynamically. Obtain and then display
state_name=new char[size+1]; the values of all the elements using
pointers.
strcpy(state_name,a.state_name);
struct GAME
strcat(state_name,b.state_name); { long Pno; //Player Number
} char Pname[20];
}; float Points;
void main( ) }
{
char *temp="Delhi";

XII/Computer Science 73
7.6 Create dynamically an array of n display the details of the Player who
elements of structure GAME. Obtain scored highest points.
data of the array elements from the
user and display all the data. Also
Exam Series – I ( 2014) set1

Instructions:
a) All the questions are compulsory
b) Programming Language C++

1. a) Write the prototype of a function named arraysum(), which take a float type array and its size as parameter
and return a integer type value. The array size parameter should have a default value 10.
2

b) Write the names of the header files which are not necessary to execute the following C++ code
1
#include<iostream.h>
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
void main()
{
char c, post[15];
gets(post);
for(int i=0; post[i]!='\0' ;i++)
if(isdigit(post[i])
cout<<” invalid”<<endl;
else
{
c=toupper(post[i]);
cout<<c;
}
}

c) Chandrabhan develops a small C++ module to find the smallest number out of a given set of numbers
stored in a one dimensional array. Somehow he has committed a few logical mistakes while writing this code
and so he is not getting the desired result from the code. Find out the mistakes and correct this C++ code so
that it provides the desired result (do not add any new statement). Underline each correction made:
2
int SMALLFIND(int ARR[ ], int Size) // Statement 1
{
int SMALL=ARR[1]; //Statement 2
for (int C=2;C<Size;C++) //Statement 3
if (ARR[C]>SMALL) //Statement 4
ARR[C]=SMALL; //Statement 5
return SMALL; //Statement 6
}

d) Find output of the following program segment: 2


int A[ ][4] = {{11,21,32,43}, {20,30,40}};
for (int i = 1; i<2; i++)
for (int j = 0; j<4; j++)
cout<<A[i][j]<<"*\n";

e) Find output of the following program segment: 3


#include<iostream.h>
int p= 6;
void change( int &a, int &b, int c)
{ p=a%b;
c=c+a;
a=a+8;
b = p+a ;
cout<<a+2<<" "<<b+2<<" "<<c+2<<endl;
}

XII/Computer Science 74
void main( )
{ int p=3,q=7;
change(::p,p,q);
cout<<::p<<" "<<p<<" "<<q<<'\n';
}

2. a) What is the difference between Actual Parameter and Formal Parameter? Give an example in C++ to
illustrate both types of parameters. 2

b) Name the header files to which the following functions belong: 1


(i)atoi() (ii) strrev()

c) Rewrite the following program after removing the syntactical error(s), if any. Underline each correction.
2
void main()
{ struct movie
{
char movie_name[20];
char movie_type;
int ticket_cost = 100;
} m;
gets(movie_name);
gets(movie_type);
}
d) Find the output of the following program: 3
#include <iostream.h>
struct cube
{ int L,B,H; };
void contain(cube M)
{ cout<<M.L<<”x”<<M.B<<”x”;
cout<<M.H<<endl;
}
void main()
{
cube p1={100,150,50},p2,p3;
++p1.L;
contain(p1);
p3=p1;
++p3.B;
p3.B++;
contain(p3);
p2=p3;
p2.B += 50;
p2.H -- ;
contain(p2);
}
e) Find the output of the following program: 3
#include <iostream.h>
#include <string.h>
#include <ctype.h>
void change( char msg[], int l)
{
XII/Computer Science 75
for( int c=0; c<l; c++)
{
char ch=msg[c];
if(islower(ch))
ch=toupper(ch);
else if( isupper(ch))
ch=tolower(ch);
else if(isdigit(ch))
ch=ch+1;
else
ch=’*’;
msg[c]=ch;
}
}
void main()
{
char message[]=”2013 Tests Finished”;
int s=strlen(message);
change(message, s);
cout<<message<<endl;
for(int c=0, r=s-1; c<=s/2; c++, r--)
{
char temp=message[c];
message[c]=message[r];
message[r]=temp;
}
cout<<message<<endl;
}

3. a) Distinguish between data hiding and data abstraction in the context of OOP 2
b) Write a complete program demonstrating function overloading to calculate area of circle, area of
rectangle and area of triangle (heron’s formula). 3
c) Define and complete a class POINT for 2 dimensional points(x, y). 4
Private members
x, y as integers
Public members
Readpoint() // to accept co_ordinates (2 values) for the point
Norm() // returns distance between two points
Display() // display co_ordinates of point and distance from origin

Exam Series – I Answer Key 2014( set 1)

1. a) Write the prototype of a function named arraysum(), which take a float type array and its size as parameter
and return a integer type value. The array size parameter should have a default value 10.
2

Ans: int arraysum( float num[], int n=10);

b) Write the names of the header files which are not necessary to execute the following C++ code
1
#include<iostream.h>
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>

XII/Computer Science 76
void main()
{
char c, post[15];
gets(post);
for(int i=0; post[i]!='\0' ;i++)
if(isdigit(post[i])
cout<<” invalid”<<endl;
else
{
c=toupper(post[i]);
cout<<c;
}
}

Ans: string.h, stdlib.h

c) Chandrabhan develops a small C++ module to find the smallest number out of a given set of numbers
stored in a one dimensional array. Somehow he has committed a few logical mistakes while writing this code
and so he is not getting the desired result from the code. Find out the mistakes and correct this C++ code so
that it provides the desired result (do not add any new statement). Underline each correction made:
2
int SMALLFIND(int ARR[ ], int Size) // Statement 1
{
int SMALL=ARR[1]; //Statement 2
for (int C=2;C<Size;C++) //Statement 3
if (ARR[C]>SMALL) //Statement 4
ARR[C]=SMALL; //Statement 5
return SMALL; //Statement 6
}

Ans:
int SMALLFIND(int ARR[ ], int Size)
{
int SMALL=ARR[0];
for (int C=1;C<Size;C++)
if (ARR[C]<SMALL)
SMALL =ARR[C];
return SMALL;
}
d) Find output of the following program segment: 2
int A[ ][4] = {{11,21,32,43}, {20,30,40}};
for (int i = 1; i<2; i++)
for (int j = 0; j<4; j++)
cout<<A[i][j]<<"*\n";

Ans: 20*
30*
40*
0*

e) Find output of the following program segment: 3


#include<iostream.h>
int p= 6;
void change( int &a, int &b, int c)
{ p=a%b;
c=c+a;
a=a+8;
b = p+a ;
cout<<a+2<<" "<<b+2<<" "<<c+2<<endl;
}
void main( )
{ int p=3,q=7;
change(::p,p,q);
cout<<::p<<" "<<p<<" "<<q<<'\n';
}

Ans: 10 18 9

XII/Computer Science 77
8 16 7

2.a) What is the difference between Actual Parameter and Formal Parameter? Give an example in C++ to illustrate
both types of parameters. 2

Ans: Actual parameters: Values/variables which are used while making a call to the function.
Formal parameters: The parameters mentioned in the function header.
#include<iostream.h>
long fact( long n) Formal
{ parameter
long f=1;
for(int i=1; i<=n; i++)
f *=i;
return f;
}
void main()
{
long num;
cout<<”enter a number “; Actual
cin>>num; parameter
cout<<n<<” “<<fact(num);
}

b) Name the header files to which the following functions belong: 1


(i)atoi() (ii) strrev()

Ans: (i) stdlib.h (ii) string.h

c) Rewrite the following program after removing the syntactical error(s), if any. Underline each correction.
2
void main()
{ struct movie
{
char movie_name[20];
char movie_type;
int ticket_cost = 100;
} m;
gets(movie_name);
gets(movie_type);
}
Ans:
#include<stdio.h>
void main()
{ struct movie
{
char movie_name[20];
char movie_type[10];
int ticket_cost;
} m;
gets(m.movie_name);
gets(m.movie_type);
m.ticket_cost=100;
}

XII/Computer Science 78
d) Find the output of the following program: 3
#include <iostream.h>
struct cube
{
int L,B,H;
};
void contain(cube M)
{ cout<<M.L<<”x”<<M.B<<”x”;
cout<<M.H<<endl;
}
void main()
{
cube p1={100,150,50},p2,p3;
++p1.L;
contain(p1);
p3=p1;
++p3.B;
p3.B++;
contain(p3);
p2=p3;
p2.B += 50;
p2.H -- ;
contain(p2);
}
Ans:
101x150x50
101x152x50
101x202x49

e) Find the output of the following program: 3


#include <iostream.h>
#include <string.h>
#include <ctype.h>
void change( char msg[], int l)
{
for( int c=0; c<l; c++)
{
char ch=msg[c];
if(islower(ch))
ch=toupper(ch);
else if( isupper(ch))
ch=tolower(ch);
else if(isdigit(ch))
ch=ch+1;
else
ch=’*’;
msg[c]=ch;
}
}
void main()
{ char message[]=”2013 Tests Finished”;
int s=strlen(message);

XII/Computer Science 79
change(message, s);
cout<<message<<endl;
for(int c=0, r=s-1; c<=s/2; c++, r--)
{
char temp=message[c];
message[c]=message[r];
message[r]=temp;
}
cout<<message<<endl;
}
Ans:
3124*tESTS*fINISHED
DEHSINIf*STSEt*4213

3. a) Distinguish between data hiding and data abstraction in the context of OOP 2
Ans: providing private and protected access specifier to different data member or member functions of class
is called data hiding. The application of data hiding is called data abstraction. Without knowing the back
ground details we can use it.
b) Write a complete program demonstrating function overloading to calculate area of circle, area of
rectangle and area of triangle (heron’s formula). 3
Ans: void area( int);
void area( int, int);
void area( int, int, int);
void main()
{ int a, b, c;
int ch;
do
{ cout<<” 1. area of circle \n”;
cout<<” 2. area of rectangle \n “;
cout<<” 3. area of triangle \n”;
cout<<” enter your choice “;
cin>>ch;
switch(ch)
{
case 1:
cout<<” enter radius of circle “;
cin>>a;
area(a);
break;
case 2:
cout<<” enter side of rectangle “;
cin>>a>>b;
area(a,b);
break;
case 3:
cout<<” enter sides of triangle “;
cin>>a>>b>>c;
area(a,b,c);
break;
default:
cout<<” invalid choice “;
}
}while(ch<=4);
}

XII/Computer Science 80
void area( int x)
{
cout<<” area of circle “<<3.412 * x * x;
}
void area( int x, int y)
{
cout<<” area of rectangle “<< x * y;
}
void area( int x, int y, int z)
{
float s= (x+y+z)/2.0;
float a= sqrt( s * (s-x) * (s-y) * (s-z));
cout<<” area of triangle “<< a;
}

c) Define and complete a class POINT for 2 dimensional points(x, y). 4


Private members
x, y as integers
Public members
Readpoint() // to accept co_ordinates (2 values) for the point
Norm() // returns distance between two points
Display() // display co_ordinates of point and distance from origin
Ans:
class point
{ int x, y;
public:
void readpoint();
int norm();
void display();
};

void point::readpoint()
{ cout<<” enter co_ordinates of a point “;
cin>>x>>y;
}
int point::norm(point p1, point p2)
{ int d1= (p1.x - p2.x) * (p1.x - p2.x);
int d2=(p1.y - p2.y) * (p1.y - p2.y);
int d=sqrt(d1+d2);
return d;
}

Exam Series – I ( 2014) set 2

Instructions:
a) All the questions are compulsory
b) Programming Language C++

1. a) Write the prototype of a function named power() which takes two integers as value parameter and return a
integer type value. One of the parameter should have a default value 3. 2
b) Write the names of header files which are not necessary to run the following program. 1
#include< iostream.h>
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{ char position[80];

XII/Computer Science 81
gets(position);
puts(strlwr(position));
}
c) Ankit develops a small C++ module to find the largest number out of a given set of numbers stored in a one
dimensional array. Somehow he has committed a few logical mistakes while writing this code and so he is not
getting the desired result from the code. Find out the mistakes and correct this C++ code so that it provides
the desired result (do not add any new statement). Underline each correction made:
2
int BIG(int ARR[ ], int Size) // Statement 1
{ int B=ARR[1]; //Statement 2
for (int C=2;C<Size;C++) //Statement 3
if (ARR[C]<B) //Statement 4
ARR[C]=B; //Statement 5
return B; //Statement 6
}
d) In the following program, if the value of N given by the user is 20, what maximum and minimum
values the program could possibly display? 2
#include <iostream.h>
#include <stdlib.h>
void main()
{ int N, Guessnum;
randomize();
cin>>N;
Guessnum=random(N-10)+10;
cout<<Guessnum<<endl;
}
e) Find the output of the following program: 3
#include<iostream.h>
#include<ctype.h>
void changestring( char str[], char c)
{ for( int k=0; str[k] !=’\0’; k++)
{ if( str[k] >= ‘F’ && str[k] <= ‘L’)
str[k]= tolower(str[k]);
else
if(str[k] == ‘E’ || str[k] == ‘e’)
str[k]= c;
else
if(k % 2==0)
str[k]=toupper(str[k]);
else
str[k]=str[k-1];
} }
void main()
{ char oldtext[]=”tRaDITIonal”;

XII/Computer Science 82
changestring(oldtext, ‘#’);
cout<<” New text : “<<oldtext<<endl;
}
2. a)Explain actual and formal parameters in a function call with suitable example. 2
b)Name the header files to which the following functions belong: 1
(i)toupper() (ii) setw()
c) Rewrite the following program after removing the syntactical error(s), if any. Underline each
correction. 2
#include<iostream.h>
class game
{ int p=900,t;
public:
void initial( int p1, t1)
{ p+=p1 ;
t+= t1; }
void trackchange()
{ p++, t++; }
void status()
{ cout<<p<<”@”<<t<<endline; }
};
void main()
{ G game;
G.initial(10,5);
G.trackchange;
G.status();
}
d) Find the output of the following program: 3
#include <iostream.h>
void execute( int &b, int c=100)
{ int t= b+c;
b+=t;
if(c==100)
cout<<t<<b<<c<<endl;
}
void main()
{ int m=90, n=10;
execute(m);
cout<<m<<’\t’<<n<<endl;
execute(m,n);
cout<<m<<’\t’<<n<<endl;
}
e) Find the output of the following program: 3
#include <iostream.h>
void Changethecontent(int Arr[], int Count)
{ for (int C=1;C<Count;C++)
Arr[C-1]+=Arr[C];
}
void main()
{ int A[]={3,4,5},B[]={10,20,30,40},C[]={900,1200};
Changethecontent(A,3);
Changethecontent(B,4);

XII/Computer Science 83
Changethecontent(C,2);
for (int L=0;L<3;L++) cout<<A[L]<<’#’;
cout<<endl;
for (L=0;L<4;L++) cout<<B[L] <<’#’;
cout<<endl;
for (L=0;L<2;L++) cout<<C[L] <<’#’;
}

3. a) Differentiate between class and object in the context of OOPs. Give suitable real life example
of a class and an object. 2
b) Write a complete program demonstrating function overloading to calculate circumference of circle,
perimeter of rectangle and perimeter of triangle. 3
c) Define a class train in C++ with the following descriptions: 4
Private members are
train_no integer
destination character array
distance float
fuel float
A member function CALFUEL() to calculate the value of fuel as per the following
distance fuel
<500 300
>=500 but <1000 500
>=1000 but <2000 1000
>=2000 1500
Public member functions are
- Function read_data() to accept data members for an object of TRAIN class except
fuel and invoke the function CALFUEL() to calculate the quantity of fuel.
-Function display() to display the details of an object

Exam Series – I Answer Key 2014 ( set 2)


1. a) Write the prototype of a function named power() which takes two integers as value parameter and return a
integer type value. One of the parameter should have a default value 3. 2
Ans: int power( int x, int y=3);
b) Write the names of header files which are not necessary to run the following program. 1
#include< iostream.h>
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{ char position[80];
gets(position);
puts(strlwr(position));
}
Ans: iostream.h conio.h

XII/Computer Science 84
c)Ankit develops a small C++ module to find the largest number out of a given set of numbers stored in a one
dimensional array. Somehow he has committed a few logical mistakes while writing this code and so he is not getting
the desired result from the code. Find out the mistakes and correct this C++ code so that it provides the desired result
(do not add any new statement). Underline each correction made: 2
int BIG(int ARR[ ], int Size) // Statement 1
{ int B=ARR[1]; //Statement 2
for (int C=2;C<Size;C++) //Statement 3
if (ARR[C]<B) //Statement 4
ARR[C]=B; //Statement 5
return B; //Statement 6
}
Ans:
int BIG(int ARR[ ], int Size) // Statement 1
{ int B=ARR[0]; //Statement 2
for (int C=1;C<Size;C++) //Statement 3
if (ARR[C]>B) //Statement 4
B= ARR[C]; //Statement 5
return B; //Statement 6
}
d) In the following program, if the value of N given by the user is 20, what maximum and minimum
values the program could possibly display? 2
#include <iostream.h>
#include <stdlib.h>
void main()
{ int N,Guessnum;
randomize();
cin>>N;
Guessnum=random(N-10)+10;
cout<<Guessnum<<endl;
}
Ans: 10, 19
e) Find the output of the following program: 3
#include<iostream.h>
#include<ctype.h>
void changestring( char str[], char c)
{ for( int k=0; str[k] !=’\0’; k++)
{ if( str[k] >= ‘F’ && str[k] <= ‘L’)
str[k]= tolower(str[k]);
else
if(str[k] == ‘E’ || str[k] == ‘e’)
str[k]= c;
else
if(k % 2==0)
str[k]=toupper(str[k]);
else
str[k]=str[k-1];
} }
void main()
{ char oldtext[]=”tRaDITIonal”;
changestring(oldtext, ‘#’);
cout<<” New text : “<<oldtext<<endl;
}

XII/Computer Science 85
Ans: New text : TTAAiiiiNNL

2. a)Explain actual and formal parameters in a function call with suitable example. 2
Ans: Actual parameters: Values/variables which are used while making a call to the function.
Formal parameters: The parameters mentioned in the function header.
#include<iostream.h>
long fact( long n) Formal
{ parameter
long f=1;
for(int i=1; i<=n; i++)
f *=i;
return f; }
void main()
{
long num;
cout<<”enter a number “; Actual
cin>>num; parameter
cout<<n<<” “<<fact(num);
}

b)Name the header files to which the following functions belong: 1


(i)toupper() (ii) setw()
Ans: (i) ctype.h (ii)iomanip.h
c) Rewrite the following program after removing the syntactical error(s), if any. Underline each
correction. 2
#include<iostream.h>
class game
{ int p=900,t;
public:
void initial( int p1, t1)
{ p+=p1 ;
t+= t1; }
void trackchange()
{ p++, t++; }
void status()
{ cout<<p<<”@”<<t<<endline; }
};
void main()
{ G game;
G.initial(10,5);
G.trackchange;
G.status();
}
Ans:
#include<iostream.h>
class game
{ int p, t;
public:
void initial( int p1, int t1)
{ p+=p1 ;
t+= t1; }
void trackchange()
{ p++;t++; }
void status()
{ cout<<p<<”@”<<t<<endl; }
};
void main()
{ game G;
G.initial(10,5);

XII/Computer Science 86
G.trackchange();
G.status();
}

d) Find the output of the following program: 3


#include <iostream.h>
void execute( int &b, int c=100)
{ int t= b+c;
b+=t;
if(c==100)
cout<<t<<b<<c<<endl;
}
void main()
{ int m=90, n=10;
execute(m);
cout<<m<<’\t’<<n<<endl;
execute(m,n);
cout<<m<<’\t’<<n<<endl;
}
Ans:
190 280 100
280 10
570 10
e) Find the output of the following program: 3
#include <iostream.h>
void Changethecontent(int Arr[], int Count)
{ for (int C=1;C<Count;C++)
Arr[C-1]+=Arr[C];
}
void main()
{ int A[]={3,4,5},B[]={10,20,30,40},C[]={900,1200};
Changethecontent(A,3);
Changethecontent(B,4);
Changethecontent(C,2);
for (int L=0;L<3;L++) cout<<A[L]<<’#’;
cout<<endl;
for (L=0;L<4;L++) cout<<B[L] <<’#’;
cout<<endl;
for (L=0;L<2;L++) cout<<C[L] <<’#’;
}
Ans:
7#9#5#
30#50#70#40
2100#1200#
3. a) Differentiate between class and object in the context of OOPs. Give suitable real life example of a class and
an object. 2
Ans:

XII/Computer Science 87
Class is a collection of different characteristics and behaviors under a common name. Object is the instance of the
class which shares these characteristics and behaviors.
For example HUMANBEING is the class and GOPAL is the object of that class.

b) Write a complete program demonstrating function overloading to calculate circumference of circle, perimeter of
rectangle and perimeter of triangle. 3
Ans:
void circumference( int);
void circumference( int, int);
void circumference( int, int, int);
void main()
{ int a, b, c;
int ch;
do
{ cout<<” 1. circumference of circle \n”;
cout<<” 2. circumference of rectangle \n “;
cout<<” 3. circumference of triangle \n”;
cout<<” enter your choice “;
cin>>ch;
switch(ch)
{
case 1:
cout<<” enter radius of circle “;
cin>>a;
circumference(a);
break;
case 2:
cout<<” enter side of rectangle “;
cin>>a>>b;
circumference(a,b);
break;
case 3:
cout<<” enter sides of triangle “;
cin>>a>>b>>c;
circumference(a,b,c);
break;
default:
cout<<” invalid choice “;
}
}while(ch<=4);
}

void circumference( int x)


{
cout<<” circumference of circle “<<2* 3.412 * x;
}
void circumference( int x, int y)
{
cout<<” circumference of rectangle “<< 2*(x + y);
}
void circumference( int x, int y, int z)
{
float a= x+y+z;
cout<<” circumference of triangle “<< a;
}

c) Define a class train in C++ with the following descriptions: 4


Private members are
train_no integer
destination character array
distance float
fuel float

XII/Computer Science 88
A member function CALFUEL() to calculate the value of fuel as per the following
distance fuel
<500 300
>=500 but <1000 500
>=1000 but <2000 1000
>=2000 1500
Public member functions are
- Function read_data() to accept data members for an object of TRAIN class except
fuel and invoke the function CALFUEL() to calculate the quantity of fuel.
-Function display() to display the details of an object
Ans:
class train
{
int trainno;
char destination[20];
float distance;
float fuel;
void calfuel();

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

void train::read_data()
{
cout<<” enter train number “;
cin>>trainno;
cout<<” enter destination “;
gets(destination);
cout<<” enter distance “;
cin>>distance;
calfuel();
}

void display()
{
cout<<” train number “<<trainno<<endl;
cout<<” destination “<<destination<<endl;
cout<<” distance “<<distance;
cout<<” quantity of fuel “<<fuel;
}

void calfuel()
{
if(distance<500)
fuel=300;
else if(distance <1000)
fuel=500;
else if(distance <2000)
fuel=1000;
else
fuel=1500;
}

Exam Series – II ( 2014) set 1

Instructions:

XII/Computer Science 89
a)All the questions are compulsory
b)Programming Language C++

1.(a) What is the difference between call by value and call by reference? Give an example in c++ to illustrate this.
2

(b) Write the names of the header files to which the following belongs: 1
(i) puts()
(ii) sin()

(c ) Rewrite the following program after removing the syntactical errors if any. Underline each correction.
2
#include[iostream.h]
#include[stdio.h]
class employee
{
int empid=901;
char ename[20];
public:
employee() { }
void joining()
{
cin>>empid;
gets(ename);
}
void list()
{ cout<<empid<<” :”<<ename<<endl; }
};
void main()
{
employee e;
joining.e();
e.list()
}

(d) Find the output of the following program. 3


#include<iostream.h>
#include<ctype.h>
void main()
{
char text[]=”Mind@Work!”;
for( int i=0;text[i]!=’\0’; i++)
{
if(!(isalpha(text[i])))
text[i]=’*’;
else if ( isupper(text[i]))
text[i]=text[i]+1;
else
text[i]=text[i+1];
}
cout<<text;
}

(e) Find the output of the following program: 2


#include<iostream.h>
#include<ctype.h>
void encode( char info[], int n);
void main()
{
char memo[]=”Justnow”;
encode(memo,2);
cout<<memo<<endl;
}
void encode( char info[], int n)
{
for( int i=0; info[i] !=’\0’; i++)

XII/Computer Science 90
if( i % 2 ==0)
info[i]=info[i] – n;
else if ( islower(info[i]))
info[i]=toupper(info[i]);
else
info[i]=info[i] + n;
}

(f) Study the following program and select the possible output(s) from possible outputs given
below. Justify your answer. 2

#include<iostream.h>
#include<stdlib.h>
const int limit=4;
void main()
{
randomize();
int points;
points=100 + random(limit);
for( int p=points; p>=100; p--)
cout<<p<<”#”;
cout<<endl;
}

Outputs:
(i) 103#102#101#100#
(ii) 100#101#102#103#
(iii) 100#101#102#103#104#
(iv) 104#103#102#101#100#

2. a) What is inheritance in the context of OOPS? Explain with the help of c++ example. 2

(b) Define a class COMPETITION in c++ with following specifications and complete the function definitions
4
Private members
Event_no integer
Description char(30)
Score integer
Qualified char
Public members
Input() To take input for event_no, description and score
Award() To award qualified as ‘y’ if score is more than the cut off score
passed as integer argument to the function else award ‘n’.
Show() To display all details.

(c ) Answer the questions (i) and (ii) after going through the following class: 2
class test
{
char paper[20];
int marks;
public:
test() //function 1
{
strcpy(paper, “computer”);
marks=0;
}
test( char p[]) //function 2
{
strcpy( paper,p);
marks=0;
}
test( int m) //function 3
{
strcpy( paper, “computer”);
marks=m;
}

XII/Computer Science 91
test( char p[], int m) //function 4
{
strcpy( paper, p);
marks=p;
}
};
(i) Which feature of object oriented programming is demonstrated using function 1, function 2, function 3 and
function 4 in the above class test.
(ii) Write statements in c++ that would execute function 2 and function 4 of class test.

(d) Consider the following class definitions and answer the questions following it: 4
class base
{
int a1;
void bf1();
protected:
int b1;
void bf2();
public:
int c1;
void bf3();
} ob1;
class middle: private base
{
int a2;
protected:
int b2;
void mf1();
public:
int c2;
void mf2();
}ob2;
class derived: protected middle
{
void df1();
int a3;
public:
int b3;
void df2();
}ob3;

(i) Name the member functions accessible by the objects of class derived.
(ii) Name the data members that are accessible in function df1().
(iii) What would be the size of class derived objects?
(iv) Name the data members that are accessible in function bf1().

3.(a) Observe the program segment given below carefully, and answer the question that follow: 1
class book
{
int book_no;
char book_name[20];
public:
void enterdetails(); //function to enter book details
void showdetails(); //function to display details
int rbook_no()
{
return book_no;
}
};
void modify( book newb)
{ fstream file;
file.open(“book.dat”, ios::binary|ios::in|ios::out);
book ob;
int recordsread=0, found=0;
while( !found && file.read((char *)&ob, sizeof(ob)))
{
recordsread++;

XII/Computer Science 92
if(newb.rbook_no()==ob.rbook_no())
{
------------------------------- // missing statement
file.write((char *) &newb, sizeof(newb);
found =1;
}
else
file.write((char *)&ob, sizeof(ob));
}
if( !found)
cout<<”record for modification does not exist “;
file.close();
};

If the function modify() is supposed to modify a record in file book.dat with the values of book newb passed to its
argument, write the appropriate statement for missing statement using seekp() or seekg() which ever needed, in the
above code that would write the modified record at its proper place.

(b) Write a function in c++ to count and display the number of lines starting with alphabet ‘A’ present in a text file
“Lines.txt” 2

(c) Write a user defined function in c++ to read the content from a text file story.txt. Count and display the number of
alphabets present in it. 2

(d) Assuming a binary file jokes.dat is containing objects belonging to a class joke as defined below. Write a user
defined function in c++ to add more objects belonging to class joke at the bottom of it. 3
class joke
{
int jokeid;
char type[5];
char jokedesc[255];
public:
void newjokeentry()
{
cin>>jokeid;
gets(type);
gets(jokedesc);
}
void showjoke()
{
cout<<jokeid<<”:”<<type<<endl<<jokedesc<<endl;
}
};

( e) Given a binary file student.dat containing records of the following class student type. 3

class student
{
char s_admno[10]; //admission number of student
char s_name[30]; // student name
int percent; // percent of mark
public:
void enterdata()
{
gets(s_admno); gets(s_name);
cin>>percent;
}

void displaydata()
{
cout<<setw(12)<<s_admno;
cout<<setw(32)<<s_name;
cout<<setw(3)<<percent<<endl;
}

int retpercent()
{

XII/Computer Science 93
return percent;
}
};

Write a function in c++, which would read contents of file student.dat and display the details of whose percent is above
75.

Exam Series – II (2014) Marking Scheme set 1


1.(a) What is the difference between call by value and call by reference? Give an example in c++ to illustrate this.
2
Ans:
Call by value: The actual and formal parameters are stored in different locations. Any change made in formal
parameters are not reflected back to actual parameters.
Call by reference: The actual and formal parameters are stored in the same locations. Any change made to formal
parameters reflected back to actual parameters.

void change( int a, int & b)


{
a= a+10;
b=b* a;
}
void main()
{
int x, y;
cin>>x>>y;
change(x,y);
cout<<x<<y;
}
Here x is passed as by value where as y is passed as by reference.

(b) Write the names of the header files to which the following belongs: 1
(i) puts()
(ii) sin()
Ans:
(i) Stdio.h
(ii) Math.h

(c ) Rewrite the following program after removing the syntactical errors if any. Underline each correction.
2
#include[iostream.h]
#include[stdio.h]
class employee
{
int empid=901;
char ename[20];
public:
employee() { }
void joining()
{
cin>>empid;
gets(ename);
}
void list()
{ cout<<empid<<” :”<<ename<<endl; }
};
void main()
{
employee e;
joining.e();
e.list()
}
Ans:
#include<iostream.h>
#include<stdio.h>
class employee

XII/Computer Science 94
{
int empid;
char ename[20];
public:
employee() { empid=901; }
void joining()
{
cin>>empid;
gets(ename);
}
void list()
{ cout<<empid<<” :”<<ename<<endl; }
};
void main()
{
employee e;
e.joining();
e.list();
}

(d) Find the output of the following program. 3


#include<iostream.h>
#include<ctype.h>
void main()
{
char text[]=”Mind@Work!”;
for( int i=0;text[i]!=’\0’; i++)
{
if(!(isalpha(text[i])))
text[i]=’*’;
else if ( isupper(text[i]))
text[i]=text[i]+1;
else
text[i]=text[i+1];
}
cout<<text;
}
Ans:
Nnd@*Xrk!*

(e) Find the output of the following program: 2


#include<iostream.h>
#include<ctype.h>
void encode( char info[], int n);
void main()
{
char memo[]=”Justnow”;
encode(memo,2);
cout<<memo<<endl;
}
void encode( char info[], int n)
{
for( int i=0; info[i] !=’\0’; i++)
if( i % 2 ==0)
info[i]=info[i] – n;
else if ( islower(info[i]))
info[i]=toupper(info[i]);
else
info[i]=info[i] + n;
}
Ans:
HUqTlOu

(f) Study the following program and select the possible output(s) from possible outputs given
below. Justify your answer. 2

#include<iostream.h>

XII/Computer Science 95
#include<stdlib.h>
const int limit=4;
void main()
{
randomize();
int points;
points=100 + random(limit);
for( int p=points; p>=100; p--)
cout<<p<<”#”;
cout<<endl;
}

Outputs:
(v) 103#102#101#100#
(vi) 100#101#102#103#
(vii) 100#101#102#103#104#
(viii) 104#103#102#101#100#

Ans:
Only (i) is the correct answer.
Value of point will be from 100 to 103. From the loop after substituting value of point we may get (i).

2. a) What is inheritance in the context of OOPS? Explain with the help of c++ example. 2
Ans:
The process of inheriting the characteristics and behaviors from one class to other class is called inheritance. It helps
in reusability, establishes the relationships between classes and establishes the transitivity relationship between
classes.

class base
{
int a,b;
public:
void getdata1()
{
cin>>a>>b;
}
void display1()
{
cout<<a<<b;
}
};

class derive: public base


{
int z;
public:
void getdata2()
{ getdata1();
cin>>z;
}
void display2()
{
display1();
cout<<z;
}
};

(b) Define a class COMPETITION in c++ with following specifications and complete the function definitions
4
Private members
Event_no integer
Description char(30)
Score integer
Qualified char
Public members
Input() To take input for event_no, description and score

XII/Computer Science 96
Award() To award qualified as ‘y’ if score is more than the cut off score
passed as integer argument to the function else award ‘n’.
Show() To display all details.
Ans:
class competition
{
int event_no;
char description[30];
int score;
char qualified;
public:
void input();
void award(int);
void show();
};

void competition::input()
{
cin>>event_no;;
gets(description);
cin>>score;
}
void competition::award(int cutoff)
{
if (score>cutoff)
qualified=’y’;
else
qualified=’n’;
}
void competition::show()
{
cout<<event_no;
cout<<description;
cout<<score;
cout<<qualified;
}

(c ) Answer the questions (i) and (ii) after going through the following class: 2
class test
{
char paper[20];
int marks;
public:
test() //function 1
{
strcpy(paper, “computer”);
marks=0;
}
test( char p[]) //function 2
{
strcpy( paper,p);
marks=0;
}
test( int m) //function 3
{
strcpy( paper, “computer”);
marks=m;
}
test( char p[], int m) //function 4
{
strcpy( paper, p);
marks=p;
}
};
(iii) Which feature of object oriented programming is demonstrated using function 1, function 2, function 3 and
function 4 in the above class test.
(iv) Write statements in c++ that would execute function 2 and function 4 of class test.

XII/Computer Science 97
Ans:
(i) function overloading/ constructor overloading/ polymorphism
(ii) test t1(“physics”);
test t2(“chemistry”,70);

(d) Consider the following class definitions and answer the questions following it: 4
class base
{
int a1;
void bf1();
protected:
int b1;
void bf2();
public:
int c1;
void bf3();
} ob1;
class middle: private base
{
int a2;
protected:
int b2;
void mf1();
public:
int c2;
void mf2();
}ob2;
class derived: protected middle
{
void df1();
int a3;
public:
int b3;
void df2();
}ob3;

(v) Name the member functions accessible by the objects of class derived.
(vi) Name the data members that are accessible in function df1().
(vii) What would be the size of class derived objects?
(viii) Name the data members that are accessible in function bf1().
Ans:
(i) df2()
(ii) a3,b3,b2,c2
(iii) 16
(iv) a1, b1, c1

3.(a) Observe the program segment given below carefully, and answer the question that follow: 1
class book
{
int book_no;
char book_name[20];
public:
void enterdetails(); //function to enter book details
void showdetails(); //function to display details
int rbook_no()
{
return book_no;
}
};
void modify( book newb)
{ fstream file;
file.open(“book.dat”, ios::binary|ios::in|ios::out);
book ob;
int recordsread=0, found=0;
while( !found && file.read((char *)&ob, sizeof(ob)))
{
recordsread++;

XII/Computer Science 98
if(newb.rbook_no()==ob.rbook_no())
{
------------------------------- // missing statement
file.write((char *) &newb, sizeof(newb);
found =1;
}
else
file.write((char *)&ob, sizeof(ob));
}
if( !found)
cout<<”record for modification does not exist “;
file.close();
};

If the function modify() is supposed to modify a record in file book.dat with the values of book newb passed to its
argument, write the appropriate statement for missing statement using seekp() or seekg() which ever needed, in the
above code that would write the modified record at its proper place.
Ans:
file.seekp((recordsread-1) * sizeof(ob), ios::beg)

(b) Write a function in c++ to count and display the number of lines starting with alphabet ‘A’ present in a text file
“Lines.txt” 2
Ans:
void countline()
{
int n=0;
char line[80];
ifstream if1;
if1.open(“lines.txt”);
while(if1.getline(line))
{
if(line[0]==’A’)
n++;
}
if1.close();
cout<<” number of lines “<<n;
}

(c) Write a user defined function in c++ to read the content from a text file story.txt. Count and display the number of
alphabets present in it. 2
Ans:
void countalpha()
{
int n=0;
char ch;
ifstream if1;
if1.open(“story.txt”);
while(if1.get(ch))
{
if( isalpha(ch))
n++;
}
if1.close();
cout<<” number of alphabets “<<n;
}

(d) Assuming a binary file jokes.dat is containing objects belonging to a class joke as defined below. Write a user
defined function in c++ to add more objects belonging to class joke at the bottom of it.
3
class joke
{
int jokeid;
char type[5];
char jokedesc[255];
public:
void newjokeentry()
{

XII/Computer Science 99
cin>>jokeid;
gets(type);
gets(jokedesc);
}
void showjoke()
{
cout<<jokeid<<”:”<<type<<endl<<jokedesc<<endl;
}
};
Ans:
void addrec()
{
joke j;
ofstream of1;
of1.open(“jokes.dat”,ios::app|ios:binary);
do
{
j.newjokeentry();
of1.write((char *)&j, sizeof(j));
cout<<” Do you want to add more records “;
cin>>ch;
}while(ch==’y’|| ch==’Y’);
}

( e) Given a binary file student.dat containing records of the following class student type. 3

class student
{
char s_admno[10]; //admission number of student
char s_name[30]; // student name
int percent; // percent of mark
public:
void enterdata()
{
gets(s_admno); gets(s_name);
cin>>percent;
}

void displaydata()
{
cout<<setw(12)<<s_admno;
cout<<setw(32)<<s_name;
cout<<setw(3)<<percent<<endl;
}

int retpercent()
{ return percent;}
};
Write a function in c++, which would read contents of file student.dat and display the details of whose percent is above
75.

Ans:

void display75rec()
{ student s;
ifstream if1;
if1.open(“student.dat”, ios:binary);
while(if1.read((char *)&s, sizeof(s)))
{ If( s.retpercent()>75)
s.displaydata();

}
}

Exam Series – II ( 2014) set 1

XII/Computer Science 100


Instructions:
a) All the questions are compulsory
b) Programming Language C++

1.(a) Differentiate between a Run time errors and syntax error. Also give suitable examples of each in c++.
2

(b) Name the header file(s) that shall be needed for successful compilation of the following c++ code.
1
void main()
{ char string[20];
gets(string);
strcat(string, “cbse”);
puts(string);
}

(c ) Rewrite the following program after removing the syntactical error(s) if any. Underline each correction.
2
#include<iostream.h>
const int max 10;
void main()
{ int number[max];
number={20, 50, 10, 30, 40 };
for( loc=max-1; loc>=0; loc --)
cout>>number[loc];
}
(d) Find the output of the following program: 3
#include<iostream.h>
struct mybox
{
int length, breadth, height;
};
void dimension( mybox m)
{
cout<<m.length<<”x”<<m.breadth<<”x”<<m.height<<endl;
}
void main()
{
mybox b1={ 10,15,5}, b2, b3;
++b1.height;
dimension(b1);
b3=b1;
++b3.length;
b3.breadth++;
dimension(b3);
b2=b3;
b2.height+=5;
b2.length--;
dimension(b2);
}

(e) Find the output of the following program: 2


#include<iostream.h>
void withdef( int hisnum=30)
{ for( int i=20; i<=hisnum; i+=5)
cout<<i<<”,”;
cout<<endl;
}
void control( int &mynum)
{ mynum+=10;
withdef(mynum);
}
void main()
{
int yournum=20;
control(yournum);

XII/Computer Science 101


withdef();
cout<<” number= “<<yournum<<endl;
}
(f) In the following c++ program what is the expected value of mymarks from options (i) to
(iv) given below. Justify your answer. 2
#include<stdlib.h>
#include<iostream.h>
void main()
{
randomize();
int marks[]={ 99, 92, 94, 96, 93, 95}, mymarks;
mymarks=marks[1+random(2)];
cout<<mymarks<<endl;
}
Expected Values:
(i) 99 (ii) 94 (iii)96 (iv) None of the options

2. (a) What is the use of constructor function? Give any two characteristics of constructor. 2

(b) Answer the questions (i) and (ii) after going through the following class: 2
class work
{ int worked;
char worktype;
public:
~work() //function 1
{
cout<<” unallocated “<<endl;
}
void status() //function 2
{
cout<<worked<<”:”<<worktype<<endl;
}
work() //function 3
{ workid=10;
worktype=’t’;
}
work( work &w) //function 4
{
worked=w.workid +12;
worktype=w.worktype +1;
}
};

(i) Which member function out of function 1, function 2, function 3 and function 4 shown in the above definition
of class work is called automatically, when the scope of an object gets over? Is it known as constructor or
destructor or overloaded function or copy constructor?

(ii) Work w; //statement 1


Work y(w); //statement 2
Which member function out of function 1, function 2, function 3 and function 4 shown in the above definition
of class work is called on execution of statement written as statement 2? What is this function specifically
known as out of destructor or copy constructor or default constructor?

(c ) Define a class RESORT in c++ with following description: 4


Private members
Rno // store room number
Name // customer name
Charges // charge per day
Days // number of days of stay
Amount // total charges
Compute() // a function to calculate and return amount as
// days*charges and if the amount is more than 11000
// then calculate as 1.02*days*charges.
Public members:
Getinfo() // a function to input rno, name, charges, days
Dispinfo() // to display all details

XII/Computer Science 102


(d) Answer the questions (i) to (iv) based on the following: 4
class facetoface
{
char centercode[10];
public:
void input();
void output();
};
class online
{
char website[50];
public:
void sitein();
void siteout();
};
class training: public facetoface, online
{
long tcode;
float charge;
int period;
public:
void register();
void show();
};

(i) Which type of inheritance is shown in the above example.


(ii) Write names of all the member functions accessible from show() function of class training.
(iii) Write names of all members accessible through an object of class training.
(iv) Is the function output() accessible inside the function siteout()? Justify your answer.

3. (a) Observe the program segment given below carefully and fill in the blanks marked as line 1 and line 2 using
fstream functions for performing the required task. 1

#include<fstream.h>
class stack
{
long ino; //item number
char item[20]; //item name
int qty; //quantity
public:
void get(int); //function to enter the content
void show(); //function to display details
void purchase( int tqty) //function to increment in qty
{
qty +=tqty;
}
long knowino() { return ino; }
};
void purchaseitem( long pino, int pqty) // pino is ino of the item purchased
{ // pqty is number of item purchased
fstream file;
file.open(“items.dat”, ios::binay|ios::in|ios::out);
int pos=-1;
stock s;
while ( (pos==-1) && file.read((char *)&s, sizeof(s)))
{
if( s.knowino()==pino)
{
s.purchase(pqty); // to update the number of items
pos=file.tellg() – sizeof(s);
------------------------; //line 1 to place file pointer to the required position
------------------------; //line 2 to write the object s on to the file
}
if( pos== -1)
cout<<”no updation takes place”;
file.close();
}

XII/Computer Science 103


}

(b)Write a function count_do() in c++ to count the presence of a word ‘do’ in a text file “memo.txt” 2

(c) Write a function in c++ to count the number of lowercase alphabets present in a text file “BOOK.TXT” 2

(d) Given a binary file PHONE.DAT, containing records of the following structure type. 3
class phonelist
{
char name[20];
char address[30];
char areacode[5];
char phoneno[15];
public:
void register();
void show();
int 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

(e) Write a function in c++ to read and display the detail of all the users whose status is ‘A’ from a binary file
“USER.DAT” . Assuming the binary file “USER.DAT” is containing objects of class USER, which is defined as follows:
3
class user
{
int uid; // user id
char uname[20]; //user name
char status; //user type a/i
public:
void register(); //function to enter the content
void show(); //function to display all data member
char getstatus()
{
return status;
}
};

Exam Series – II Marking Scheme set 2

Instructions:
a) All the questions are compulsory
b) Programming Language C++

1.(a) Differentiate between a Run time errors and syntax error. Also give suitable examples of each in c++.
2
Ans:
The errors due to any violation of rule/regulations of c++ programming are called syntax error. i.e not putting ; at end,
not declaring variable but using it.
The errors occurs at run time is called runtime error. Divide by zero, square root of negative number or opening of file
in wrong mode for operations.

(b) Name the header file(s) that shall be needed for successful compilation of the following c++ code.
1
void main()
{ char string[20];
gets(string);
strcat(string, “cbse”);
puts(string);
}
Ans:
stdio.h
XII/Computer Science 104
string.h

(c ) Rewrite the following program after removing the syntactical error(s) if any. Underline each correction.
2
#include<iostream.h>
const int max 10;
void main()
{ int number[max];
number={20, 50, 10, 30, 40 };
for( loc=max-1; loc>=0; loc --)
cout>>number[loc];
}
Ans:
#include<iostream.h>
const int max= 10;
void main()
{ int number[max]={20, 50, 10, 30, 40 };
for(int loc=max-1; loc>=0; loc --)
cout<<number[loc];
}

(d) Find the output of the following program: 3


#include<iostream.h>
struct mybox
{
int length, breadth, height;
};
void dimension( mybox m)
{
cout<<m.length<<”x”<<m.breadth<<”x”<<m.height<<endl;
}

void main()
{
mybox b1={ 10,15,5}, b2, b3;
++b1.height;
dimension(b1);
b3=b1;
++b3.length;
b3.breadth++;
dimension(b3);
b2=b3;
b2.height+=5;
b2.length--;
dimension(b2);
}
Ans:
10x15x6
11x16x6
10x16x11

(e) Find the output of the following program: 2


#include<iostream.h>
void withdef( int hisnum=30)
{ for( int i=20; i<=hisnum; i+=5)
cout<<i<<”,”;
cout<<endl;
}
void control( int &mynum)
{ mynum+=10;
withdef(mynum);
}
void main()
{
int yournum=20;
control(yournum);

XII/Computer Science 105


withdef();
cout<<” number= “<<yournum<<endl;
}
Ans:
20,25,30,
20,25,30,
number= 30

(f) In the following c++ program what is the expected value of mymarks from options (i) to
(iv) given below. Justify your answer. 2
#include<stdlib.h>
#include<iostream.h>
void main()
{
randomize();
int marks[]={ 99, 92, 94, 96, 93, 95}, mymarks;
mymarks=marks[1+random(2)];
cout<<mymarks<<endl;
}
Expected Values:
(i) 99 (ii) 94 (iii)96 (iv) None of the options
Ans:
(ii) is the correct answer.
Marks[ 1 + random(2)] always gines mark[1] or mark[2] i.e 92 or 94
2. (a) What is the use of constructor function? Give any two characteristics of constructor. 2
Ans:
Constructor functions are used to initialize the object(s) of class. It is a special function.
The constructor functions are invoked automatically when a new objects will be created.
The constructors may have arguments so they can be overloaded.
They can not be inherited.

(b) Answer the questions (i) and (ii) after going through the following class: 2
class work
{ int worked;
char worktype;
public:
~work() //function 1
{
cout<<” unallocated “<<endl;
}
void status() //function 2
{
cout<<worked<<”:”<<worktype<<endl;
}
work() //function 3
{ workid=10;
worktype=’t’;
}
work( work &w) //function 4
{
worked=w.workid +12;
worktype=w.worktype +1;
}
};

(i) Which member function out of function 1, function 2, function 3 and function 4 shown in the above definition
of class work is called automatically, when the scope of an object gets over? Is it known as constructor or
destructor or overloaded function or copy constructor?

(ii) Work w; //statement 1


Work y(w); //statement 2
Which member function out of function 1, function 2, function 3 and function 4 shown in the above definition
of class work is called on execution of statement written as statement 2? What is this function specifically
known as out of destructor or copy constructor or default constructor?
Ans:
(i) Function1 , destructor
(ii) Function 4 , copy constructor
XII/Computer Science 106
(c ) Define a class RESORT in c++ with following description: 4
Private members
Rno // store room number
Name // customer name
Charges // charge per day
Days // number of days of stay
Amount // total charges
Compute() // a function to calculate and return amount as
// days*charges and if the amount is more than 11000
// then calculate as 1.02*days*charges.
Public members:
Getinfo() // a function to input rno, name, charges, days
Dispinfo() // to display all details

Ans:

class resort
{
int rno;
char name[20];
float charges;
int days;
float amount;
float compute();
public:
void getinfo();
void dispinfo();
};

void resort::getinfo()
{
cin>>rno;
gets(name);
cin>>charges;
cin>>days;
}

void resort::dispinfo()
{
cout<<rno;
cout<<name;
cout<<charges;
cout<<days;
cout<<amount;
}

float resort::compute()
{
amount= days * charges;
if(amount>11000)
amount= 1.02 * days*charges;
return amount;
}

(d) Answer the questions (i) to (iv) based on the following: 4


class facetoface
{
char centercode[10];
public:
void input();
void output();
};
class online
{
char website[50];
public:

XII/Computer Science 107


void sitein();
void siteout();
};
class training: public facetoface, online
{
long tcode;
float charge;
int period;
public:
void register();
void show();
};

(v) Which type of inheritance is shown in the above example.


(vi) Write names of all the member functions accessible from show() function of class training.
(vii) Write names of all members accessible through an object of class training.
(viii) Is the function output() accessible inside the function siteout()? Justify your answer.
Ans:
(i) multiple inheritance
(ii) sitein(), siteout(), input(),output(),register()
(iii) data member: NIL
member functions: input(), output(), register(), show()
(iv) No. These are functions of indivisual classes.

3. (a) Observe the program segment given below carefully and fill in the blanks marked as line 1 and line 2 using
fstream functions for performing the required task. 1

#include<fstream.h>
class stack
{ long ino; //item number
char item[20]; //item name
int qty; //quantity
public:
void get(int); //function to enter the content
void show(); //function to display details
void purchase( int tqty) //function to increment in qty
{
qty +=tqty;
}
long knowino() { return ino; }
};
void purchaseitem( long pino, int pqty) // pino is ino of the item purchased
{ // pqty is number of item purchased
fstream file;
file.open(“items.dat”, ios::binay|ios::in|ios::out);
int pos=-1;
stock s;
while ( (pos==-1) && file.read((char *)&s, sizeof(s)))
{
if( s.knowino()==pino)
{
s.purchase(pqty); // to update the number of items
pos=file.tellg() – sizeof(s);
------------------------; //line 1 to place file pointer to the required position
------------------------; //line 2 to write the object s on to the file
}
if( pos== -1)
cout<<”no updation takes place”;
file.close();
}
}
Ans:
(i) file.seekp(pos, ios::beg);
(ii) file.write()char *)&s, sizeof(s));

(b)Write a function count_do() in c++ to count the presence of a word ‘do’ in a text file “memo.txt” 2
Ans:

XII/Computer Science 108


void count_do()
{
ifstream if1;
if1.open(“memo.txt”);
char word[3];
int n=0;
while(! if1.eof())
{
if1>>word;
if( strcmpi(word, “do”)==0)
n++;
}
if1.close();
cout<<” number of do are “<<n;
}

(c) Write a function in c++ to count the number of lowercase alphabets present in a text file “BOOK.TXT”
2
Ans:
void count_do()
{
ifstream if1;
if1.open(“book.txt”);
char ch;
int n=0;
while(! if1.eof())
{
if1.get(ch);
if( isalpha(ch))
if(islower(ch))
n++;
}
if1.close();
cout<<” number of lower case alphabets are “<<n;
}

(d) Given a binary file PHONE.DAT, containing records of the following structure type. 3
class phonelist
{
char name[20];
char address[30];
char areacode[5];
char phoneno[15];
public:
void register();
void show();
int checkcode( char AC[])
{
return strcmp( areacode, AC);
}
};
Write a function TRANSFER() in c++, that would copy all those records which are having areacode as “DEL” from
PHONE.DAT to PHONBACK.DAT

Ans:
void transfer()
{
ifstream if1;
if1.open(“phone.dat”,ios::binary);
ofstream of1;
of1.open(“phonback.dat”, ios::binary);
phonelist p;
while(if1.read((char*)&p, sizeof(s)))
{
if(p.checkcode(“DEL”)==0)
of1.write((char *)&p, sizeof(p));
}

XII/Computer Science 109


if1.close();
of1.close();
}

(e) Write a function in c++ to read and display the detail of all the users whose status is ‘A’ from a binary file
“USER.DAT” . Assuming the binary file “USER.DAT” is containing objects of class USER, which is defined as follows:
3
class user
{
int uid; // user id
char uname[20]; //user name
char status; //user type a/i
public:
void register(); //function to enter the content
void show(); //function to display all data member
char getstatus()
{
return status;
}
};
Ans:
void status()
{
ifstream if1;
if1.open(“user.dat”, ios::binary);
user u;
while(if1.read((char *)&u, sizeof(u)))
{
if( u.getstatus()==’A’)
u.show();
}
if1.close();
}

XII/Computer Science 110

You might also like