0% found this document useful (0 votes)
2K views114 pages

Sybba (Ca) Lab Book Sem-Iv

C++ is an object-oriented programming language that is an extension of C and adds features like classes, data binding, inheritance, and polymorphism to allow for code reuse and lower development costs. C++ is widely used to develop games, desktop applications, operating systems, browsers, databases, and other software that require high performance due to its closeness to hardware and ability to easily manipulate resources. C++ provides advantages over procedural programming by making code faster and easier to execute, maintain, and debug through a clear structure and ability to create reusable applications with less code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views114 pages

Sybba (Ca) Lab Book Sem-Iv

C++ is an object-oriented programming language that is an extension of C and adds features like classes, data binding, inheritance, and polymorphism to allow for code reuse and lower development costs. C++ is widely used to develop games, desktop applications, operating systems, browsers, databases, and other software that require high performance due to its closeness to hardware and ability to easily manipulate resources. C++ provides advantages over procedural programming by making code faster and easier to execute, maintain, and debug through a clear structure and ability to create reusable applications with less code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 114

Savitribai Phule Pune University

S. Y. B. B. A. (C. A.) Semester-IV


(CBCS 2019 Pattern)

Object Oriented Concepts Through CPP,


NODE JS and Advance PHP

CA-406: Lab Book

RollNo.: Division: SeatNo.:

Student Name:

CollegeName:

AcademicYear:
CERTIFICATE
This is to certify thatMr./Ms.
Seatnumber of S.Y.B.B.A.(C.A) Sem-IV has successfully
completed Laboratory Course (Object Oriented Concepts Through
CPP and NODE JS / Advance PHP ) in the year . He/She has
scoredmark out of 10 (for Labbook).

SubjectTeacher H.O.D./Coordinator

InternalExaminer ExternalExaminer
Editorial Board: Dr. D. Y. Patil Arts, Commerce and Science College, Pimpri.

Section-I: Object Oriented Concepts ThroughCPP

Mrs. Vidya Bankar.


Mrs. Reshma Masurekar.
Mrs. Ashwini Satkar.

Section-II: NODE JS

Mr. Bhushan Nikam.


Mr. Satish Mulgi.

Section-III: Advance PHP

Mrs. Madhuri Darekar.


Mrs. Trupti Kulkarni.

Reviewed By:

Dr. Ranjit Patil.


Mrs. SujataPatil.
Mrs. Sangeeta Nimbalkar.
Mrs. LeenaBhat.
Mr. Sudarshan Lakhdive.
Mrs. Shakila Siddavatam.
Mr. Shivendu Bhushan.
Introduction

1. About the workbook:

This workbook is intended to be used by S.Y.B.B.A. (C.A.) Semester-IV students for


Object Oriented Concepts Through CPP, NODE JS and Advance PHP assignments as
well as Add-on subject jQuerry. It is designed by considering all the practical topics
mentioned in the syllabus.

2. The objectives of this workbookare:

• Defining the scope of thecourse.


• Tobring theuniformityin thepracticalconductionandimplementationinallcolleges
affiliated toSPPU.
• To have continuous assessment of the course andstudents.
• Providing ready reference for the students during practicalimplementation.
• Providemoreoptionstostudentssothattheycanhavegood practicebefore facingthe
examination.
• Catering to the demand of slow and fast learners and accordingly providing the
practice assignments tothem.

3. How to use thisworkbook:

The workbook is divided into three sections. Section-I is related to CPP assignments,
Section-IIisrelatedtoNODEJSassignmentsandSection-IIIisrelatedto AdvancePHP
assignments.
Section-I CPP is divided into nine assignments.
Section-II NODE JS is divided into four assignments.
Section-III Advance PHP is divided into six assignments.
From Section-II and Section-III students have to perform practical assignments of
selected elective subject only.
Each assignment of all sections has three SETs-A, B and C. It is mandatory for students
to complete SET A and SET B in lab. Assignment also includes practice programs
which are expected to be solved by students as home assignments and to be evaluated
by subject teachers.

4. Instructions to thestudents

Please read the following instructions carefully and follow them during practical.
• Students are expected to carry this workbook every time they come to the lab for
computerpractical.
• Students should prepare for the assignment by reading the relevant material which is
mentioned in readyreference.
• Instructor will specify which problems to solve in the lab during the allotted slot and
student should complete them and get verified by the instructor. However, student
should spend additional hours in Lab and at home to cover all workbook assignments
ifneeded.
• Students will be assessed for each assignment on a scale from 0 to5.

Not done 0
Incomplete 1
Late Complete 2
Needs improvement 3
Complete 4
Well Done 5

5. Instruction to theInstructors

Make sure that students should follow above instructions.


• Explain the assignment and related concepts in around ten minutes using
whiteboard if required or by demonstrating thesoftware.
• Evaluate each assignment carried out by a student on a scale of 5 as specified
above by ticking appropriatebox.
• The value should also be entered on assignment completion sheet of the
respectivesection.

6. Instructions to the Labadministrator

You have to ensure appropriate hardware and software is made available to each student.
The operating system and software requirements on server side and also client side areas
given below:
• Operating System -Windows
• TurboC++
• WampServer
• Visual StudioCode
Assignment Completion Sheet
Section-I: Object Oriented Concepts Through CPP

Sr. Assignment Name Marks Teacher’s


No. (out of 5) Sign

1 Beginning with C++

2 Operators and Functions in C++

3 Classes and Objects

4 Constructors and Destructors

5 Inheritance

6 Polymorphism

7 Managing Console I/O operations

8 Working with Files

9 Templates
Total ( Out of 45 )

Total (Out of 5)

Instructor Signature:
Section-II: NODE JS

Sr. Assignment Name Marks Teacher’s


No. (out of 5) Sign

1 Node.js web server, modules &npm

2 File system

3 Events in node.js

4 Node.js with database


Total ( Out of 20 )

Total (Out of 5)

‘OR’

Section-III: Advance PHP

Sr. Assignment Name Marks Teacher’s


No. (out of 5) Sign

Introduction to Object Oriented Programming


1
in PHP
2 To study Web Techniques

3 XML

4 PHP with AJAX


Connecting Database using PHP & AJAX
5

6 PHP Framework - Druple


Total ( Out of 30 )

Total (Out of 5)

Instructor Signature:
Section-I

Object Oriented Concepts


Through CPP
Assignment No. 1: Beginning with C++

Introduction:
In 1982, Bjarne Stroustrup started to develop a successor to C with Classes at Bell labs, which he
named "C++", as it is an extension to C programming language. C++ runs on a variety of
platforms, such as Windows, Mac OS, and the various versions of UNIX. The major purpose of
C++ programming is to introduce the concept of object orientation to the C programming
language.

Procedural programming is about writing procedures or functions that perform operations on the
data, while object-oriented programming is about creating objects that contain both data and
functions.
Object-oriented programming has several following advantages over procedural programming:
• OOP is faster and easier toexecute.
• OOP provides a clear structure for the programs.
• OOP makes the code easier to maintain, modify anddebug.
• OOP makes it possible to create full reusable applications with less code and shorter
developmenttime.
• OOPmakesdevelopmentandmaintenanceeasierifcodegrowsasprojectsizegrows.
• OOP provide datahiding
• OOP provide ability to simulate real-world event much moreeffectively.

C++ is a general purpose, object oriented programming language. C++ has some additional
facilities to those in C such as classes, data binding, data hiding, inheritance, encapsulation,
polymorphism, default function argument etc. because of which it allows code to be r eused and
lowering development costs.

Real-World applications of C++:


• C++isclosetothehardware,caneasilymanipulateresourcesanditisfast,which makesit a
primary choice to develop the gamingsystems.

• C++ can be used to develop most of the GUI based and desktop applications easily.
Example: Adobe Photoshop, Win amp media player fromMicrosoft.

• C++ is also used in writing database management software. The two most popular
databases MySQL and Postgres are written inC++.

• The fact that C++ is a strongly typed and fast programming language makes it an ideal
candidate for writing operating systems. Apple OS X has some of its parts written in
C++. Similarly, some parts of the iPod are also written in C++. Most of the software from
MicrosoftisdevelopedusingC++(flavorsofVisualC++).ApplicationslikeWindows95, ME,
98; XP, etc. are written in C++. Apart from this, the IDE Visual Studio, Internet Explorer
and Microsoft Office are also written inC++.

1
• Browsers are mostly used for rendering purposes. Rendering engines need to be faster in
execution as most people do not like to wait for the web page to be loaded. With the fast
performance of C++, most browsers have their rendering software written in C++.Mozilla
Firefox internet browser is an open-source project and is developed completely in
C++.Google applications like Google File System and Chrome browser are written in
C++.

• C++ is useful in developing an application that requires high-performance image


processing, real-time physical simulations, and mobile sensor applications that need
high performance and speed. Maya 3D software from Alias system is developed in C++
and is used for animation, virtual reality, 3D graphics, andenvironments.

• Compilers of various high-level programming languages are written either in C or C++.


The reason is that both C and C++ are low-level languages that are close to hardware and
areabletoprogramandmanipulatetheunderlyinghardwareresources.

• C++ can be used for building higher-level applications with graphics libraries,
applicationstocommunicatewithnetworkdevicesandcomputernetworksimulatorsas well
as remote device systems and networkmanagement.

C++ Data types:


Data types in C++ are mainly divided into three types:
1. Primitive/Built-in Data Types: These data types are built-in or predefined data types
and can be used directly by the user to declare variables. Primitive data types available
in C++are:
• int
• char
• bool
• float
• double
• void
2. Derived Data Types: The data-types that are derived from the primitive or built-in data
types are referred to as Derived Data Types. These can be of four typesnamely:
• Function
• Array
• Pointer
• Reference
3. Abstract or User-Defined Data Types: These data types are defined by user itself.C++
provides the following user-defined data types:
• Class
• Structure
• Union
• Enumeration
• Typedef definedDataType

2
Simple C++ Program:

Example: C++ Hello world program to simply print "Hello World" on computer
screen.

// My first C++ program


#include <iostream.h>
int main()
{
cout<< "Hello World!";
return 0;
}

Fundamental components in C++ programs:

• Comments: // My first C++program


In above C++ program first line with double slash symbol indicate single line comment
and to indicate multiline comment programmer can enclose multiple lines in /* */ which
means these lines inserted by the programmer has no effect on the behavior of the
program. Programmers use comment to include short explanations or observations about
program.

• Header files: #include <iostream.h>


Lines beginning with ‘#’ are directives which are read and interpreted by preprocessor
before thecompilation of the C++ program begins. In above C++ program directive
#include <iostream.h>, instructs the preprocessor to include header fileiostream, which
allows to add the contents of the iostream.h file to the program to perform standard input
and output operations, such as accepting input through keyboard and writing the output of
program onscreen.

• Main function: int main()


The function named main is a special function in all C++ programs; it is the function
which called by operating system automatically when C++ program run. The execution of
all C++ programs begins with the main function, regardless of where the function is
actually located within the code.
Proper way of writing the main function in C++ is to use int return type for mainfunction.
C++ standards and specifications mention that the main function should always return
integervaluewhich can be‘0’or‘1’where‘0’isthestandard for“successfulexecutionof
theprogram”.

• Operator:
In C++ input and output are performed in the form of a sequence of bytes or more
commonly known as streams. Streams are of two types, if the direction of flow of bytes is
from the device like keyboard to main memory then it is an Input Stream and if the
direction of flow of bytes is from main memory to device like display screen then it is an
output stream.

3
C++ isable to input and output the built-in data types using the stream extraction
operator >> and the stream insertion operator << respectively. iostream stands for
standard input-output stream in C++, this header file contains definitions to objects like
cin, coutetc.

C++ Input and Output Operators:


InC++coutisapredefinedobjectwhichisaninstanceofostreamclass.Thecoutobjectis
connected to the standard output device, which usually is the display screen. The cout is
used in conjunction with output operator "<<" ("put to"), also known as stream insertion
operator to direct a value to standard output i.e. to display output on thescreen.
cinisapredefinedobjectwhichisaninstanceofistreamclass.Thecin objectisconnected tothe
standardinputdevice,whichusuallyisthekeyboard.The cinisusedin conjunction with input
operator ">>" ("get from"), also known as stream extraction operator to read a value from
standard input i.e. to accept input fromkeyboard.

Example: C++ program to illustrate use of input and output operators.


#include<iostream.h>
int main()
{
int num1, num2;
cout<<“\n Enter two numbers :”;
cin>>num1>>num2; //cascaded input operators
cout<<“\n Two numbersare:”<<num1<<“ ”<<num2; // cascaded outputoperators
return0;
}

Cascading of Input / Output Operators in C++:


The cascading of the input and output operators refers to the multiple use of input or
output operators in one statement. The statement using multiple output operators “<<” is
saidtobecascadingoutputoperatorand the statementusing multiple inputoperators“>>” is
said to be cascading inputoperator.
In above program, the cascaded input operators wait for the user to input two integer
values, where values are assigned from left to right, means first input value will get
assigned to num1 and second input value will get assigned to num2. The cascaded output
operator first displays the message “Two numbers are:”, then displays the value ofnum1
and after that it displays the value of num2.
It is observed that cascading of the input/output operator improves the readability and
reduces the size of the program.

• C++ Program Execution:


Create a C++ program using editor in Turbo C++.Save the program usingF2, give a
meaningful name to a source file which should reflects the purpose of the program, with
extension ".cpp". Compile the program using Alt + F9.Execute your C++ program by
pressingCtrl+F9.PressAlt+F5toviewtheoutputoftheprogramattheoutputscreen.

4
Practice Programs:

1. Write a C++ program to find factorial of a givennumber.


2. Write a C++ program to check whether a given number is even orodd.
3. Write a C++ program to check whether a given number is prime ornot.
4. Write a C++ program to check whether a given number is perfect ornot.
5. Write a C++ program to find largest and smallest number of 3 integer numbers. (Use
cascading of I/Ooperators.)

Set A:

1. Write a C++ program to generate multiplicationtable.


2. Write a C++ program to display first ‘n’ numbers of Fibonacciseries.
3. Write a C++ program to reverse anumber.
4. Write a C++ program to display Armstrong numbers between twointervals.
5. Write a C++ program to accept two integers and an arithmetic operator(+, -, *, /) from
user and performs the corresponding arithmetic operation and display the result. (Use
switchstatement)

Set B:

1. WriteaC++programtoprintthefollowingpattern.
A
B C
D E F
G H I J

2. Write a C++ program to print the followingpattern

*
* *
* * *
* * * *

3. WriteaC++programtocalculatefollowingseries:
(1*1)+(2*2)+(3*3)+ … +(n*n)

4. Write a C++ program to convert decimal number into binarynumber.

5
Set C:
1. Write a C++ program to print the followingpattern
*
* *
* * *
* * * *
* * * * *
2. WriteaC++programtocalculatefollowingseries:
1/1! + 2/2! + 3/3! + …. +n/n!

Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
3: Needs Improvement [ ] 4: Complete [ ] 5: WellDone [ ]

Signature of Instructor

6
Assignment No. 2: Operators and Functions in C++

Operators in C++:
C++ has a rich set of operators. All C operators are valid in C++ also. In addition to that
C++ introduces some new operators. We have already seen two such operators namely,
the insertion operator <<, and the extraction operator >>. Other new operators are:

Operator Name of Operator Function


:: Scope resolution operator To access global version of a variable
::* Pointer-to-member declarator To declare a pointer to a member of a class
->* Pointer-to-member operator To access a member using a pointer to the
object and a pointer to that member.
.* Pointer-to-member operator To access a member using object name and
a pointer to that member.
new Memory allocation operator To allocate memory for object.
delete Memory release operator To free allocated memory of an object.
endl Line feed operator To insert a new line character similar to ‘\n’
setw Field width operator To sets the field width to be used on output
operations.

Scope resolution operator:


In C++ the scope resolution operator ( :: ) is used for several reasons, some of them are:
• Accessing a global variable when there is a local variable with samename
• Defining a function outside aclass
• Accessing a class’s staticvariables
• Referring to a class inside anotherclass
• In case of multipleInheritance
Out of these, in this assignment we are going study first use of scope resolution operator.
If the global variable name is same as that of local variable name, the scope resolution
operator will be used to access the global variable.

Example: C++ program to illustrate use of Scope Resolution Operator (::)


#include<iostream.h>
int num=30; // Initializing a global variablenum
intmain()
{ int num=10; //Initializing the local variable num
cout<< "\nValue of global num is " <<::num;
cout<< "\nValue of local num is " <<num;
return 0;
}
Output:
Value of global num is 30
Value of local num is 10
In above program, we have two variables both named num with global & local scope. So,
to access global num variable in main function we need to use scope resolution operator
(i.e. ::num).

7
Memory management operators:
Allocating memory of a variable or an array run time is known as Dynamic Memory
Allocation(DMA).In C, dynamic memory management is handled by malloc( ) and free( )
function, but in C++ dynamic memory management is handled by using operators called
'new' and 'delete', where 'new' operator replaces malloc( ) and 'delete' operator replaces
free( ) in C. New and Delete operators manage memory effectively hence they are called
as memory management operators. In C++, we need to deallocate the dynamically
allocated memory manually after we have no use for the variable.
Syntax for anydatatype: pointer-variable = newdata-type;
delete pointer-variable;
Syntax foranarray: pointer-variable=newdata-type[size];
delete[size]pointer-variable;

Example: C++ program to illustrate use of memory management operators.


#include<iostream.h>
int main()
{ int*ptr; // declare an integerpointer
ptr =newint; // dynamically allocate memory for an int variable
int *arr_ptr=newint[5]; // create a memory for an array of 5integers
*ptr=100; // assign value to the memory
cout<<*ptr<<endl; // print thevalue stored in memory
inti; //variabledeclarationanywhereinthescopeisallowedinC++
for(i=0;i<5;i++)
{ arr_ptr[i]=i+1; //assign value to an arrayelements
}
cout<<arr_ptr[0]; // print first element of an array
deleteptr; // deallocate the memory
delete[]arr_ptr; //deallocatememoryofanarray
return0;
}
Output:
100
1
In above C++ program we have used pointer to allocate memory dynamically because
newoperatorreturnstheaddressofmemorylocation.Incaseofanarray,thenewoperator returns
the address of the first element of an array. Delete operator returns the memory to the
operating system which is known as memorydeallocation.

Advantages of the new operator over malloc() function:


• It does not use the sizeof() operator as it automatically computes the size of the
dataobject.
• It automatically returns the correct data type pointer, so does not need to use the
typecasting.
• Itallowstoinitializethedataobjectwhilecreatingthememoryspaceforobject.

8
Manipulators:
Manipulators are operators that are used to change formatting parameters on streams and
to insert or extract certain special characters, these are helping functions that can modify
the input/output stream. It does not mean that we change the value of a variable, it only
modifies the I/O stream using insertion (<<) and extraction (>>) operators. To use
manipulators in C++ program we need to include header file iomanip.h.
Following are some of the most widely used C++ manipulators:
1) endl:
endl is the line feed operator in C++. It acts as a stream manipulator whose purpose is
to feed the whole line and then point the cursor to the beginning of the next line. We
can use endl instead of ‘\n’ (newline character) for the same purpose.
Example:
cout<<“Good”<<endl<<”Morning”;
This will display “Good” and “Morning” on two separate lines.
2) setw:
setw manipulator function stands for set width. This manipulator is used to specify the
minimum number of character positions on the output field a variable will consume,
that is it sets the minimum field width on output. It is mostly used in output to right
justify numbers.
Example:
Sum=123;
cout<<setw(5) <<Sum;
This sum value is right justified within the field. 1 2 3
3) setfill:
setfill is used after setw manipulator. If a value does not entirely fill a field, then the
character specified in the setfill argument of the manipulator is used for filling the
fields. It specifies a character that is used to fill the unused portion of a field.
Example:
cout<<setw(10)<<setfill(‘*’)<<1234;
This will give you output: ******1234
4) setprecision:
The setprecision manipulator is used with floating point numbers. It is used to specify
the number of digits to be displayed after the decimal point of a float value.
Example:
PI=3.14159;
cout<<setprecision(2)<<PI;
Output: 3.14

Functions in C++:

Function prototyping:
The function prototype describes the function interface and it is used to give details to the
compiler about the number of arguments and about the required data types of a function
parameter, it also tells about the return type of the function. Using these details, the compiler
cross-checks the function signatures before calling it. If the function prototypes are not

9
mentioned, then the program may be compiled with some warnings. If some function is called
somewhere in a program, but its body is not defined yet, that is defined after the current line, then
it may generate problems. The compiler does not find what is the function and what is its
signature. In that case, we need to use function prototyping. If the function is defined before, then
we do not need to use prototypes.
Syntax:
return_type function_name (argument_list);
Example:
int multiplication (int x, int y, int z);
int addition (int, int, int); /*this is also acceptable at the place of declaration because at this
stage, the compiler only checks for the type of arguments when the function is called. */

Call by reference:
Call by value means pass arguments by value to the function and call by reference means pass
address of arguments to the function. In call by value, called function creates a new set of
variable and copies the values of arguments into them. The function does not have access to the
actual variables in the calling program. This mechanism is fine if the function does not want to
alter the values of the original variables in calling program.
To change values of the original variables in calling program we have to use call by reference. In
call by reference, address of the value is passed to the function, so actual and formal arguments
share the same address space. Hence, value changed by called function will get reflected in
calling function also.
Example: C++ program to illustrate use of call by reference.
void swap(int*, int*);
int main()
{ int a = 10, b=20; // initializevariables

cout<< "Before swapping"<<endl;


cout<< "a = " << a<<endl;
cout<< "b = " << b<<endl;

swap(&a,&b); // call function by passing variableaddresses

cout<< "\nAfter swapping" <<endl;


cout<< "a = " << a <<endl;
cout<< "b = " << b <<endl;
return 0;
}

// function definition to swap numbers


void swap(int* num1, int* num2)
{ intt;
t = *num1;
*num1 = *num2;
*num2 = t;
}
10
Output:
Beforeswapping
a =10
b =20
After swapping
a =20
b =10

In above program we are using call by reference, when the function is working with reference or
address it is actually working with original data.

Return by reference:
A function can also return a reference. A C++ program can be made easier to read and maintain
byusingreferencesratherthanpointers.Whenafunctionreturnsareference,itreturnsanimplicit pointer
to its return value. This way, a function can be used on the left side of an assignment statement.
Example: C++ program to illustrate use of return by reference.
#include<iostream.h>in
t n;
int& test();

int main()
{
test()=10;
cout<<n;
return 0;
}
int& test()
{
return n;
}
In above program return type of function test() is int& hence test() returns by reference. In
program, test() will not return value of n, instead it returns reference of the variable n. Since test()
is returning address of n it can be assigned a value, in our program it is 10. Hence program will
display output: 10.

Inline Function:
When the program executes the function call instruction, the CPU stores the memory address of
the instruction following the function call, copies the arguments of the function on the stack and
finallytransferscontroltothespecifiedfunction.TheCPUthenexecutesthefunctioncode,stores the
function return value in a predefined memory location/register and returns control to the
callingfunction.
This can become overhead if the execution time of function is less than the switching time from
thecallerfunctiontocalledfunction(callee).Forfunctionsthatarelargeand/orperformcomplex
tasks,theoverheadofthe functioncallisusuallyinsignificantcomparedtotheamountoftimethe
functiontakestorun.However,forsmall,commonly-usedfunctions,thetimeneededtomakethe

11
function call is often a lot more than the time needed to actually execute the function’s code. This
overhead occurs for small functions because execution time of small function is less than the
switching time.
C++providesaninlinefunctionfeaturetoreducethefunction calloverhead.Italsosaveoverhead of
arguments push/pop on the stack, while function calling. Inline function is a function that is
expandedinlinewhenitiscalled.Ifa functionisInline, the compilerplacesa copyofthecode of that
function at each point where the function is called at compile time and may make the program
executionfaster.
To inline a function, place the keyword inline before the function name and define the function
before any calls are made to the function. The compiler can ignore the inline qualifier, in case
defined function is more than a line.
Syntax:
inline return-type function-name(argument list)
{
//Function Body
}
Example: C++ program to illustrate use of inline function.
#include <iostream.h>
inline int square(int x)
{
return (x*x);
}
int main()
{
cout<< "Square (2): " <<square(2)<<endl;
cout<< "Square (3): " <<square(3)<<endl;
return0;
}
Output:
Square (2):4
Square (3):9

Default Arguments:
In C++ programming, we can provide default values for function parameters. A default argument
is a value provided in a function declaration for function parameters. If a function with default
arguments is called without passing arguments, then the default values are automatically assigned
by the compiler during compilation of program. However, if arguments are passed while calling
the function, the default arguments are ignored.

Example: C++ program to illustrate use of default arguments.


#include<iostream.h>
int sum(int a=10, int b=20);
int sum(int a, int b)
{
return (a+b);
}

12
int main()
{
cout<<sum()<<endl;
cout<<sum(50)<<endl;
cout<<sum(50,50)<<endl;
return 0;
}
Output:
30
70
100

In above program for first function call a=10 and b=20, for second function call a=50 and b=20
and for third function call a=50 and b=50.

Rules for default argument:


• Adefaultargumentischeckedfortypeatthetime ofdeclarationandevaluatedatthetime ofcall.
• Onlytrailingarguments canbedefaultvaluesandthereforeadddefaultsfromrighttoleft.
• We cannot provide default value to a particular argument in the middle of an argument
list.

Function declaration with default values:


int sum(int a, int b=20,intc=30); //allowed
int sum(int a=10,intb); //notallowed
int sum(int a=10, int b,intc=30); //notallowed
int sum(int a=10, int b=20,intc=30); //allowed
Default arguments are useful in situation where some arguments always have the same value. For
example bank interest may remain same for all customers for a particular period of deposit.

Practice Programs:
1. Write a C++ program to read two float numbers. Perform arithmetic operations like +, -,
*, / on these numbers using Inline Function. (Use manipulators)
2. Write a C++ program to store percentage of ‘n’ students and display it where ‘n’ is the
number of students entered by the user.(Use new and deleteoperator)
3. Write a C++ program to perform increment and decrement operation on integer number.
(Use inlinefunction)

Set A:
1. Write a C++ program to accept length and width of a rectangle. Calculate and display
perimeter as well as area of a rectangle by using Inlinefunction.
2. Write a C++ program to define power function to calculate x^y. (Use default value as 2
fory).
3. Write a C++ program to accept and display Bank_Account details as Acc_No,
Acc_holder_name, Addr, Contact_Number and Balance. Perform deposit of some amount
and display modified bank account details. (Usemanipulators)

13
Set B:
1. Write a C++ program to accept ‘n’ float numbers, store them in an array and print the
alternate elements of an array. (Use dynamic memoryallocation)
2. WriteaC++programtomodifycontentsofanintegerarray.(UseCall byreference)
3. Write a C++ program to calculate area and circumference of a Circle. (Use default
argument, scope resolution operator and manipulator.)

Set C:
1. Create a C++ program to maintain inventory of a book having details Title, Authors[],
Price, Publisher and Stock. Book can be sold, if stock is available, otherwise purchase will be
made. Write a menu driven program to perform followingoperation:
• Accept bookdetails.
• Salea book. (Sale contains number of copies to besold.)
• Purchaseabook. (Purchasecontainsnumberofcopiestobepurchased)
(Use dynamic memory allocation while accepting authordetails).

Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of Instructor

14
Assignment No. 3: Classes and Objects

Class:
A class in C++ is just an extension of a ‘structure’ used in the ‘C’ language. Class is a user-
defined data type. It actually binds the data and its related functions in one unit, they are called
members of the class.
A structure and a class differ a lot as a structure has limited functionality and features as
compared to a class. A structure is used to represent a record and a class can have both data
members and functions also. C++ expands the role of structure to create a class.
The Structure and Class, are almost similar in all respect except the significant one difference
that,structurebydefaulthaveallitsmemberas“public”,andclassbydefaulthaveallitsmember
“private”. Both a structure and a class provide a way to create a customized data type which can
be used further to create instances. Instance of structure is called ‘structure variable’ and instance
of a class is called‘object’.

Object:
An object is an instance of a Class. When a class is defined, no memory is allocated but when it
is instantiated (i.e. an object is created) memory is allocated.
When you define a class, you define a blueprint for a data type. This doesn't actually define any
data,butitdoesdefinewhattheclassnamemeans,thatis,whatanobjectofthe classwillconsist of and
what operations can be performed on such anobject.

Access Specifiers:
Access specifiers are used to implement an important feature of Object-Oriented Programming
known as Data hiding. Access specifiers in a class define how the data members and functions of
a class can be accessed. That is, it sets some restrictions on the class members not to get directly
accessed by the outside functions. This access restriction to the class members is specified by the
labeled public, private, and protected sections within the class body. The keywords public,
private, and protected are called access specifiers.
• public - members are accessible from outside the class but within aprogram.
• private - members cannot be accessed or viewed from outside the class. Only the class
and friend functions can access privatemembers.
• protected - members cannot be accessed from outside the class, however, they can be
accessed in inheritedclasses.
But if we do not specify any access specifier for the members inside the class then by default the
access specifier for the members will be private. Member functions of the class can access all the
data members and other member functions of the same class (private, public or protected)
directly by using their names.

15
Example: C++ program to demonstrate class, object, access specifiers and defining
member function inside class definition.
#include<iostream.h>
classSquare //class
{
public: //access specifier
floatside;
floatarea() //member function definition inside theclass
{ return(side*side);
}
};
intmain() // mainfunction
{
Squareobj; //object
obj.side=5.5; // accessing public data member outside class
cout<<"Square side length is: " <<obj.side<<"\n";
cout<< "Area of square is: " <<obj.area();
return 0;
}
Output:
Square side length is: 5.5
Area of square is: 30.25
A class definition starts with the keyword class followed by the class name; and the class body,
enclosedbya pairofcurlybraces.Aclassdefinitionmustbefollowedbyasemicolonoralistof
declarations.
InC++publickeyworddeterminestheaccessattributesofthemembersoftheclassthatfollows it, in
above program data member side and member function area arepublic.
A public member can be accessed from outside the class anywhere within the scope of the class
object hence side is accessible in main function through object of square class. You can also
specify the members of a class as private or protected as per the need.
Defining member functions inside and outside class definition:

Member functions are the functions, which have their declaration inside the class definition and
works on the data members of the class. The definition of member functions can be inside or
outside the definition of class. In both the cases, the function body remains the same; however,
the function header is different.

Member function definition inside the class definition:


If the member function is defined inside the class definition it can be defined directly. Member
function inside the class does not require to be declared first here we can directly define the
function. Defining a member function within the class definition declares the function by
default inline, even if you do not use the inline specifier. Above C++ program is an example of
member function definition inside theclass.

16
Member function definition outside the class definition:
If the member function is defined outside the class, then we have to use the scope resolution
operator ‘::’ along with class name and function name. Function name in the function header is
preceded by the class name and the scope resolution operator (: :).
The scope resolution operator informs the compiler what class the member belongs to. Defining a
member function outside a class requires the function declaration (function prototype) to be
provided inside the class definition.
Example:
#include<iostream.h>cl
ass Square
{
public:
float side;
float area();
};
float Square::area() //member function definition outside theclass
{ return (side*side);
}
int main()
{
Square obj;
obj.side=5.5;
cout<< "Square side length is: " <<obj.side<< "\n";
cout<< "Area of square is: " <<obj.area();
return 0;
}
Output:
Square side length is: 5.5
Area of square is: 30.25

Static data members and Static member functions:


Static data members:
Static data members are class members that are declared using the static keyword. The normal
variable is created when the function is called and its scope is limited, while the static variable is
created once and destroyed at the end of the program. These variables are visible within the class
but its lifetime is till the program ends. There is only one copy of the static data member in the
class, even if there are many class objects. This is because all the objects share the static data
member. To hold the count of objects created for a class, static data members are used.
The static data member is always initialized to zero when the first class object is created. While
definingastaticvariable,someinitialvalue canalsobeinitializedtothevariable.Typeandscope of each
static member variable must be defined outside the class definition using scope resolution
operator. This is necessary because the static data members are stored separately rather than as a
part of anobject.
Static data members are associated with the class itself rather than with any class object, hence
they are also known as class variables.

17
Static member functions:
Like static data member, we can also have static member functions. A static member function can
only access other static variables or functions present in the same class. To create a static member
function we need to use the static keyword while declaring the function.
Since static member variables are class properties and not object properties, to access them we
need to use the class name instead of the object name. A static member function can be called
even if no objects of the class exist and the static functions are accessed using class name and the
scope resolution operator ::. You could use a static member function to determine whether some
objects of the class have been created or not.
Example: C++ program to illustrate use of static data member and static member function.
#include <iostream.h>
class StaticDemo
{
private:
staticintnum; //declaration of static datamember
public:
staticvoidDisplay() //static member functiondefinition
{
cout<<"Value of num is : "<<num<<endl;//accessing static data member
}
};
int StaticDemo::num=10; //staticdatamemberdefinitionandinitializationoutsideclass
intmain()
{
StaticDemo::Display(); //call tostatic member function
return0;
}
Output:
Value of num is : 10

Array of objects:
An object of class represents a single record in memory, if we want more than one record of class
type, we have to create an array of object. An array which contains the class type of element is
called array of objects.
Array of objects contains the objects of the class as its individual elements. It is declared in the
same way as an array of any built-in data type.
Example: C++ program to illustrate use of array of objects.

#include<iostream.h>cl
ass Employee
{
int Emp_id;
char Name[20];
long Salary;

18
public:
void Accept()
{
cout<<"\n\tEnter Employee Id, Name and Salary : ";
cin>>Emp_id>>Name>>Salary;
}
void Display()
{
cout<<"\n"<<Emp_id<<"\t"<<Name<<"\t"<<Salary;
}
};
int main()
{
int i;
Employeeemp[3]; //CreatingArrayofobjectstostore3 Employeesdetails
for(i=0;i<3;i++)
{
cout<<"\nEnter details of "<<i+1<<" Employee";
emp[i].Accept();
}
cout<<"\nDetails of Employees";
for(i=0;i<3;i++)
emp[i].Display();
return 0;
}

Above program will accept and display details of 3 employees using array of objects.

Objects as a function argument:


In C++ we can pass objects of a class as arguments, the same way how we pass other variables.
To pass it we write the object name as the argument while calling the function. Object as function
argument is normally used to communicate between two objects.
The objects of a class can be passed as arguments to member functions as well as non-member
functions either by value or by reference.
Call by value: When an object is passed by value, a copy of the actual object is created inside
the function, to pass entire object into another function. This copy is destroyed when the
function terminates. Moreover, any changes made to the copy of the object inside the function
are not reflected in the actual object.
Call by reference: In this method, only a reference to that object (not the entire object) is
passed to the function. Thus, the changes made to the object within the function are also
reflected in the actualobject.

Whenever an object of a class is passed to a member function of the same class, its data
members can be accessed inside the function using the object name and the dot operator.
However, the data members of the calling object can be directly accessed inside the function
without using the object name and the dotoperator.

19
Function returning objects:
As we can pass entire object as an argument, similarly we can return object from the function.
We can return entire object from function by specifying its return type as class name just like
primary data-types. An object can be returned by a function using the return keyword.

Friend Function:
Data hiding is a fundamental concept of object-oriented programming. It restricts the access of
private members from outside of the class. Similarly, protected members can only be accessed
by derived classes and are inaccessible from outside. However, there is a feature in C++called
friend functions that break this rule and allow us to access private and protected data of a
class outside theclass.
For accessing the data, the declaration of a friend function should be done inside the body of a
class starting with the keyword friend. A friend function of a class is defined outside that class'
scope but it has the right to access all private and protected members of the class.
Even though the prototypes for friend functions appear in the class definition, friends are not
member functions. The function can be defined anywhere in the program like a normal C++
function. The function definition does not use either the keyword friend or scope resolution
operator.
Characteristics of a Friend Function:
• Friend function is not in the scope of the class to which it has been declared as afriend.
• It cannot be called using the object as it is not in the scope of thatclass.
• It can be invoked like a normal function without using theobject.
• It cannot access the member names directly and has to use an object name and dot
membership operator with the membername.
• It can be declared either in the private or the publicpart.
Example: C++ program to illustrate use of objects as a function argument, function
returning object and friend function.
# include <iostream.h>
class Demo
{
int x,y;
public:
void Accept();
// friend function declaration with objects as arguments and returning object
friend Demo sum (Demo, Demo);
void Display();
};
Demo sum(Demo obj1, Demo obj2)
{
Demo obj3;
obj3.x=obj1.x+obj2.x;
obj3.y=obj1.y+obj2.y;
returnobj3; //function returningobject
}

20
int main()
{
Demo obj1, obj2, obj3;
obj1.Accept();
obj2.Accept();
obj3=sum(obj1,obj2); //call to a friendfunction
obj3.Display();
return 0;
}

voidDemo::Accept()
{
cout<<"\nPlease enter value ofx and y :";
cin>>x>>y;
}

void Demo::Display()
{
cout<<"x= "<<x<<endl;
cout<<"y= "<<y<<endl;
}
Output:
Please enter value of x and y : 1020
Please enter value of x and y : 1020
x=20
y=40

Above C++ example give us an idea about the concept of a friend function, but it doesn’t show
any meaningful use. In the above example, we could have made "sum" as a member function of
the class instead of declaring it as a friend function to the class.
A more meaningful use would be operating on objects of two different classes. That's when the
friend function can be very helpful. A friend function can act as a bridge between two classes as
in the following example.

Example: C++ program to illustrate use of friend function for two classes.
#include <iostream.h>

class Square; // forward declaration of a class

class Rectangle
{
int width, height;
public:
void setvalue(int w, int h){width=w; height=h;}
friend void display(Rectangle &, Square &);
};

21
class Square
{
int side;
public:
void setvalue(int s){side=s;}
friend void display(Rectangle &, Square &);
};

void display(Rectangle &r, Square &s)


{
cout<< "Rectangle Area: " <<r.width * r.height<<endl;
cout<< "Square Area: " <<s.side * s.side<<endl;
}
int main ()
{
Rectangle rec;
rec.setvalue(5,10);
Square sq;
sq.setvalue(5);
display(rec,sq);
return 0;
}
Output:
Rectangle Area: 50
Square Area: 25
In above program friend function display() is friendly to Rectangle and Square class. It does not
belong to any class, so it can be used to access private data of Rectangle and Square class.

Friend Class:
Like friend function, a class can also be a friend of another class. A friend class can access all
the private and protected members of other class in which it is declared as friend. This is needed
when we want to allow a particular class to access the private and protected members of a class.
In order to access the private and protected members of a class into friend class we must pass on
object of a class to the member functions of friendclass.

Example: C++ program to illustrate use of friend class.


#include <iostream.h>
class A
{
int num;
public:
void setvalue(int i)
{
num=i;
}

22
friendclassB; //making B class, a friend class of Aclass

};
class B
{
public:
void display(A &a)
{
cout<<"Value of num is : "<<a.num;
}
};
int main()
{
A a_obj;
a_obj.setvalue(10);
B b_obj;
b_obj.display(a_obj);
return0;
}
Output:
Value of x is :10

In the above example, B class is a friend class of A class. In order to access the private
members of A class into B class we have explicitly pass an object of A class to the member
functions of Bclass.
This is similar to passing an object as function argument but the difference is, an object a_obj
we are passing as argument is of different class (A) and the calling object is of different class
(B).

Practice Programs:
1. Write a C++ program to create a class Customer with data members ID, Name, Addr and
Contact_No. Write member functions to accept and display customer information. (Use
scope resolution operator while defining memberfunctions)
2. Write a C++ program to create a class Employee with data members Emp_id, Name,
department, date_of_joining and Salary. Write member functions to accept and display
details of ‘n’ employees. (Use array ofobjects)
3. Write a C++ program to add two float numbers of two different classes using friend
function.

Set A:
1. Write a C++ program to create a class Student with data members Roll_No,
Student_Name, Class. Write member functions to accept and display Student information
alsodisplaycountofstudents.(UseStaticdatamemberandStaticmemberfunction)
2. Write a C++ program to calculate the average height of all the students of a class. The
numberofstudentsandtheirheightsareenteredbyuser. (Usearrayofobjects)

23
3. Write a C++ program to calculate maximum and minimum of two integer numbers of two
different classes.(Use friendfunction)

Set B:
1. Write a C++ program using class to accept and display ‘n’ Products information, also
display information of a product having maximum price. (Use array of objects and
dynamic memoryallocation)
2. Write a C++ program to create a class Distance with data members feet and inches. Write
member functions for the following:
a. To acceptdistance
b. To displaydistance
c. To add two distanceobjects
(Use object as a function argument and function returning object)
3. Write a C++ program to create two classes Array1 and Array2 with an integer array as a
data member. Write necessary member functions to accept and display array elements of
boththeclasses.Findanddisplaymaximumofboththearray.(UseFriendfunction)

Set C:
1. Write a C++ program to calculate multiplication of two integer numbers of two different
classes. (Use friend class)

Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of Instructor

24
Assignment No. 4: Constructors and Destructors

Constructor:
Aconstructorisa‘special’memberfunctionwhosetaskistoinitializetheobjectsofitsclass.Itis called
constructor because it constructs the values of data members of the class. Constructor is
automatically called when object of class iscreated.

Characteristics of Constructor:
• Constructors are declared as public memberfunction.
• Constructors are automatically invoked when an object of class iscreated.
• Constructor has same name as the classname.
• Constructors don’t have any returntype.
• Constructors can have defaultarguments.
• Constructorscannotbeinherited,thoughaderivedclasscancallthebaseclassconstructor.
• Constructors cannot bevirtual.
• Constructors cannot refer to theiraddresses.
• Constructors can implicitly call new and delete operators when memory allocation is
required.

Constructorscanbedefinedeitherinsidetheclassdefinitionoroutsideclassdefinition. If
constructors are defined outside class definition, then they can be defined using class name and
scope resolution::operator.

Example: To define Constructor inside the class.


class Number
{
int n;
public:
Number() //Constructor defined inside theclass
{
n=10;
}
};

Example: To define Constructor outside the class.


class Number
{
int n;
public:
Number(); //Constructordeclared
};
Number :: Number() //Constructor Defined outside theclass
{
n=10;
}
When a class contains a constructor, objects of the class will be initialized automatically.

25
Ex. Number Obj1;
Here Obj1 invokes constructor and initializes the data members of class Number.
If constructor is not defined in a class, C++ compiler generates a default constructor.

Types of Constructors:
1. DefaultConstructors:
The constructor that accepts no arguments is called as Default Constructor.

Example: To illustrate the use of Default Constructor.


#include<iostream.h>clas
s Number
{
int n;
public:
Number() //DefaultConstructor
{
n = 0;
}
};
int main( )
{
Number Obj1;
return 0;
}

Number Obj1 invokes Default constructor and initializes data member n to 0(zero).

2. ParameterizedConstructors:
The constructor that accepts arguments is called as Parameterized constructor. These
argumentsinitializeanobject,whenitiscreated.Theconstructorscanbecalledexplicitlyor
implicitly.
If more than one constructor is defined in a class, it is called as Constructor Overloading.

Example: To illustrate the use of Parameterized Constructor.


#include<iostream.h>clas
s Number
{
int n;
public:
Number(intx) //ParameterizedConstructor
{
n = x;
}
};
int main( )

26
{
Number Obj1=Number(50); // Explicitcall
NumberObj2(100); // Implicitcall
}
Number Obj1 & Number Obj2 invokes parameterized constructor and initializes data
member n to 50 & 100 respectively.

3. CopyConstructor:
A constructor that initializes an object using another object of the same class is
called as copy constructor. It takes a reference of object of the same class as its argument.
It copies data from one object to other by copying every member of an object with the
member of object passed as argument.

Example: To illustrate the use of Copy Constructor.


#include<iostream.h>clas
s Number
{
int n;
public:
Number (int x )
{
n = x;
}
Number(Number&N) //CopyConstructor
{
n= N.n;
}
};

int main( )
{
Number Obj1(10), Obj2(Obj1);
return 0;
}

Number Obj2(Obj1) defines the obj2 and at the same time initializes it to values of Obj1.

4. DynamicConstructor:
The constructor can be used to allocate memory while creating objects. Memory
can be allocated using new operator. Allocation of memory to objects at the time of their
construction is known as dynamic construction of objects.

Example: To illustrate the use of Dynamic Constructor.


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

27
class MyString
{
Char *Str;
int len;
public:
MyString ()
{
len=0;
Str=new char [len+1];
}
MyString (char *S)
{
len=strlen(S);
Str=new char [len+1];
Strcpy(Str, S);
}
void Concatenate(MyString &S1, MyString &S2)
{
len=S1.len+S2.len;
delete Str;
Str=new char [len+1];
Strcpy(Str, S1.Str);
Strcat(Str, S2.Str);
cout<<”String =”<<Str;
}
};
int main( )
{
MyString Obj1(“Computer”), Obj2(“Application”), Obj3;
Obj3.Concatenate(Obj1, Obj2);
return 0;
}

Constructors with default arguments


It is possible to define constructors with default arguments.
Example: To illustrate the use of Constructors with default arguments.
#include<iostream.h>clas
s Number
{
int m, n;
public:
Number(int x, int y=100 )
{
m = x;
n=y;
}

28
};
int main( )
{
Number Obj1(50);
}
Number Obj1 invokes constructor with default arguments and assigns the value 50 to the
variable x and 100 to y.

Dynamic initialization of Objects:


Class objects can be initialized dynamically i.e. initial value of an object can be provided
during run time. Dynamic initialization is used to provide various initialization formats, using
overloaded constructors.

Example: To illustrate the use of Dynamic initialization of Constructor


#include<iostream.h>cl
ass Number
{
int n;
public:
Number(int x)
{
n = x;
}
void display()
{
cout<<"n = " <<n;
}
};
int main( )
{
int a;
cout<<"\n Enter the value of a:";
cin>>a;
Number Obj(a);
Obj.display();
return 0;
}

Destructor:
Destructor is a member function that destroys an object which has been created by
constructor.Ifnewoperatorisusedtoallocatememoryintheconstructors,deleteoperatorisused to free
memory in the destructor. Destructor can clean up the storage which is no longer accessible.
A destructor is invoked implicitly when the object goes out of scope like:
a. the functionends.
b. the programends.

29
c. a block containing local variablesends.
d. a delete operator iscalled.

Characteristics of Destructor:
• Destructors have same name as the class name preceded by a tilde(~).
• Destructors doesn’t take any argument and doesn’t return anyvalue.

Example: To illustrate the use of Destructor.


#include<iostream.h>clas
s Number
{
public:
Number ( )
{
cout<<”\n Constructor called”;
}
~Number ( )
{
cout<<”\n Destructor called”;
}

};
int main( )
{
Number Obj1;
{
Number Obj2;
} //Destructor Ob2called
return0; //Destructor Ob1called
}
Note: Objects are destroyed in the reverse order of creation.

Practice Programs:
1. Write a C++ program to create a class ‘MyNumber’ with three data members of type
integer. Create and initialize the object using default constructor and parameterized
constructor. Also define copy constructor to copy one object to another. Write a C++
program to illustrate the use of aboveclass.

2. Write a C++ program to create a class ‘Fraction’ with integer data members numerator
and denominator. Create and initialize the object using parameterized constructor. Write a
member function to display addition two fraction objects.(Use the concept of dynamic
initialization ofobject)

3. Write a C++ program to create a class ‘MyArray’ which contains single dimensional
integer array of given size. Write a member function to display array in ascending order.
(UseDynamicConstructortoallocateandDestructortofreememoryofanobject)

30
Set A:
1. Write a C++ program to create a class ‘MyNumber’ with three data members of type
integer. Create and initialize the object using default constructor, parameterized
constructor and parameterized constructor with default value. Write a member function to
display average of given three numbers for allobjects.

2. Write a C++ program to create a class MyDate with three data members as dd, mm, yyyy.
Create and initialize the object by using parameterized constructor and display date in dd-
mon-yyyy format. (Input: 19-12-2014 Output: 19-Dec-2014).(Use the concept of dynamic
initialization ofobject)

3. WriteaC++programtocreatea class‘MyPoint’withtwointegerdatamembersasx& y. Define


copy constructor to copy one object to another. (Use Default and parameterized
constructor to initialize the appropriate objects) Write a C++ program to illustrate the use
of aboveclass.

Set B:
1. Write a C++ program to create a class ‘MyArray’ which contains single dimensional
integer array of given size. Write a member function to display even and odd numbers
from a given array. (Use Dynamic Constructor to allocate and Destructor to free memory
of anobject)

2. Write a C++ program to create a class ‘MyMatrix’ which contains two dimensional
integer array of size mXn. Write a member function to display sum of all elements of
entered matrix. (Use Dynamic Constructor for allocating memory and Destructor to free
memory of anobject)

3. Write a C++ program to create a class ‘MyVector’ with data members size & a pointer to
integer. The size of the vector varies so the memory should be allocated dynamically.
Create and initialize the object using default and parameterized constructor. Write a
member function to display the vector in the format (10, 20,30,….)

Set C:
1. Create a C++ class ‘Student’ with data members Rollno, Name,Number of subjects, Marks
of each subject (Number of subjects varies for each student). Writea parameterized
constructor which initializes rollno, name & Number of subjects and creates the array of
marksdynamically.Displaythedetailsofallstudentswithpercentageandclassobtained.

Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of Instructor

31
Assignment No. 5: Inheritance

Inheritance:
The mechanism of deriving a new class from an old class is called as Inheritance.
Inheritance allows a derived class to inherit the properties and characteristics from base class. A
classcanalsoinheritpropertiesfrommorethanoneclassorfrommorethanonelevel.Inheritance supports
the reusability as inheritance can extend the use of existing classes and eliminate redundantcode.

The class that inherits the properties from another class is called Sub class or Derived Class.
Theclasswhosepropertiesareinheritedbyderivedclassis calledSuperclassorBaseClass.
Syntax to define derived class:
class Derived_class_name : visibility_mode Base_class_name
{
//body of Derived class
};
Where,
Derived_class_name is the name of the sub class/derived class.
visibility_mode specifies the mode in which derived class can be inherited. For example: public,
private, protected. Default visibility mode is private.
Base_class_name is the name of the base class from which you want to inherit the sub class.

Modes of Inheritance
The following table represents the scope of the access specifier of the members of base class in
the derived class when derived in private, public & protected modes:

 Private mode: If a sub class is derived from a base class in private mode then both public
memberandprotected membersofthebaseclassbecomesPrivateinderivedclass.Private
members of the base class never get inherited in subclass.
 Public mode: If a sub class is derived from base class in public mode then the public
memberofthebase classremainspublicinthederivedclassandprotectedmembersofthe base
class remains protected in derived class. Private members of the base class never get
inherited in subclass.
 Protected mode: If a sub class is derived from a base class in protected mode then both
public member and protected members of the base class becomes protected in derived
class. Private members of the base class never get inherited in subclass.

32
Types of Inheritance:
1. SingleInheritance:
A derived class with only one base class is called as Single Inheritance.

Syntax to define derived class:


class Derived_class: visibility_mode Base_class
{
//Body of Derived class
};

Example: To illustrate the use of Single Inheritance using public derivation.


#include<iostream.h>cl
ass Base
{
int x; //private; not inheritable
public:
int y; //public;inheritable
void setValues()
{
x=10;
y=20;
}
int getx()
{
return x;
}
}
class Derived :publicBase // publicderivation
{
int z;
public:
void add()
{
Z=getx() + y;
}
void display()
{
cout<<”\n x= “<<getx();
cout<<”\n y= “<<y;
cout<<”\n Addition : “<<z

33
}
}
int main()
{
Derived D;
D.setValues();
D.add();
D.display();
}
DerivedclassisapublicderivationofthebaseclassBase.So,Derivedclassinheritsallthepublic members
of class Base and retains their visibility. Thus public members of the Base class are also public
members of the Derived class. The private members of the Base class cannot be inherited by
classDerived.

Example: To illustrate the use of Single Inheritance using private derivation.


#include<iostream.h>cl
ass Base
{
int x; //private; not inheritable
public:
int y; //public; ready forinheritance
void setValues()
{
x=10;
y=20;
}
int getx()
{
return x;
}
}
class Derived :privateBase // privatederivation
{
int z;
public:
void add()
{
D.setValues();
z=getx() + y;
}
void display()
{
cout<<”\n x= “<<getx();
cout<<”\n y= “<<y;
cout<<”\n Addition : “<<z

34
}
}
int main()
{
Derived D;
//D.setValues(); wont work
D.add()
D.display();
}
Derived class is a private derivation of the base class Base. So, Derived class inherits only public
members of base class Base as private and retains their visibility. The private members of the
Base class cannot be inherited by class Derived.

2. MultipleInheritance:
A derived class with several base classes is called as Multiple Inheritance.

Syntax to define derived class:


class Derived_class : visibility_mode Base_class1, visibility_mode Base_class2,..
{
//Body of Derived class
};
A class is derived with multiple base classes. The number of base classes are separated by a
comma (‘, ‘). Visibility mode for every base class must be specified.

3. MultilevelInheritance:
The mechanism of deriving a class from another derived class is called as
Multilevel inheritance.

35
Syntax to define derived class:
class Intermediate_class : visibility_mode Base_ class
{
//Body of Intermediate class
};
class Derived_class : visibility_mode Intermediate_class
{
//Body of Derived class
};

4. HierarchicalInheritance:
More than one derived classes inherits the features from a single base class is called as
Hierarchical Inheritance i.e. more than one derived classes are created from a single base class.

Syntax to define derived class:


class Derived_class1 : visibility_mode Base_class
{
//Body of Derived class
};
class Derived_class2 : visibility_mode Base_class
{
//Body of Derived class
};
class Derived_class3 : visibility_mode Base_class
{
//Body of Derived class
};

5. HybridInheritance:
More than one type of inheritance is combined to form Hybrid Inheritance.
For Ex.: Combination of Hierarchical inheritance and Multiple Inheritance.

36
Syntax to define derived class:
class Intermediate_class1 : visibility_mode Base_ class
{
//Body of Intermediate class1
};
class Intermediate_class2 : visibility_mode Base_ class
{
//Body of Intermediate class2
};
class Derived_class : visibility_mode Intermediate_class1, visibility_mode Intermediate_class2
{
//Body of Derived class
};

Virtual baseclass:
Severalpathsexisttoa derivedclassfromthesamebaseclassi.e.a derivedclasscanhave
duplicate sets of members inherited from a single base class. This introduces ambiguity and it
should beavoided.
Duplication ofinheritedmembersduetomultiplepathsisavoidedbymakingthecommon base
class as virtual base class. This is achieved by preceding the base class name with the
keywordvirtual.
When a class is made a virtual base class, necessary care is taken so that only one copy of
that class is inherited, regardless of the number of paths exist between virtual base class and a
derived class.

37
Syntax:
class Base_class
{
//Body of Base class
};
class Intermediate_class1 : virtual visibility_mode Base_ class
{
//Body of Intermediate class1
};
class Intermediate_class2 : visibility_mode virtual Base_ class
{
//Body of Intermediate class2
};
class Derived_class : visibility_mode Intermediate_class1, visibility_mode Intermediate_class2
{
//Body of Derived class
};
Note:Virtual and visibility mode can be used in either order.

Example: To illustrate the use of virtual base class.


Calculating marks and grade of student using virtual base class.

#include<iostream.h>
#include<conio.h>
#include<string.h>in
tn;
class student
{
protected:
int rno;
char name[20];
public:
void acceptinfo()
{
cout<<"\nRoll no: ";
cin>>rno;
cout<<"Name: ";
gets(name);
}
void displayinfo()
{
cout<<"\nRoll no: "<<rno <<"\nName: "<<name;
}
};

38
class test:public virtual student
{
protected:
int marks1, marks2;
public:
void acceptmark()
{
cout<<"Mark 1: ";
cin>>marks1;
cout<<"Mark 2: ";
cin>>marks2;
}
void displaymark()
{
cout<<"\nMark 1: "<<marks1<<"\nMark 2: "<<marks2;
}
};
class sport : public virtual student
{
protected:
int score;
public:
void acceptscore()
{
cout<<"Score:";
cin>>score;
}
voiddisplayscore()
{
cout<<"\nScore: "<<score;
}
};
class result:public test,public sport
{
protected:
int totalmarks, perc;
char grade[20];
public:
void calctotal();
void accept()
{
acceptinfo();
acceptmark();
acceptscore();
calctotal();
}

39
void display()
{
displayinfo();
displaymark();
displayscore();
cout<<"\nTotal: "<<totalmarks
<<"\nPercentage: "<<perc<<" %"
<<"\nGrade: "<<grade<<"\n";
}
int gettotal()
{
return totalmarks;
}
};
void result::calctotal()
{
totalmarks=marks1+marks2+score;
perc=(totalmarks*100)/300;
if(perc>=75)
strcpy(grade,"Distinction");
else if(perc>=60 && perc <75)
strcpy(grade,"First Class");
else if(perc>=35 && perc<60)
strcpy(grade,"Pass Class");
else
strcpy(grade,"Fail");
}

int main()
{
int ch, i, j;
clrscr();
do{

cout<<"\nMain Menu\n"
<<"\n1. Accept details"
<<"\n2. Display details in ascending order"
<<"\n3. Exit\n"
<<"\nEnter your option: ";
cin>>ch;
switch(ch)
{
case 1: cout<<"\nDetails of how many students do you want ot enter: ";
cin>>n;
result r[10];
cout<<"\nEnter the following details";

40
for(i=0; i<n; i++)
{
r[i].accept();
}
break;
case 2: cout<<"\nThe details are\n";
for(i=0; i<n; i++)
{
r[i].display();
}
getch();
break;
case 3: exit(0);
}
}while(ch!=3);
return 0;
}
Abstract class:
An abstract class is not used to create objects. An abstract class is designed only to acts
as a base class.

Constructor in derived class:


While using constructors during inheritance, is that, as long as a base class constructor
doesnottakeanyarguments,thederivedclassneednothaveaconstructorfunction.However,ifa base
class contains a constructor with one or more arguments, then it is mandatory forthe derived class
to have a constructor and pass the arguments to the base class constructor. While applying
inheritance, we usually create objects using derived class. Thus, it makes sense for the derived
class to pass arguments to the base class constructor. When both the derived and base class
containsconstructors,thebaseconstructorisexecutedfirstandthentheconstructorinthederived class
isexecuted.
In case of multiple inheritance, the base class is constructed in the same order in which they
appear in the declaration of the derived class. Similarly, in a multilevel inheritance, the
constructor will be executed in the order of inheritance.
The derived class takes the responsibility of supplying the initial values to its base class. The
constructor of the derived class receives the entire list of required values as its argument and
passesthemontothebaseconstructorintheorderin whichtheyaredeclaredinthederived class. A base
class constructor is called and executed before executing the statements in the body of the
derivedclass.
Syntax to define derived class constructor:
Derived-Constructor (ArgList2, ArgList2,…….ArgListN,ArgListD): Base1(ArgList1),
Base2(ArgList2)……. BaseN(ArgListN)
{
// Body of Derived Constructor
}

41
Practice Programs:
1. Create a base class Employee(empcode, empname). Derive the classes
Manager(designation, club_dues), Scientist(deptname, publications) and Labourer from
Employee class. Write a C++ menu drivenprogram
i. to accept the details of ‘n’employees
ii. to display theinformation
iii. to display details of manager with designation as ”GeneralManger”.

2. Create two base classes Learning_Info( Roll_No, Stud_Name, Class, Percentage) and
Earning_Info(No_of_hours_worked, Charges_per_hour). Derive a class Earn_Learn_info
from above two classes. Write necessary member functions to accept and display Student
information. Calculate total money earned by the student. (Use constructor in derived
class)

Set A:
1. DesignabaseclassProduct(Product_Id,Product_Name,Price).DeriveaclassDiscount
(Discount_In_Percentage) from Product. A customer buys ‘n’ products. Write a C++
program to calculate total price, totaldiscount.

2. DesignaBaseclassCustomer(name,phone-number).DeriveaclassDepositor(accno,
balance) from Customer. Again derive a class Borrower (loan-no, loan-amt) from
Depositor. Write necessary member functions to read and display the details of ‘n’
customers.

Set B:
1. Design two base classes Personnel (name, address, email-id, birth date) and Academic
(marksintenth,marksintwelth,classobtained).DeriveaclassBio-data fromboththese
classes. Write a C++ program to prepare a bio-data of a student having Personnel and
Academicinformation.

2. Design a base class Employee (emp-code, name). Derive two classes as Fulltime (daily
rate, number of days, salary) and Parttime (number of working hours, hourly rate, salary)
from Employee. Write a C++ menu driven programto:
i. Accept the details of ‘n’ employees and calculate thesalary.
ii. Display the details of ‘n’employees.
iii. Search a givenEmployee.

3. Create a base class Student(Roll_No, Name) which derives two classes


Academic_Marks(Mark1, Mark2, Mark3) and Extra_Activities_Marks(Marks). Class
Result(Total_Marks, Grade) inherits both Academic_Marks and Extra_Activities_Marks
classes. (Use Virtual BaseClass)
Write a C++ menu driven program to perform the following functions:
i. Build a mastertable.
ii. Calculate Total_marks andgrade.

42
Set C:
1. Create a base class Student(Roll_No, Name, Class) which derives two classes
Internal_Marks(IntM1, IntM2, IntM3, IntM4, IntM5) and External_Marks(ExtM1 ExtM2,
ExtM3, ExtM4, ExtM5). Class Result(T1, T2, T3, T4, T5) inherits both Internal_Marks
and External_Marks classes. (Use Virtual BaseClass)
Write a C++ menu driven program to perform the following functions:
i. To Accept and display studentdetails
ii. Calculate Subject wise total marksobtained.
iii. Check whether student has passed in Internal and External Exam of each subject.
Also check whether he has passed in respective subject or not and display result
accordingly.

Assignment Evaluation
0: Not Done[] 1: Incomplete[] 2: Late Complete []
3: Needs Improvement[] 4: Complete[] 5: Well Done []

Signature of Instructor

43
Assignment No. 6: Polymorphism

Polymorphism:
Polymorphism means ‘One name, multiple forms’.

Compile time Polymorphism:


Compiler selects appropriate function for a particular call at compile time is called as
Compile time Polymorphism. It is also called as early binding or static binding or static linking.
Compile time Polymorphism is achieved by using function overloading and operator overloading.

Function Overloading:
Same function name is used to create a function that perform variety of different tasks is
called as Function Overloading.
A family of functions can be designed with same function name but with different
argument list. The function performs different operations depending on the argument list in the
function call. The appropriate function to be invoked is determined by checking the number and
type of arguments.

Example: C++ program to find volume of cube, cylinder and rectangle using function
overloading.
#include<iostream.h>
#include<conio.h>int
volume(int);
double volume(double,int);
long volume(long,int,int);
int main()
{
clrscr();
int x,s,h,b;

44
double y,r;
long z,l;
cout<<"\nEnter the value for s: ";
cin>>s;
x=volume(s);
cout<<"\nVolume of cube: "<<x;

cout<<"\nEnter the value for r and h: ";


cin>>r>>h;
y=volume(r,h);
cout<<"\nVolume of cylinder: "<<y;

cout<<"\nEnter the value for l,b and h: ";


cin>>l>>b>>h;
z=volume(l,b,h);
cout<<"\nVolume of rectangle: "<<z;
getch();
return 0;
}
int volume(int s)
{
return (s*s*s);
}
double volume(double r,int h)
{
return (3.14*r*r*h);
}
long volume(long l,int b,int h)
{
return (l*b*h);
}

Example: C++ program to find area of triangle, circle, and rectangle using function
overloading.
#include<iostream.h>#i
nclude<conio.h> float
area(float r)
{
return(3.14*r*r);
}

float area(float b,int h)


{
return(0.5*b*h);
}

45
int area(int l,int b)
{
return(l*b);
}
void disp(float m)
{
cout<<"\nArea: "<<m;
}
int main()
{
clrscr();
int m,n;
floatl,a;
cout<<"CIRCLE:\n";
cout<<"Enter the Radius:";
cin>>l;
a=area(l);
disp(a);
cout<<"\n\nTRIANGLE\n:";
cout<<"EntertheBaseandHeight:";
cin>>l>>m;
a=area(l,m);
disp(a);
cout<<"\n\nRECTANGLE:\n";
cout<<"EntertheLengthandBreadth:";
cin>>m>>n;
a=area(m,n);
disp(a);
getch();
return 0;
}

Operator Overloading:
In Operator Overloading, an operator is overloaded to give user defined meaning to it.
Overloaded operator is used to perform operation on user-defined data type. Although semantics
ofanoperatorcanbeextended,butcannotchangeitssyntax,thegrammaticalrulesthatgovernits use such
as the number of operands, precedence andassociativity.
For example '+' operator can be overloaded to perform addition on various data types, like for
integer, float etc.
Operator overloading is achieved using the operator function. The operator function is
created using operator keyword.
Syntax of operator function:
returntype classname :: operator Op (argument List)
{
//Function Body
}

46
where, returntype is the type of value returned by the specified operation.
op is the operator being overloaded. op is preceded by the keyword operator. ‘operator op’ is the
function name.
The argument list will depend on whether the operator is unary or binary and whether the
function is a member function or friend function.

The operator function can be either member function or friend function.


• A friend function will have one argument for unary operators and two for binary
operators.
• A member function has no arguments for unary operators and only one for binary
operators because the object used to invoke the member function is passed implicitly and
therefore is available for memberfunction.

Restrictions on Operator overloading while implementing operator overloading:


1. Precedence and Associativity of an operator cannot bechanged.
2. Arity(numbersofOperands)cannotbechanged.Unaryoperatorremainsunary,binary
remains binaryetc.
3. No new operators can be created, only existing operators can beoverloaded.
4. Cannotredefinethemeaningofaprocedure.Youcannot changehowintegersareadded.
5. There are few operators in C++ that cannot be overloaded suchas
• ternary operator?:,
• sizeof,
• scope resolution operator::
• membership operators . and .*.

Overloading Unary operators:


Unary operators are Increment, Decrement and unary minus which can be overloaded.

Example: To overload the operator unary minus- to negate the numbers.


#include<iostream.h>#i
nclude<conio.h> class
Numbers
{
int x;
int y;
public:
void accept(int a,int b)
{
x=a;
y=b;
}
void display()
{
cout<<"x="<<x<<"\n";
cout<<"y="<<y<<"\n";
}

47
void operator -()
{
x=-x;
y=-y;
}
};
int main()
{
Numbers N;
clrscr();
N.accept(10,20);
N.display();
-N;
cout<<"\nAfter unary minus handled variable are:"<<"\n";
N.display();
return(0);
}

Overloading Unary operators using friend function:

Example: To overload operator unary minus- to negate the numbers using friend function.
#include<iostream.h>#i
nclude<conio.h> class
Numbers
{
int x;
int y;
public:
void accept(int a,int b)
{
x=a;
y=b;
}
void display()
{
cout<<"x="<<x<<"\n";
cout<<"y="<<y<<"\n";
}
friend void operator -(Numbers &Obj)
{
Obj.x=-Obj.x;
Obj.y=-Obj.y;
}
};

48
int main()
{
Numbers N;
clrscr();
N.accept(10,20);
N.display();
operator –(N);
cout<<"\nAfter unary minus handled variable are:"<<"\n";
N.display();
return(0);
}

Overloading increment operator:


The increment operator ++ is used in two ways: pre-increment (++d) and post-increment(d++).
To distinguish between pre and post increment operator overloading, dummy parameter of type
int in the function heading of the post-increment operator function is used. Decrement operator
can be overloaded similarly.
void operator++()
{
++x;
++y;
}
void operator++(int)
{
x++;
y++;
}

Overloading Binary operators:


Arithmetic operators are most commonly used operator in C++. Almost all arithmetic(+, - , * ,/)
operators are overloaded to perform arithmetic operation on user-defined data type.
Example: To Overload Binary ‘+’ operator using member function
#include<iostream.h>#i
nclude<conio.h>
classNumbers
{
int x;
public:
void accept(int a)
{
x=a;
}
void display()
{
cout<<"x="<<x<<"\n";
}

49
Numbers operator +(Numbers Obj)
{
Numbers temp;
temp.x=x+Obj.x;
return temp;
}
};
int main()
{
clrscr();
Numbers N1,N2,N3;
N1.accept(100);
N2.accept(200);
cout<<"\nFirst number:";
N1.display();
cout<<"\nSecond number:";
N2.display();
cout<<"\nOperations:\n\n";
cout<<"\nAddition:";
N3=N1+N2;
N3.display();
getch();
return(0);
}

Example: To Overload Binary operator ‘+’ using friend function.


#include<iostream.h>#i
nclude<conio.h>
classNumbers
{
int x;
public:
void accept(int a)
{
x=a;
}
void display()
{
cout<<"x="<<x<<"\n";
}
friend Numbers operator +(Numbers Obj1,Numbers Obj2)
{
Numbers temp;
temp.x=Obj1.x+Obj2.x;
return temp;

50
}
};
int main()
{
clrscr();
Numbers N1,N2,N3;
N1.accept(100);
N2.accept(200);
cout<<"\nFirst number:";
N1.display();
cout<<"\nSecond number:";
N2.display();
cout<<"\nOperations:\n\n";
cout<<"\nAddition using friend function:";
N3=operator+(N1,N2);
N3.display();
getch();
return(0);
}

Overloading insertion and extraction operators:


Overloading insertion(<<) operator and extraction (>> ) operator is used to input and
output objects using stream class library in the similar way as built in data types.
<<operator is overloaded with ostream class object cout to print primitive type value to the
screen. Similarly <<operator is overloaded in class to print user-defined type to screen.
>>operator is overloaded with istream class object cin to read primitive type values from the
user. Similarly >>operator is overloaded in class to read user-defined type value.

Example: To Overload <<&>> operator.


#include<iostream.h>
#include<conio.h>
#include<fstream.h>
class Numbers
{
int x;
public:
friend ostream& operator <<(ostream &,Numbers &);
friend istream& operator >>(istream &,Numbers &);
};
ostream & operator <<(ostream &out,Numbers &d)
{
out<<"\nValue of x:"<<d.x;
return out;
}
istream & operator >>(istream &in,Numbers &d)
{

51
in>>d.x;
return in;
}
int main()
{
Numbers N;
cout<<"Input";
cin>>N; //invokes operator >>( )function
cout<<"Output";
cout<<N; //invokes operator <<( )function

getch();
return 0;
}
}

String manipulation using Operator Overloading:


Relational operators like ==, > ,>=, <, <=, !, != are used to compare two user-defined
objects.

Example: To compare two strings are equal or not


#include<iostream.h>#i
nclude<conio.h>
#include<string.h>
classmystring
{
char str[30];
int len;
public:
mystring(char *s)
{
strcpy(str,s);
}
int operator ==(mystring ms)
{
if(strcmp(str,ms.str)==0)
return 0;
else
return 1;
}
};
int main()
{
char s1[10],s2[10];
clrscr();
cout<<"Enter first string"<<"\n";

52
cin>>s1;
cout<<"Enter secondstring"<<"\n";
cin>>s2;
mystring obs1(s1),obs2(s2);
if(obs1==obs2)
cout<<"\nGiven strings are not same"<<"\n";
else
cout<<"\nGiven strings are same"<<"\n";
getch();
return(0);
}

Run time Polymorphism:


An appropriate member function is selected for a particular call while the program is
running (at run time) is called as Run time Polymorphism. It is also called as late binding or
dynamic binding or dynamic linking. Run time Polymorphism is achieved by using Virtual
Function.

this pointer:
Keyword this is used to represent an object that invokes a member function. this is a pointer that
pointstotheobjectfor whichthisfunctionwascalled.Thisuniquepointerisautomaticallypassed to a
member function when it is called. The pointer ‘this’ acts as an implicit argument to all the
memberfunctions.
Example1: To illustrate the use of this pointer.
#include<iostream.h>cl
ass Test
{
int x;
public:
void setX (int x)
{
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};
int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}

53
Example2: To illustrate the use of this pointer.
#include<iostream.h>#i
nclude<conio.h> class
Test
{
int x;
public:
Test(int x)
{
this->x = x;
}
Test& maximum(Test& T)
{
if(T.x >= x)
return T;
else
return * this;
}
void print() { cout << "x = " << x << endl; }
};

int main()
{
Testobj1(50),obj2(30);
obj1.print();
obj2.print();
Testobj3=obj1.maximum(obj2);
obj3.print();
getch();
return 0;
}
Note: return * this will return the object that invoked the function.

Virtual Function:
When same function name is used in both the base and derived classes, the function in
baseclassdeclaredasvirtualusingthekeywordvirtual precedingitsnormaldeclarations.Whena
function is made virtual, C++ determines which function to use at run time based on the type of
object pointed to by the base pointer, rather than the type of the pointer. By making the base
pointertopointtodifferentobjects,differentversionsofvirtualfunctionscanbeexecuted.
RuntimePolymorphismisachievedonlywhenaVirtualFunctionisaccessedthrougha
pointer to the baseclass.

Example: To illustrate the use of virtual function.


class Base
{
public:

54
void Display()
{
cout<<”\n Display Base”;
}
virtual void show()
{
cout<<”\n Show Base”;
}

};
class Derived: public Base
{
public:
void Display()
{
cout<<”\n Display Derived”;
}
void show()
{
cout<<”\n Show Derived”;
}
};

int main()
{
Base B;
Derived D;
Base*Bptr;

Bptr =&B;
Bptr->Display(); //Calls Baseversion
Bptr->Show(); //Calls Baseversion

Bptr = &D;
Bptr->Display(); //Calls Baseversion
Bptr->Show(); //Calls Derivedversion

return(0);
}

Note: When Bptr is pointing to derived class object D, the statement


Bptr->Display();
calls only the function associated with Base; whereas the statement
Bptr->Show();
calls the Derived version of Show(). Because Show() function from the base class is declared as
virtual.

55
Pure virtual function:
A virtual function equaled to zero is called as pure virtual function It is also called as “do-
nothing” function. It is a function declared in a base class that has no definition relative to the
base class.
Syntax:
virtual void display()=0;

A class containing such pure function is called as an abstract class.

Practice Programs:
1. WriteaC++program tosortintegerandfloatarrayelementsinascendingorderbyusing
function overloading.

2. Create a class College containing data members as College_Id, College_Name,


Establishment_year, University_Name. Write a C++ program with following member
functions:
i. To accept ‘n’ Collegedetails
ii. To display College details of a specifiedUniversity
iii. TodisplayCollegedetailsaccordingtoaspecifiedestablishmentyear
(Use Array of Object and Functionoverloading)

3. Create a class Fraction containing data membersas Numerator and Denominator. Write
a C++ program to overload operators ++, -- and * to increment, decrement a Fraction and
multiply two Fraction respectively. (Use constructor to initialize values of an object).

4. Create a base class Conversion. Derive three different classes Weight (Gram, Kilogram),
Volume(Milliliter, Liter), Currency(Rupees, Paise) from Conversion class. Write a C++
programtoperformread,convertanddisplayoperations.(UsePurevirtualfunction)

Set A:
1. Write a C++ program to calculate area of cone, sphere and circle by using function
overloading.

2. Create a C++ class Employee with data members E_no, E_Name, Designation andSalary.
Accept two employees information and display information of employee having
maximum salary. (Use thispointer)

3. Write a C++ program to create a class Integer. Write a C++ program to implement
necessarymemberfunctionstooverloadtheoperatorunarypreandpostdecrement‘--’for an
integernumber.

4. Create a C++ class Integer that contains one integer data member. Overload following
binary operators (+,-,*,/).

56
5. ConsideraclassPointcontainingxandycoordinates.WriteaC++programtoimplement
necessary functions to accept a point, to display a point and to find distance between two
points using operator overloading (-). (Use friendfunction)

Set B:
1. Create class Person which contains data member as Passport_Id, Person_name,
Nationality,Gender,Date_of_Birth,Date_of_Issue,Date_of_expiry.Writeac++program to
perform following memberfunctions:
i. Enter details of allpersons
ii. Display passport details of oneperson
iii. Display passport details of allpersons
(Use Function overloading and Array of object).

2. Create a class Date with members as dd, mm, yyyy. Write a C++ program for overloading
operators >> and <<to accept and display aDate.

3. Create a class MyString which contains a character pointer (using new operator). Write a
C++ program to overload followingoperators:
i. < To compare length of twostrings
ii. != To check equality of twostrings
iii. + To concatenate twostrings

4. Create a base class Shape. Derive three different classes Circle, Rectangle and Triangle
from Shape class. Write a C++ program to calculate area of Circle, Rectangle and
Triangle. (Use pure virtual function).

Set C:
1. Create a class MyString which contains a character pointer (Use new and delete
operator).Write a C++ program to overload followingoperators:
i. ! To change the case of each alphabet from givenstring
ii. [] To print a character present at specified index

Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of Instructor

57
Assignment No. 7: Managing Console I/O Operations

Stream is a sequence of bytes. It represents a device on which input and output operations are
performed. C++ provides standard iostream library to operate with streams. The iostream is an
object-oriented library which provides Input/Output functionality using streams. C++ stream
classes are as follows:

I/O Stream Meaning Description


ios General It contains basic facilities that are used by all other input
Input/Output & output classes. Declares constants & functions for
Stream Class handling formatted input & output operations
istream Input Stream Inherits properties of ios. It reads and interprets input.
Declares input functions get(), getline() and
read().Contains overloaded extraction operator >>.

ostream Output Stream Inherits properties of ios. It can write sequences of


characters and represents other kinds of data. Declares
output functions put()and write().
Contains overloaded insertion operator<<.

iostream Input / Output Inherits properties of ios istream and ostream & contains
Stream all input & output functions.
streambuf File Stream Base Provides an interface to physical devices through buffers
& acts as a base for filebuf class used ios files

Unformatted I/O Operations:


We have used objects cin & cout which are predefined in iostream file for input & output of
various types. cin is an object of type istream & cout is an object of type ostream.
We read data from keyboard using following format:
cin>>variable1>> variable2>>………>> variableN
We write data or display it on screen using following format:
cout<<variable1<<variable2<< .........................<<variable

Example: Illustrate use of cin & cout statements.


int rno;
cin>>rno;
cout<<”Roll No:”<<rno<<endl;
In this we have to study different functions of istream class and of ostream class.

istream class functions:


int get()-Accepts a character from input screen & returns it.
istream &get(char &ch)- Accepts a character from input screen & assigns it to the character ’ch’.
istream &getline(char *buffer,int size,char del=’\n’)-It accepts a string from input stream until it
enters a newline character.

58
ostream class functions:
ostream &put(char ch)- It inserts a character ch in an output screen.
ostream &write(const char *s, streamsize n)- It inserts first n characters of the character array
pointed to by ‘s’ into the output screen.

Examples: Program to illustrate use of get() & put() functions.


#include<iostream.h>
#include<conio.h>int
main()
{
char c;
clrscr();
cin.get(c); //get a character from keyboard & assigns it to
cout<<"Entered Character is:"<<c; //display an entered character on output screen.
return 0;
}
In above program we can also display same character entered by user using
cout.put(c) method instead of using cout statement.

Examples: Program to illustrate use of getline() & write() functions.


#include<iostream.h>
#include<conio.h>int
main()
{
intsize;
char name[20];
char*city="Pune";
clrscr();
cout<<"Enter name of student:";//Accept name of student from user
cin>>name;
cout<<"Entered name is:"<<name;//Display entered name
cout<<"City of student is:"<<endl;
cout.write(city,10);//Display city using write function
cout<<"Enter another name of student:"<<endl;
cin.getline(name,size); //Use geline function to accept name
cout<<"Another name of student is:"<<name; //Display another name of student accepted
from user
return 0;
}

Formatted Console I/O Operations:


C++ supports a number of features that could be used for formatting output.These features
includes:
• ios class functions &flags
• Manipulators
• User-Defined Outputfunctions(Manipulators)

59
The ios class contains a large number of member functions that help us to format the output in a
number of ways.

Manipulators are helping functions that can modify the input or output stream. These format
manipulators are available by including the file “<iomanip.h>”.

ios format functions & manipulators:

ios Task Equivalent


Functions Manipulators
width() Specify required field size for displaying an output value setw()
precision() Specify number of digits to be displayed after the decimal point setprecision()
of float value
fill() Specify a character that is used to fill the unused portion of a setfill()
field
setf() Specify format flags that can control the form of output display setiosflags()
i. e left justification & right justification
unsetf() To clear the flags specified resetiosflags()

#include<iostream.h>#include<c
onio.h> #include<math.h>
int main()
{
clrscr();
cout.width(5); //set width to 5
cout<<123<<12<<endl; //dispay output in width of box5
cout.width(5);
cout<<543;
cout.width(5);
cout<<19<<endl;
cout.precision(3); //display 3 digits after decimalpoint
cout<<sqrt(2)<<"\n";
cout.precision(4); //display4digitsafterdecimalpoint
cout<<sqrt(3)<<"\n";
cout.fill('*'); //Padding fill with'*'
cout.width(10);
cout<<"SYBBA"<<"\n";
cout.fill('#'); //Padding fill with'#'
cout.setf(ios::right,ios::adjustfield); //it display output to rightside
cout.width(12);
cout<<"CA"<<"\n";
return 0;
}
Output:
12312

60
54319
1.414
1.7321
*****SYBBA
##########CA

User-Defined Manipulators:
In addition to predefined functions C++ allows us to create our own manipulator functions to
provide any special output formats.

ostream & manipulator(ostream & output)


{

// code

return output;
}
manipulator is the name of manipulator under creation.

Example: Program to illustrate how to create user defined manipulator.


#include<iostream.h>
ostream & unit(ostream & output)
{
output<<"Kilograms";
return output;
}
int main()
{
cout<<"Weight:"<<40<<unit;
return 0;
}
Output:

C:\TURBOC3\BIN>TC
Weight:40Kilograms

Practice programs:
1. Define a class Item that contains data member as Item_no, Item _Name, Item _Price.
Derive a class Discount(discount_in_percentage) from class Item. A Customer buys ‘n’
items.Acceptquantityforeachitem,calculatetotaldiscountandaccordinglygenerateand
display the bill using appropriateManipulators.

Set A:
1. Write a C++ program to create a class Employee which contains data members as
Emp_Id, Emp_Name, Basic_Salary, HRA, DA, Gross_Salary. Write member functions to
acceptEmployeeinformation.CalculateanddisplayGrosssalaryofanemployee.

61
(DA=25%ofBasicsalaryandHRA=40%ofBasic salary)(Useappropriatemanipulators
todisplayemployeeinformationingiven format:-Emp_IdandEmp_Nameshouldbeleft
justified and Basic_Salary, HRA, DA, Gross salary Right justified with a precision of
threedigits)
2. Write a C++ program to create a class Teacher which contains data members as
Teacher_Name, Teacher_City, Teacher_Contact_Number. Write member functions to
accept and display five teachers information. Design User defined Manipulator to print
Teacher_Contact_Number.(ForContactNumbersetrightjustification,maximumwidthto 10
and fill remaining spaces with‘*’)

Set B:
1. Create a C++ class Train with data members as Train_No,Train_Name,No_of
Seats,Source_Station,Destination_Station. Write necessary member functions for the
following:
i. Accept details of ntrains.
ii. Display all traindetails.
iii. Display details of train from specified starting station and ending station byuser.
2. Create a C++ class Manager with data members Manager_Id, Manager_Name,
Mobile_No., Salary. Write necessary member functions for thefollowing:
i. Accept details of n managers
ii. Display manager details in ascending order of theirsalary.
iii. Display details of a particular manager. (Use Array of object and Use appropriate
manipulators.)

Set C:
1. Create a C++ class Marksheet with data members Seat_No., Student_Name, Class,
Subject_Name, Int_Marks, Ext_Marks, Total, Grand_Total, Percentage, Grade. Write
member function to accept Student information for 4 subjects. Calculate Total,
Grand_Total, Percentage, Grade and display Marksheet. (Use user defined manipulator)

Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of Instructor

62
Assignment No. 8: Working with Files

File: It is collection of data or information. Stream: It is sequence of bytes.

To perform input and output operations on files, three classes included in the <fstream.h> library.
It defines several classes including ifstream , ofstream and fstream.

Stream Description
ofstream Stream class to write on files
ifstream Stream class to read from files
fstream Stream class to both read and write from/to files.

Opening file:
File can be opened by using member function open() or by using constructor.

Stream Description Examples By Using Constructor Examples By Using Member


Function
ofstream Stream class to ofstream outfile1(“first.txt”); ofstream outfile2;
write onfiles outfile2.open(“second.txt”);
ifstream Stream class to read ifstream infile1(“first.txt”); ifstream infile2;
fromfiles infile2.open(“second.txt”);

fstream Stream class toboth fstream file1(“first.txt”,ios::out); fstream file2;


read and write to / file2.open(“second.txt”,ios::out);
fromfiles.

Detecting End-Of-File:
It checks whether end of file occurs or not. eof() is member function of ios class. It returns
nonzero value if end of file condition is encountered and zero otherwise.

Syntax:
ifstream fin;
if(fin.eof()!=0)
{
exit(1);
}
This statement terminates the program on reaching end of file.

File Opening Modes:


There are different modes (flags) of a file which are listed below:

Parameter Meaning
ios::in Open for input operations.
ios::out Open for output operations.

63
ios::binary Open in binary mode.
ios::ate Set the initial position at the end of the file.
If this flag is not set, the initial position is the beginning of the file.
ios::app All output operations are performed at the end of the file, appending the content to
the current content of the file.
ios::trunk If the file is opened for output operations and it already exists, its previous content is
deleted and replaced by the new one.

Closing File:
A file which is opened while reading or writing in file handling must be closed after performing
an action on it.

Syntax:
filename.close();

File Pointer and Their Manipulations:


Each file has two pointers associated with it known as file pointers.
Input pointer (get pointer)
Output pointer (put pointer)

Following member functions are used to move the file pointer at the desired position while
reading or writing from the file.

Function Description
seekg() Moves get pointer(input) to 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.

File Handling Functions:


C++ provides us with the following operations in File Handling:

open() Function-To create a file by using open function.


file.open(“sample.txt”,ios::in |ios::out);

get() & put() Functions- put() writes a single character in file and get() reads a single character
from a file.
fstream file; //Input & output stream
file.put(‘h’); //put char to file
file.get(ch); //get character from file

read() & write() Functions- These functions are used to perform read & write operations on
binary file.
infile.read((char *) & v, sizeof(v));
infile.write((char *) & v, sizeof(v));

64
These functions take two arguments. The first is address of the variable V and second is the
length of that variable in bytes.

Text and Binary files:


The C++ language supports two types of files:
• Textfiles
• Binary files

Text Files:
These files are designed to store text. In such files various character translations are performed
such as “\r+\f” is converted into “\n”, whereas in binary files no such translations are performed.
By default, C++ opens the files in text mode.
Example: Program to illustrate reading & writing to text file .
#include<fstream.h>i
nt main ()
{
char sname[20]="SYBBA",line[20];
ofstream outfile;
outfile.open("example.txt");
outfile<<sname;
outfile.close();
ifstream infile;
infile.open("example.txt");
infile.getline(line,20);
cout<<line;
infile.close();
return 0;
}
OUTPUT:
SYBBA
By using above program we can write ‘SYBBA’ to text file ’example.txt’. Then we perform read
operation on same file & display ‘SYBBA’ to output screen

Binary Files:
It is used to read & write a given number of bytes on the given stream. write() is a member
function of ostream inherited by ofstream and read is a member function of istream inherited by
ifstream. Objects of class fstream have both.

Example: Program to illustrate reading & writing to Binary File.


// writing on a text file
#include<fstream.h>
int main ()
{
char sname[20]="SYBBA";
ofstream outfile;

65
outfile.open("example.bin");
outfile.write((char *) & sname,sizeof(sname));
outfile.close();
ifstream infile;
infile.open("example.txt");
infile.read((char *)& sname,sizeof(sname));
cout<<sname;
infile.close();
return 0;
}
OUTPUT
SYBBA
By using above program we can write ‘SYBBA’ to text file ’example.bin. Then we perform read
operation on same file & display ‘SYBBA’ to output screen

Reading & Writing Class Objects:


How class objects can be written to & read from disk files.

Example: Program to illustrate reading & writing class objects.


#include <iostream.h>
#include <fstream.h>
class student
{
intrno;
charname[20];
public:
void getdata();
void putdata();
};
void student:: getdata()
{
cout<<"Enter rno:\n";
cin>>rno;
cout<<"Entername:\n";
cin>>name;
}
void student:: putdata()
{
cout<<"Roll No:"<<rno<<endl;
cout<<"Name:"<<name<<endl;
}
int main ()
{
student s[3];
fstream file;
file.open("student.txt",ios::in | ios::out);

66
cout<< "Enter details of 3 students:\n";
for(int i=0;i<3;i++)
{
s[i].getdata();
file.write((char *) & s[i],sizeof(s[i]));
}
file.seekg(0); //reset to start
cout<<"\nOUTPUT\n\n";
for(i=0;i<3;i++)
{
file.read((char *) & s[i],sizeof(s[i]));
s[i].putdata();
}
file.close();
return 0;
}

OUTPUT:
Enter details of 3 students:
Enterrno:1
Entername:Avani
Enterrno:2
Entername:Ananya
Enterrno:3
Enter name:Kavya

OUTPUT
Roll No:1
Name:Avani
Roll No:2
Name:Ananya
Roll No:3
Name:Kavya

Updating A File:Random Access


Updating is the maintenance of any data file. The updating includes one or more of following
tasks:
• Displaying contents of afile
• Modifying an existingitem
• Adding a newitem
• Deleting an existingitem

These action requires the file pointers to move to a particular location. File contains collection of
items of equal lengths. Size of each item/object can be obtained using

int object_length=sizeof(object);

67
Location of object can be obtained using int location=m* object_length;
This location gives us byte number of the first byte of mth object.We can set file pointer to reach
this byte with the help of seekg() & seekp() .

We also find total number of objects ina file using object_length as follows:
int n=file_size/ object_length;
The file_size can be obtained using function tellg() & tellp() when file pointer is located at the
end of file.

Error Handling During File Operations:


There are several error handling functions supported by class ios that help you read and process
the status recorded in a file stream. Following table lists these error handling functions and their
meaning :

Function Meaning
Returns non-zero (true value) if end-of-file is encountered while reading;
int eof()
otherwise returns zero (false value).
int fail() Returns non-zero (true) when an input or output operation has failed.
Returns a non-zero value if an invalid operation is attempted or any
unrecoverable error has occurred. However, if it is zero (false value), it
int bad()
may be possible to recover from any other error reported and continue
operations.
Returns non-zero (true) if no error has occurred. This means, all the
above functions are false. For example, if fin.good() is true, everything is
int good()
okay with the stream named as fin and we can proceed to perform I/O
operations. When it returns zero, no further operations can be carried out.

Command Line Arguments:


We supply arguments to main function at the time of invoking program by command line
argument. They may be used to pass the names of data files.
Example: Program to illustrate use of command line arguments.
#include<iostream.h>#include<fstrea
m.h> #include<stdlib.h>
int main(int argc,char *argv[])
{
int number[9]={1,2,3,4,5,6,7,8,9};
if(argc!=2)
{
cout<<"argc="<<argc<<"\n";
cout<<"Error in arguments\n";
exit(1);
}
ofstream fout1;
fout1.open(argv[1]);
if(fout1.fail())

68
{
cout<<"Unable to open a file"<<argv[1]<<"\n";
exit(1);
}
else
{
for(int i=0;i<9;i++)
{
if(number[i]%2==0)
fout1<<number[i]<<""; //write all even numbers from number array to file
}
}
fout1.close();
ifstream fin;
int i;
char ch;
for(i=1;i<argc;i++)
{
fin.open(argv[i]);
cout<<"Contents of"<<argv[i]<<"\n";
do
{
fin.get(ch);//reads an even numbers from file
cout<<ch; //display it
}while(fin);
cout<<"\n\n";
fin.close();
}
return 0;
}
Output:
C:\TC\SOURCE>temp a.txt
Contents of a.txt
2468
C:\TC\SOURCE>exit

To run this program we first compile it. Then instead of using Ctrl+F9 we have to run it by dos
shell. Click on File & then select DOS Shell.DOS Shell gets opened. Now give program name
space a.txt. All even numbers will get added to a.txt file afterwards we print even numbers from
’a.txt’ file to the output screen. Sometime program name is not found in BIN directory so change
directory from BIN to SOURCE & then run your program.

69
Practice programs:
1. Write a C++ program to copy even numbers from the file “Numbers.txt” into the file
“even.txt” and odd numbers into the file “odd.txt”. Display the count of numbers in each
file. Compute the median and average of numbers in bothfiles.
2. Write a C++ program that reads a “source.txt” file and creates another file named as
“destination.txt” which is identical to source except that every sequence of consecutive
blank spaces is replaced by a singlespace.
3. Write a C++ program to read the contents from the file “sample.txt”. Store all the
characters from “sample.txt” into the file “character.txt” & store all digits into the file
“digit.txt“.
4. Write a C++ program which will accept ‘n’ integers from user through command line
argument.StorePrimenumbersinfile“Prime.txt”andremainingnumbersin“Others.txt”.

Set A:
1. Write a C++ program to accept ‘n’ numbers from user through Command LineArgument.
Store all positive and negative numbers in file “Positive.txt” and “Negative.txt”
respectively.
2. Write a C++ program to read the contents of a text file. Count and display number of
characters, words, lines and blank spaces from a file. Find the number of occurrences of a
given word present in afile.
3. Create a C++ class Employee with data members Emp_No, Emp_Name, Emp_Marks.
Write necessary member functions for thefollowing:
i. Accept the details and store it into the file“Emp.dat”
ii. Read the details from file and displayit.
iii. Update a given record into thefile.

Set B:
1. Write a C++ program to create a class Newspaper with data members Name, publisher,
cost. Write necessary member functions for thefollowing:
i. Accept details for ‘n’ Newspapers from user and store it in a file
“Newspaper.txt”.
ii. Display details of Newspapers from a file.
iii. Count the number of objects stored in afile.
2. Write a C++ program that reads from a formatted file a list of 4 students and their marks
for 3 tests, computes the average test score for each student and the grade and outputs
them in anotherfile.
3. Create a C++ class ‘city’ with data members name and STD code. Accept ‘n’ cities with
STD codes from user. Store this data in the file ‘cities.txt’. Write a program that reads the
data from file cities.txt display the list of city with STD codes from afile

70
Set C:
1. Create a C++ class MyFile containing:

fstream fp;
Char *fn;
Write necessary member Functions using operator overloading:
+ F3=F1+F2 Put contents of F1 and F2 inF3.
- -F3 Changes the case of all upper and lower case characters inF3.

Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of Instructor

71
Assignment No. 9: Templates

Templates are powerful features of C++ which allows you to write generic programs. The simple
idea is to pass data type as a parameter so that we don’t need to write the same code for different
data types. In simple terms, we can create a single function or a class to work with different data
types using templates. Templates are often used in larger code base for the purpose of code
reusability and flexibility of the programs. The concept of templates can be used in two different
ways:
• FunctionTemplates
• ClassTemplates

Function Template:
It is used to define generic functions. A single function template can work with different data
types at once. It works on different types of data.

Syntax of function template with single parameter:


A function template starts withthe keyword template followed by template parameter(s) inside
<> which is followed by functiondeclaration.

template <class T>


returntype functionName(arguments of type T)
{
// Body of function with type T
}
T is a generic name for a data type used by the function. This name can be used within the
function definition.

Syntax of function template with Multiple Parameters:

template <class T1,class T2>


returntype functionName(arguments oftypesT1,T2, ................ )
{
// Body of function
}

Example: Program to illustrate use of Function Template with multiple parameters.


#include<iostream.h>template<c
lass T>
T add(T num1, T num2)
{
return (num1 + num2);
}

int main()
{
int result1;

72
double result2;
// calling with int parameters
result1 = add(2, 3);
cout << "2 + 3 = " << result1 << endl;

// calling with double parameters


result2 = add(2.2, 3.3);
cout << "2.2 + 3.3 = " << result2 << endl;

return 0;
}
Output:
2+3=5
2.2 + 3.3 = 5.5

Class Template:

Class templates are used for writing generic class operations. We would need to create a different
class for each data type or create different member variables and functions within a single class
using a class template.

Syntax of class template with single parameter:


template <class T>
class className
{
public:
... .. ...
//class member specification with anonymous type T
... .....

... .....

};
T is a generic name for a data type which will be specified when a class is instantiated. we can
define more than one generic data type by using a comma-separated list.

Syntax of class template with multiple parameters:


template <class T1, class T2,…..>
class className
{
public:
... .....
... .....
... .....

};

73
Example: Program to illustrate use of Class Template with multiple parameters.
#include<iostream.h>
#include<conio.h>
template<classT1,classT2>c
lassA
{
T1 a;
T2b;
public:
A(T1 x,T2y)
{
a = x;
b = y;
}
void display()
{
cout<<"Values of a and b are :"<< a<<","<<b<<endl;
}
};
int main()
{
clrscr();
A<int,float> d(5,6.5);
d.display();
return 0;
}
Output:
Values of a and b are: 5, 6.5

Practice programs:
1. Write a C++ program to swap two integer values and two float values by using function
template.

Set A:
1. Write a C++ template program to accept array elements of type integers & characters.
Reverse an array of bothtypes.
2. Write a C++ program to find maximum & minimum of two integer numbers and twofloat
numbers by using functiontemplate.
3. Write a C++ template program to sort the array elements of type integer, float and
character.

Set B:
1. Write a C++ program to define class template for calculating the square of givennumbers
with different datatypes.

74
2. Write C++ template program to find the area of circle & rectangle with different data
types.
3. Write a template to represent a generic vector. Include member functions to perform the
followingtasks:
i. To create thevector.
ii. To modify the value of a givenelement.
iii. To multiply the vector by a scalarvalue.
iv. To display the vector in the form (10,20, 30,…..)

Set C:
1. Write C++ template program to implement stack & its operations like push &pop.

Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of Instructor

75
Section-III

Advance PHP
Assignment 1: Introduction to Object Oriented Programming in PHP

Introduction:
Object-Oriented Programming (OOP) is a programming model that is based on the concept of
classes and objects. As opposed to procedural programming where the focus is on writing
procedures or functions that perform operations on the data, in object-oriented programming the
focus is on the creations of objects which contain both data and functions together.
Object Oriented Concepts:
Before we go in detail, let’s define important terms related to Object Oriented Programming.

• Class: Class is a programmer-defined data type, which includes local methods and local variables.
A class may contain its own constants,variables (called "properties"), and functions (called
"methods").
• Object: An individual instance of data structure defined by a class. You define a class once and
then make many objects that belong to it. Objects are also known asinstance.
• Constructor: Constructor Functions are special type of functions which are called automatically
whenever an object is created. It is a special function that initializes the properties of theclass.
• Destructor: Like a constructor function you can define a destructor function using
function destruct (). You can release all the resources with-in adestructor.
• Encapsulation: Encapsulation means hiding or wrapping the code and data into a single unit to
protect the data from outside world. It is used to protect class’s internal data ( properties and method)
from code outside that class and hiding details of implementation. In PHP, encapsulation is provided
by visibilityspecifiers.
• Inheritance: When a class is defined by inheriting existing function of a parent class then it is
called inheritance. Here child class will inherit all or few member functions and variables of a
parentclass.
• Interface: Interfaces allow you to create code which specifies which methods a class must
implement, without having to define how these methods are handled. Interfaces are defined in the
same way as a class, but with the interface keyword replacing the class keyword and without any
of the methods having their contents defined. All methods declared in an interface must be public;
this is the nature of an interface. Note that it is possible to declare a constructor in aninterface.
• Introspection: Introspection is the ability of a program to examine an object’s characteristics, such
as its name, parent class (if any), properties, and methods. With introspection, you can write code
that operates on any class or object. You don’t need to know which methods or properties are
defined when you write your code; instead, you can discover that information at runtime, which
makes it possible for you to write generic debuggers, serializes, profilers,etc.

Implementation of Object Oriented Concepts:

Function Description Example


class classname [extends Creates a class Class student
baseclass] {
[var $propery [= value];…] [function
functionname (arguments)
{
//code
}
….]}

1
$instance = new Create an object <?php
classname(); $instance1 = new myclass ();
//This can also be done with a variable:
$newname= ‘hello’;
$instance2 = new $newname();
?>
class classname Add a Method <?php
{ class myclass
function methodname() { functionmymethod()
{ { print “ hello,myclass}}
Statements; ?>
} To invoke the method on the object
} $instance1, we need to invoke the
operator “->" to access the newly
created function mymethod

<?php

$instance1=new myclass();
$instance1->mymethod();
?>
void _construct ([mixed Constructor is a function Method 1
$args [, $. ..]]) which is called right after a <?php
new object is created. class student
{
public $name;
public $marks;
functionconstruct($nm,$mk)
{

void _destruct (void) Destructor is a function <?php


which is called right after class Student
you release an object. {
var $name; var $address; var $phone;
//This is constructor

function _construct()
{
this->name=”abc”; this-
>address=”pqr”; this->phone=1111;
}

functiondestruct()

{
echo “Student Object Released”;}

function printstudentinfo()

2
Echo this->name . ”\n”; echo this-
>address . ”\n”; echo this->phone .
“\n”;
}
}
$stud =new student();
$stud->printstudentinfo();
$stud=NULL;
?>

class extendedClass Inheritance <?php


extends classname It is the ability of PHP to extend class myclass
classes that inherit the {
characteristics of the parent //property declaration
class. public $var=’a default value’;
//method declaration
public function desplayVar()
{
echo $this->var;
}
}
class extendedClass extends myclass
{
//redefine the parent method function
displayVar()
{
echo “Extending Class”;
parent::displayVar();
}
}
$extend =new extendedClass();
$extend->displayVar();
?>
Output : Extending class a default value
Introspection
class_exist() We can use this function to $class = class_exists(classname);
determine whether a class exists.

3
get_declared_classes() This function returns array of $classes = get_declared_classes();
defined classes and checks if the
class name is in returned array.

get_class_methods() We can use this function to get $methods=get_class_methods(classna me);


the methods and properties of
class

This function returns only $properties=get_class_vars(classnam e);


get_class_vars() properties that have default
values.

get_parent_class() This function is used to find the $superclass=get_parent_class( classname );


class’s parent class.

is_object() Is_object function is used to $obj= is_obj(var);


make sure that it is object.

4
get_class() function is used
get_class() to get the class to which an $classname= get_class(object);
object belongs and to get class
name

This function is used to $method_exists=method_exists(object


check if method on an object ,method);
method_exists() exists .

This function returns an


get_object_vars() array of properties set in an $array=get_object_vars(object);
object

Interfaces An interface is declared Example of an interface class duck


similar to a class but only { functionquack()
include function prototypes {
(without implementation) and echo “quack,quack,qk, qk…”;
constants. When a class uses an }
interface the class must define }
all the methods / function of the Interface birds
interface otherwise the PHP {
engine will give you anerror. function breath(); function eat();
}
The interface’s function Class duck implements birds
/methods cannot have the details { functionquack()
filled in. that is left to the class {
that uses the interface. echo “quack,quack,qk, qk…”;
}
}
function breath()
{
echo “duck is breathing”;
}
function eat()
{
echo “ duck is eating”;
}

5
Practice Programs:
1) Write a PHP program to create class circle having radius data member and two member
functions find_circumfernce () and find_area() . Display area and Circumference
depending on user’spreference.
2) Create Class Collge and Class Department as base class and derived class respectively , Create one
more class as Faculty to display it’s detail information.( Use the concept ofinterface)
3) Write PHP script to demonstrate the concept of introspection for examiningobject.

Set A:
1) Write class declarations and member function definitions for an employee(code, name, designation).
Derive emp_account(account_no, joining_date) from employee and emp_sal(basic_pay, earnings,
deduction) from emp_account. Write a menu drivenprogram
a) To build a mastertable
b) To sort allentries
c) To search anentry
d) Displaysalary
2) Define an interface which has methods area( ), volume( ). Define constant PI. Create a class cylinder
which implements this interface and calculate area and volume. (Hint: Use define())
3) Write a Calculator class that can accept two values, then add them, subtract them, multiply them
together, or divide them onrequest.
For example:
$calc = new Calculator(
3, 4 ); echo $calc-
>add(); // Displays “7”
echo $calc- >multiply(); // Displays “12”
SetB:
1) Create a class named DISTANCE with feet and inches as data members. The classhas
the following member functions: convert_feet_to_inch() , convert_inch_to_feet() .
Display options using radio button and display conversion on nextpage.
2) Write a PHP program to create a class Employee that contains data members as
Emp_Name, Dept_name , Basic_sal,DA, HRA,TA , IT,PF,PT , GROSS,
DEDUCTION ,NET . It hasmember functions calculate_gross , calculate_deductions ,
Calculate_net_salary . Display pay slip of employee. Create and Initialize members
Emp_Name, Dept_name , Basic_sal of Employee object by using parameterized
constructor.
3) Write a PHP program to create a class temperature which contains data members as
Celsius and Fahrenheit . Create and Initialize all values of temperature object by using
parameterized constructor . Convert Celsius to Fahrenheit and Convert Fahrenheit to
Celsius using member functions. Display conversion on nextpage.
Set C:
1) Write a PHP program to create a class article having articleid, name, articleqty, price.
Write menu driven program to perform following functions :( Use array ofobjects)
i) Display details of all articlespurchased.
ii) Display details of articles whose price exceeds500
iii) Display details of articles whose quantity exceeds50
2) Write a PHP program to create a class Worker that has data members as
Worker_Name, No_of_Days_worked, Pay_Rate. Create and initialize the object
using default constructor, Parameterized constructor. Also write necessary member
function to calculate and display the salary ofworker.

6
Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete []


3: Needs Improvement [ ] 4: Complete [ ] 5: well done [ ]

Signature of the Instructor

7
Assignment 2: To study Web Techniques
Sticky Forms:
Sticky form remembers the values you entered in the input fields. Good example of sticky form is
Google search box. Sticky form helps user to type the same form again supplying the values in inputs.
Sticky form is form in which the results of a query are accompanied by a search form whose default
values are those of the previous query. To make sticky form , You just include the attribute value for
text fields, and selected/checked for other elements:
Example :
<html>
<body>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<b>Your Name : </b><input type="text" name="name" value="<?php if(isset($_POST['name'])) echo
$_POST['name'];?>">

<p><input type="submit" name="submit" value="Submit" /></p>

</form>
<?php
echo "Your Name is =". $_POST['name']."<br>";
?>
</body>
</html>

Multi – Valued Parameters:

HTML selection lists, created with the select tag, can allow multiple selections. To ensure that PHP
recognizes the multiple values that the browser passes to a form-processing script, you need to make
the name of the field in the HTML form end with [].When PHP engine sees a submitted form field
name with square brackets at the end, it creates a nested array of values within the $_GET or $_POST
and $_REQUEST superglobal array, rather than a single value.

For example:

<select name="languages[]">
<input name="c">C</input>
<inputname="c++">C++</input>
<inputname="php">PHP</input>
<inputname="perl">Perl</input>
</select>

Now, when the user submits the form , $_GET['languages'] contains an array instead of a simple
string. This array contains the values that were selected by the user.

8
Example
<html>
<head><title>LANGAUGES</title></head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="GET">
Select your Language :<br>
<select name="languages[]" multiple>
<option value="c"> C </option>
<option value ="c++"> C++</option>
<option value ="php"> PHP</option>
<option value ="perl"> Perl </option>
</select>
<br>
<input type="submit" name="s" value="My Languages!" />
</form>
<?php
if (array_key_exists('s', $_GET))
{
$lang = join (" ,", $_GET['languages']);
echo "You know $lang languages.";
}
?>
</body>
</html>

Sticky Multi – Valued Parameters:


You can make multiple selection form elements sticky. You’ll need to check to see whether each
possible value in the form was one of the submitted value.
For example :

RED: <input type="checkbox" name="attributes[]" value=“red“ <?= if (is_array($_GET['attributes'])


and in_array(‘red', $_GET['attributes'])) { "checked"; } ?>>

Consider following example to implement sticky multi-value


parameters

9
<html>
<head><title>LANGAUGES</title></head>
<body>

<?php
$c1 = $_GET['c1'];
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="GET">
Qualification : <br>
<input type="checkbox" name="c1[]" value="ssc" <?php if(in_array('ssc', $_GET['c1'])) {echo
"checked"; }?>> SSC <br>

<input type="checkbox" name="c1[]" value="hsc"


<?php if(is_array($_GET['c1']) and in_array('hsc', $_GET['c1'])) { echo "checked"; }?>> HSC <br>

<input type="checkbox" name="c1[]" value="bca"


<?php if(is_array($_GET['c1']) and in_array('bca', $_GET['c1'])) { echo "checked";}?>> BCA <br>

<input type="checkbox" name="c1[]" value="mca"


<?php if(is_array($_GET['c1']) and in_array('mca', $_GET['c1'])) {echo "checked";}?>> MCA <br>

<input type="submit" name="s" value="My Qualification" />


</form>
<?php
if (array_key_exists('s', $_GET))
{
$a = join (" ,", $_GET['c1']);
echo "You Qualification : $a";
}
?>
</body>
</html>

Self Processing Page:

• Self processing page means one PHP page can be used to both generate a form and process
it.You can use PHP_SELF variable for generating self processing page. PHP_SELF is a
variable that returns the current script being executed. This variable returns the name andpath
of the current file (from the root folder). You can use this variable in the action field of the
FORM.
• <form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

10
Example A self-processing page
<html>
<head><title>Temperature Conversion</title></head>
<body>

<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
?>

<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">


Fahrenheit temperature:
<input type="text" name="fahrenheit" /><br />
<input type="submit" name="Convert to Celsius!" />
</form>
<?php
}
elseif ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$fahr = $_POST['fahrenheit'];
$celsius = ($fahr - 32) * 5/9;
printf("%.2fF is %.2fC", $fahr, $celsius);
} else
{
die("This script only works with GET and POST requests.");
}
?>
</body>
</html>

Server information :
$_SERVER is a PHP super global array which holds information about the items like Server
information, Header information, Details on PHP page request, File name or path information,
Remote user information, HTTP Authentication Details.

Element/Code Description
$_SERVER['PHP_SELF'] Returns the filename of the currently executing script
$_SERVER['GATEWAY_INTERFACE'] Returns the version of the Common Gateway Interface
(CGI) the server is using
$_SERVER['SERVER_ADDR'] Returns the IP address of the host server
$_SERVER['SERVER_NAME'] Returns the name of the host server (such as
www.w3schools.com)
$_SERVER['SERVER_SOFTWARE'] Returns the server identification string (such as
Apache/2.2.24)
$_SERVER['SERVER_PROTOCOL'] Returns the name and revision of the information
protocol (such as HTTP/1.1)
$_SERVER['REQUEST_METHOD'] Returns the request method used to access the page
(such as POST)

11
$_SERVER['QUERY_STRING'] Returns the query string if the page is accessed via a
query string
$_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request
$_SERVER['HTTP_HOST'] Returns the Host header from the current request
$_SERVER['HTTPS'] Is the script queried through a secure HTTP protocol
$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing
the current page
$_SERVER['REMOTE_HOST'] Returns the Host name from where the user is viewing
the current page
$_SERVER['REMOTE_PORT'] Returns the port being used on the user's machine to
communicate with the web serve
$_SERVER['SERVER_PORT'] Returns the port on the server machine being used by
the web server for communication (such as 80
$_SERVER['SCRIPT_NAME'] Returns the path of the current script
$_SERVER['SCRIPT_URI'] Returns the URI of the current page

Example: to display server information like name , script name , user agent etc.

<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>

Output :
/php/demo_global_server.php
www.w3schools.comwww.w
3schools.com
https://www.w3schools.com/php/showphp.asp?filename=demo_global_server
Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112
Safari/537.36
/php/demo_global_server.php

12
Practice Programs:
1) Write a PHP script to Design a form to accept a number from the user to check whether
number is palindrome or not. (Use the concept of self processingpage)
2) Write PHP program to accept user details such as user-id, name, Address, email, and mobile
no. Display same information on nextpage.
3) Write PHP program to create student registration form and display student information.
(Use sticky formconcept).

Set A:
1) Write PHP program accept name, select your cities you would like to visit and display
selected information on page. (Use multi-valuedparameter),.
2) Write PHP program to create student registration form and display student information.
(Use sticky formconcept).
3) Write a PHP script for the following: Design a form to accept a number from theuser.
Perform the operations and show theresults.
• Check whether number is palindrome ornot.
• Reverse the number using
recursions.
(Use the concept of self processing page.)
4) Write PHP program to select list of subjects from list box and display selected subject on
information. (Use sticky multi-valuedparameter)

Set B:
1) Write a PHP Script to display Server information in table format (Use$_SERVER).
2) Write a PHP program to accept two strings from user and check whether entered
strings are matching or not. (Use sticky formconcept).
3) Write a PHP script to accept an Indian currency and then convert it in dollar orpounds
(radio buttons) according to user’s preference. (use concept of self processingform).
4) Write PHP program to accept client name, property details (Flat, Bunglow, Plot),
Display selected information same page. (Use multi- valueparameter).

Set C:
1) Write PHP program to accept name of student , Gender(male ,female ) using radio buttons
,Qualification(SSC, HSC, BCA, MCA) using check boxes . Display information of student.
(Use sticky multi-valued parameter).

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete []


3: Needs Improvement [ ] 4: Complete [ ] 5: well done [ ]

Signature of the Instructor

13
Assignment 3 – XML
Introduction to XML:

XML stands for eXtensible Markup Language. It is a text-based markup language derived from
Standard Generalized Markup Language (SGML). XML was designed to store and transport data.
XML was designed to be both human- and machine-readable. XML is a markup language much
like HTML. XML was designed to describe data. XML tags are not predefined . You must define
your own tags.XML is self describing.

XML document are well – formed and valid. A well - formed XML document follows the basic
XML syntax rules.A valid document also follows the rules imposed by a DTD or an XSD.

A simple document is shown in the following example −

<?xml version = "1.0"?>


<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>

The following image depicts the parts of XML document.

Document Prolog Section :


Document Prolog comes at the top of the document, before the root element. This section contains −

• XMLdeclaration
• Document typedeclaration
Document Elements Section:
Document Elements are the building blocks of XML. These divide the document into a hierarchy
of sections, each serving a specific purpose.
XML declaration :
It contains details that prepare an XML processor to parse the XML document. It is optional,
but when used, it must appear in the first line of the XML document.
<?xml version="version_number" encoding="encoding_declaration"
standalone="standalone_status" ?>

An XML declaration should abide with the following rules:

14
• The XML declaration is case sensitive and must begin with "<?xml>" where "xml" iswritten
in lower-case. If the XML declaration is included, it must contain version numberattribute.
• The Parameter names and values are case-sensitive.The names are always in lowercase.
• The order of placing the parameters is important. The correct order is:version, encoding and
standalone. Either single or double quotes may beused.
• The XML declaration has no closing tag i.e.</?xml>

Example of XML declaration:


• <?xml>
• <?xmlversion="1.0">
• <?xml version="1.0" encoding="UTF-8" standalone="no" ?>
• <?xml version='1.0' encoding='iso-8859-1' standalone='no'?>

DTD :Document Type Declaration :


• The XML Document Type Declaration, commonly known as DTD, is a way to
describe XML languageprecisely.
• DTDs check vocabulary and validity of the structure of XML documents
against grammatical rules of appropriate XMLlanguage.
• An XML DTD can be either specified inside the document, or it can be kept ina
separate document and then likedseparately.
• Basic syntax of a DTD is asfollows:
<!DOCTYPE element DTD identifier
[
declaration1
declaration2
........
]>

XML Tags :
XML tags are case sensitive. The tag <Letter> is different from the tag <letter>.
Opening and closing tags must be written with the same case.

For example,
<Message>This is incorrect</message>
<message>This is correct</message>

XML Elements :
• An XML file is structured by several XML-elements, also called XML-nodes or XML-tags.
XML-elements' names are enclosed by triangular brackets <>.
• EachXML-elementneedstobeclosedeitherwithstartorwithendelementsasshownbelow:
<element>....</element>.
• An XML document can have only one rootelement
• An XML-element can contain multiple XML-elements as its children, but the children
elements must notoverlap.
• In XML, all elements must be properly nested within eachother.
XML attributes:
• An XML-element can have one or more attributes.
• Attribute names in XML (unlike HTML) are case sensitive. That is, HREF andhrefare
considered two different XMLattributes.
• Same attribute cannot have two values in asyntax

So XML follows tree structure


<root>
<child>

15
<subchild> .... </subchild>
</child>
</root>
<?xml version = “1.0” ?>
<BookStore>
<Books>
<PHP>
<title>Programming PHP</title>
<publication>O’RELLY</publication>
</PHP
>
<PHP><title>Beginners PHP</title>
<publication>WROX</publication>

</PHP
>
</Books>
</BookStore>

16
SimpleXML :
• SimpleXML is an extension that allows us to easily manipulate and get XMLdata.
• The SimpleXML extension is the tool of choice for parsing an XMLdocument.
• SimpleXML turns an XML document into a data structure you can iterate through likea
collection of arrays andobjects.
• The SimpleXML extension includes interoperability with the DOM for writing XML filesand
built-in XPathsupport.
• SimpleXML is easier to code than the DOM, as its nameimplies.
SimpleXMLElement class represents an element in an XML document.
• To create root element of xml document, first create object of SimpleXMLElement class and
initialize with rootelement.
• For example :
• $bk=newSimpleXMLElement(“<bookstore/>”);

Methods or functions of simpleXMLElement class

Function name description syntax example

addChild() The addChild() addChild(name,val $book = $bk->addchild(“book”);


function adds a ue);
child element to
the SimpleXML
elemen
addAttribute() adds an attribute addAttribute(name, $book->addAttribute(“Category” ,
to the value); “Technical”);
SimpleXML
element.
getName() Returns the name getName(); $bk->getName();
of the XML tag
referenced by the
SimpleXML
element
asXML() Returns a well- asXML([filename])
formed XML string ; echo $bk->asXML();
(XML version 1.0)
from a SimpleXML
object
children() Returns the children() foreach ($book->children() as $child)
children of a {
specified node as echo "Child node: " . $child .
an array "<br>";
}
attributes(); Returns the attributes(); foreach ($book->attributes () as
attributes/values $k=>$v)
of an element {
echo $k : $v . "<br>";
}
count(); The count() count(); $cnt=$book->count();
function counts
the children of a
specified node.

17
simplexml_load Converts an simplexml_load_fil $xml=simplexml_load_file("note.xm
_file() XML file into a e(file) l"
SimpleXMLEle );
me nt object
simplexml_load The <?php
_string() simplexml_load_s $note=<<<XML
tr ing() function <note>
converts a well- <to>Tove</to>
formed XML </note>
string into a XML;
SimpleXMLElem
e nt object. $xml=simplexml_load_string($note);

Reading XML document


<?php
$bk = simplexml_load_file(“book.xml”);
echo htmlspecialchars($bk->asXML());
?>

• With SimpleXML, all the elements in XML document are represented as tree of
SimpleXMLElementobjects.Anygivenelement’schildrenareavailableaspropertiesof
elements SimpleXMLElement object.

• For example ,We can access element name as properties $book->title , $book->publisheretc.

Consider an application that reads “Book.xml” file into simple XML object. Display attributes and
elements.

//book .xml
<?xml version='1.0' encoding='UTF-8'?>
<bookstore>
<book category="Technical">
<title> LET US C </title>
<author> YASHWANT KANETKAR </author>
<year> 1980 </year>
</book>
<book category="Cooking">
<title> COOKING EVERYDAY </title>
<author> TARALA DALAL </author>
<year> 2000 </year>
</book>
<book category="YOGA">
<title> LIGHT ON YOGA </title>
<author> B.K.IYENGAR </author>
<year> 1990 </year>
</book>
</bookstore>

// book.php
<?php
$xml = simplexml_load_file("book.xml");
echo $xml->getName() . "<br />";
foreach($xml->children() as $child)
{
echo $child->getName() . "<br>";
18
foreach($child->attributes() as $k=>$v)
{
echo $k . "=". $v . "<br>";
foreach($child->children() as $i=>$j)
{
echo $i .":". $j."<br>";

}
}
}
?>

Practice Programs:
1) Write a XML program which shows how you can easily read and display the contents of an
XML document using SimpleXML.
2) Write a script to create “Company.xml” file with multiple elements as shownbelow:
<CemployeeTeam>
<Team Name=”Red”>
<Ename> </ Ename>
<Eexperience> </ Eexperience >
<Emobno> </ Emobno>
<Eaddress> </Eaddress>
</Team>
</CemployeeTeam>
3) Write a PHP Script to read book.XML and print book details in tabular format using simple
XML.(Content of book.XML are (bookcode , bookname , author , year ,price).

Set A:
1) Write a PHP script to create XML file named“Course.xml”
<Course>
<SYBBA CA>
<Studentname> .......</Studentname>
<Classname> ...... </Class name>
<percentage> .... </percentage>
</SYBBA CA>
</Course>
Store the details of 5 students who are in SYBBACA.
2) Write PHP script to generate an XML code in the followingformat
<?xml version="1.0" encoding="ISO-8859-1" ?>

<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
</CATALOG>
Save the file with name “CD.xml”.

3) Write PHP script to generate an XML code in the followingformat


<?xml version="1.0" encoding="ISO-8859-1" ?>
<CATALOG>
19
<PLANT>
<BOTANICAL>Sanguinaria canadensis</BOTANICAL>
<ZONE>4</ZONE>
<LIGHT>Mostly Shady</LIGHT>
<PRICE>$2.44</PRICE>
<AVAILABILITY>031599</AVAILABILITY></PLANT></CATAOG>
Save the file with name “plant.xml”.

Set B:
1) Write a script to create “cricket.xml” file with multiple elements as shownbelow:
<CricketTeam>
<Team country=”India”>
<player> </player>
<runs> </runs>
<wicket> </wicket>
</Team>
</CricketTeam>
Write a script to add multiple elements in “cricket.xml” file of category, country=”Australia”.
2) Write a script to create “breakfast.xml” file with multiple elements as shownbelow:

<breakfast_menu>
<food>
<name>French Fries</name>
<price>Rs45</price>
<description>Young youths are very much intrested to eat it </description>
<calories>650</calories>
</food>
</breakfast_menu>
Write a script to add multiple elements in “breakfast.xml” file of category, Juice.
3) Create a XML file which gives details of movies available in “Mayanagari CD Store” from
followingcategories
a) Classical
b) Action
c) Horror
Elements in each category are in the following format
<Category>
<MovieName> ---- </MovieName>
<ReleaseYear> ---- </ReleaseYear>
</Category>
Save the file with name “movies.xml”.
Set C:
1) Create an application that reads “book.xml” file into simple XML object. Display attributes and
elements (Hint:simple_xml_load_file() function).

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete []


3: Needs Improvement [ ] 4: Complete [ ] 5: well done [ ]

Signature of the Instructor


20
Assignment 4: PHP with AJAX
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better,
faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script.
When a user wants more content, they click a link. With AJAX, a user can click something and
content can be loaded into the page, using JavaScript, without reloading the entirepage.
Conventional web applications transmit information to and from the sever using synchronous
requests. It means you fill out a form, hit submit, and get directed to a new page with new information
from the server. With AJAX, when you hit submit, JavaScript will make a request to the server,
interpret the results, and Update the current screen. In the purest sense, the user would never know that
anything was even transmitted to the server.
AJAX cannot work independently. It is used in combination with other technologies to create
interactive WebPages.

1) JavaScript
✓ Loosely typed scriptinglanguage.
✓ JavaScript function is called when an event occurs in apage.
✓ Glue for the whole AJAXoperation.
2) DOM
✓ API for accessing and manipulating structureddocuments.
✓ Represents the structure of XML and HTMLdocuments.
3) CSS
✓ Allows for a clear separation of the presentation style from the content andmay
be changed programmatically byJavaScript.
4) XMLHttpRequest
✓ JavaScript object that performs asynchronous interaction with theserver.

XMLHttpRequest is a JavaScript object capable of calling the server and capturing its response.
It is used to send HTTP or HTTPS requests to a web server and load the server response data backinto
thescript.

Creating an XMLHttpRequest Object :


All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a builtin XMLHttpRequest
object.

Syntax for creating an XMLHttpRequest object:


xmlhttp=newXMLHttpRequest();
When a request to a server is sent, we want to perform some actions based on the response.
The onreadystatechange event is triggered every time the readyState changes. The readyState
property holds the status of the XMLHttpRequest.

Three important properties of the XMLHttpRequest object:

• readyState :The readyState property defines the current state of the XMLHttpRequestobject.

The following table provides a list of the possible values for the readyState property:
State Description
0 The request is notinitialized.
1 The request has been setup.
2 The request has beensent.
3 The request is in process
4 The request iscompleted.

21
• OnReadyStateChange : Determine the function called when the objects readyState changes.
xmlobj.onreadystatechange=function()
{
}

• responseText:Returns the response as astring.


• responseXML:Returns the response as XML. This property returns an XML documentobject,
which can be examined and parsed using the W3C DOM node tree methods andproperties.
• Status:Returns the status as a number (e.g., 404 for "Not Found" and 200 for"OK").
• statusText:Returns the status as a string (e.g., "Not Found" or"OK").
• Methods of XMLHttpRequest object:
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest
objec

• open( method, URL, async )

Specifies the method, URL, and other optional attributes of a request. The method parameter can
have a value of "GET", "POST", or "HEAD“. The "async" parameter specifies whether the
request should be handled asynchronously or not. "true" means that the script processing carries
on after the send() method without waiting for a response, and "false" means that the script waits
for a response before continuing script processing.

• send( content ): Sends therequest.


• abort()Cancels the currentrequest.

Practice Programs:
1) Write a simple PHP program which implements Ajax for addition of twonumbers.
2) Write an Ajax program to display list of games stored in an array on clicking OKbutton.
3) Write an Ajax program to read a text file and print the contents of the file when user click on the print
button.(consider “a.txt” file to create text & write text as “Ajax Example” init.)

Set A:
1) Write a PHP script using AJAX concept, to check user name and password are valid or
Invalid (use database to store user name andpassword).
2) Write Ajax program to carry out validation for a username entered in textbox. If the
textbox is blank, print ‘Enter username’. If the number of characters is less than three,print’
Username is too short’. If value entered is appropriate the print ‘Validusername’.
3) Write Ajax program to get book details from XML file when user select a book name.
Create XML file for storing details of book(title, author, year,price).

Set B:
1) Write Ajax program to fetch suggestions when is user is typing in atextbox.
(eg like google suggestions.Hint create array of suggestions and matching string will be displayed )
2) Write Ajax program to get player details from XML file when user select a player name.
Create XML file for storing details of player (Country, player name, wickets, runs).
3) Write a AJAX program to display the following output to search your favourite tutorial from
“tutorial.php”file.

22
Set C:
1) Write a AJAX program to display the selected course information from the list given in XML
file and show the following output.

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete []


3: Needs Improvement [ ] 4: Complete [ ] 5: well done [ ]

Signature of the Instructor

23
Assignment 5: Connecting Database using PHP & AJAX
Fetch Data from MySQL table using PHP
To fetch data from the MySQL database, configure the following steps –
1) First, Include database connection filedatabase.php
2) Assign connection variable $conn to a new variable$db
3) Create a custom function fetch_data(). This function will return data to fetch from the database.
Then call fetch_data() and assign it to a new variable$fetchData.
4) Also, Create another custom function show_data($fetchData). This function returns data with an
HTMLtable.
5) Callshow_data($fetchData).
6) This function accepts a parameter to get fetched data.
File Name –backe

Function name description syntax example

mysql_connect Open mysqli_connect([$ho $conn = new mysqli($servername,


aconnection to st, $username, $username, $password);
aMySQL Server $passwd, $dname,
$port, $socket] )

mysql_create_d Create a mysql_create_db (stri $sql = 'CREATE DATABASE my_d


b MySQLdatabase ng $database_name ,r b';
esource$link_identifi
er = NULL ) : bool
mysql_error Returns the text mysql_error ( resourc echo mysql_errno($link) . ": " . mysq
ofthe error e $link_identifier = l_error($link). "\n";
messagefrom NULL ) : string
previousMySQL
operation
mysql_fetch_ro Get a result mysql_fetch_row ( res $row = mysql_fetch_row($result);
w rowas an ource $result ) : array
enumeratedarray

mysql_db_query Selects a mysql_db_query ( stri $result = mysql_query($sql, $link);


databaseand ng $database , string $
executes aquery on query,resource$link_
it identifier=NULL)
: resource|bool
select_db() used to change $mysqli -> mysqli_select_db($con, "test");
the default select_db(name)
database for the
connection.

mysql_close Close mysql_close ( resourc mysql_close($link);


MySQLconnection e $link_identifier =
NULL ) : bool

24
Practice Programs:
1) Write an Ajax program to display list of book stored in an array on clicking ok button.
(ConsiderBook_List.php)
2) Write an Ajax program to search the book name according the character typed & display same list
using array. (UseNew.php)
3) Write an Ajax program to display list of games stored in an array on clicking okbutton.

Set A:
1) Write Ajax program to print Movie details by selecting an Actor’s name. Create table MOVIE and
ACTOR as follows with 1 : M cardinality MOVIE (mno, mname, release_yr) and ACTOR(ano,
aname).
2) Create Trip table as follows
Trip (tno, tname, Source, Destination, cost). Write Ajax program to select the trip name and print the
selected trip details.
3) Create student table as follows Student(sno, sname, per).
Write Ajax program to select the student name and print the selected student’s details.

Set B:
1) Write Ajax program to get player details from player table by inserting a player name at run
time display it’s details in tabular form .Consider ,
player (Country, player_name, wickets, runs).
2) Write Ajax program to calculate maximum runs scored for a particular country (Use Above
Playertable).

Set C:
1) Write Ajax program to get details of voters whose vage is greater than 40 year from Voter table
Create voter table as Voter (vid, vname, vage,vaddress).

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete []


3: Needs Improvement [ ] 4: Complete [ ] 5: well done [ ]

Signature of the Instructor

25
Assignment 5: PHP Framework - Druple
Drupal is open source software that allows publishing, managing and organizing a wide variety of
content on a website easier. Drupal is used to easily manage, update and publish the content in the
website. Many individuals and organizations are using Drupal to create professional websites to suit
their custom requirements. Because of easy creating sites, application and management, Drupal is
used by many organizations. We can enhance the functionality of Drupal by adding available add-on
modules.
Creating Contents
You can add two types of contents in your website: Article and Basic Page.
To create content click the link “Add content.” From the short cut menu.
Choose between Article and Basic page.
Creating Articles
Content type Article has the following features:
• Summary posted to the front page of the Website.
• Commentsenabled.
• An image can be displayed with thearticle.
• User name of the article author as well as the time it was originallypublished.
• Tags enabled, allowing you to categorize articles.
To create an article, do the followingsteps:
• From the shortcut menu, click the link “Add content.” An overlay will appear prompting you
to choose between Article and Basicpage.
• Click“Article”.
• Enter a title and body for yourpage.
• Scroll to the bottom and clickSave.
Creating Basic Page
Content type Basic Page has the following features:
• Are not published to the front page of your Website.
• Do not allow visitors to postcomments.
• Do not have taggingenabled.
• Do not have an image uploadwidget.
• Are notdate-stamped.
To create a Basic Page, do the following steps:
• From the shortcut menu, click the link “Add content.” An overlay will appear prompting you
to choose between Article and Basicpage.
• Click “Basicpage”.
• Enter a title and body for yourpage.
• Scroll to the bottom and clickSave.
Customizing the Display
Use the following steps to change the theme and logo image of yourwebsite:
• Using the administrative dashboard, click the tabAppearance.
• Scroll down to the bottom of the screen (where all the disabled themes live), and beneath
your theme’s screen shot, click the link Enable and setdefault.”
After the screen refreshes, click the settings link for your theme.
• Scroll to the fieldset “Logo image settings.” Unselect the check box “Use the default
logo.” A new set of settings will berevealed.
• Click Browse and find your logo image for this theme on your harddrive.
• Scroll to the bottom of the screen and click “Saveconfiguration.”
Blocks
• Blocks can be placed into any region in your theme.
To create Block, do the followingsteps:

26
• Using the administrative dashboard, navigate to Structure >Blocks.
• Click the link “Addblock”.
• Enter description and the text.
• Scroll to the bottom and click “Saveblock.”

Modules
The modules are used to create, edit, and delete content; convert URLs into specific database requests
to retrieve content; and create the menus you use to navigate your Web site.
Modules are little programs that allow you to do more things with your Website. Modules are set of
files contained in a Drupal folder. These files may include the following:
• An information file that describes the module to Drupal. This file lists the version, files within
the module directory, configuration screen shots, and a short description of the module. This
file isrequired.
• Installation instructions for Drupal that create the necessary database tables for the module.
This file isrequired.
• PHP scripts that hook into Drupal and allow you to perform specifictasks.
• Template files responsible for the output of the module. These template files can be altered by
your theme. These files areoptional.
• CSS files, JavaScript files, and images. These files areoptional.

Practice Programs:
1) Create a Page in Drupal titles “Game”. Add the details of different games (football, hockey, and
cricket) with player list on the page. The page should contain announcement about upcoming
match.
2) Create a module in Drupal To design a form with the following components:
Item - Ino, IName, andRate
One submit button.
After submitting the form insert a Item record into a table named Item. Also display a message
when the record is inserted successfully, and fetch the Item from the table and display
“<Iname>=<Rate>. Also add Navigation on the Home Page called “Item Rate”.
3) Using Drupal create a module containing details of your college. On the home page add
Navigation which contains your college name and also add logoimage.
Set A:
1) Create a Basic Page in Drupal titled “About Me”. Add the details about yourself in the page. Also
place this page link in the Main Menu. Display this menu link before all the menu items. Show
text “This is <your name>” when move the mouse pointer at this menulink.
2) Develop a module in Drupal to create a page showing your contact details (name, roll_no,
address, phone). Also add Navigation on the Home Page called “ContactDetails”.
3) Using Drupal create a page showing the teacher details (name, contactno, subjecttaught). Add
Navigation on the home page called “TeacherDetails”

Set B:
1) Create a Block in Drupal titled “Event”. The block should be displayed in the left side of each
page. The block should contain announcement about an upcoming events. Also change the theme
of your website by followingproperties:
a) Change the backgroundcolour.
b) Change the logoimage.
2) Create a front-page article in Drupal titled “My Article”. Write an article about PHP
programming Language and add to the article page. Display an Image appropriate to the Article
at the bottom of the Article. Also place this page link in the Main Menu. Display this menu link
before all the menu items. Show text “This is <your name>” when move the mouse pointer at
this menu link. Also post a commentabout.
3) Create a module in Drupal To design a form with the followingcomponents:
27
Text Fields - Roll No, Name, and Address
One submit button.
After submitting the form insert a student record into a table named student. Also display a message
when the record is inserted successfully, and fetch the name of student from the table and display
“Hello: <student name>”. Also add Navigation on the Home Page called “Student Form”.

Set C:
1) Develop a module in Drupal to design a registration form with the following fields:
Text Field – First Name, Last Name, email, city List Boxes – Select Country, Date of Birth
(Separate Select Boxes for month, day, and year)
Radio Buttons – Gender - Male/Female
Check Boxes – Technology Known – Java, PHP
One Browse button to upload picture.
Perform validation to check if the First Name and Last Name are not empty and the email is valid.
If that is not the case display error message and the form will not be submitted.
Display message “Form has been submitted successfully” after clicking on the Submit button.
Also add a Navigation on the Home Page called “Registration”.

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete []


3: Needs Improvement [ ] 4: Complete [ ] 5: well done [ ]

Signature of the Instructor

28
Add-On
jQuery
Savitribai Phule Pune University
Syllabus for B.B.A (CA) (CBCS 2019 Pattern) Semester IV
Subject Code: - 407
Subject Name -: jQuery
Practical Assignments

1. Write a jQuery code to check whether jQuery is loaded or not.


2. Write a jQuery code to scroll web page from top to bottom and vice versa.
3. Write a jQuery code to disable right click menu in html page.
4. Write a jQuery code to disable the submit button until the visitor has clicked a check box.
5. Write a jQuery code to fix broken images automatically.
6. Write a jQuery code to blink text continuously.
7. Write a jQuery code to create a zebra stripes table effect.
8. Write a jQuery code to print a page.
9. Write a jQuery code to allow the user to enter only 15 characters into the textbox.
10. Write a jQuery code to make first word of each statement to bold.
11. Write a jQuery code to create a division (div tag) using jQuery with style tag.
12. Write a jQuery code to select values from a JSON object.
13. Write a jQuery code to add list elements within an unordered list element.
14. Write a jQuery code to remove all the options of a select box and then add one option and
select it.
15. Write a jQuery code to underline all the words of a text.
16. Write a jQuery code to demonstrate how to get the value of a textbox.
17. Write a jQuery code to remove all CSS classes from an application.
18. Write a jQuery code to distinguish between left and right mouse click.
19. Write a jQuery code to check if an object is a jQuery object or not.
20. Write a jQuery code to detect whether the user has pressed 'Enter key' or not.
21. Write a jQuery code to count number of rows and columns in a table.
22. Write a jQuery code to display form data onto the browser.
23. Write a jQuery code to find absolute position of an element.
24. Write a jQuery code to remove a specific value from an array.
25. Write a jQuery code to change button text.
26. Write a jQuery code to add options to a drop-down list.
27. Write a jQuery code to set background-image to the page.
28. Write a jQuery code to get the selected value and currently selected text of a dropdown
box.
29. Write a jQuery code to disable a link.
30. Write a jQuery code to Restrict "number"-only input for textboxes including decimal
points.
31. Write a jQuery code to set value in input text.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy