Sybba (Ca) Lab Book Sem-Iv
Sybba (Ca) Lab Book Sem-Iv
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-II: NODE JS
Reviewed By:
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
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
5 Inheritance
6 Polymorphism
9 Templates
Total ( Out of 45 )
Total (Out of 5)
Instructor Signature:
Section-II: NODE JS
2 File system
3 Events in node.js
Total (Out of 5)
‘OR’
3 XML
Total (Out of 5)
Instructor Signature:
Section-I
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.
• 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++ can be used for building higher-level applications with graphics libraries,
applicationstocommunicatewithnetworkdevicesandcomputernetworksimulatorsas well
as remote device systems and networkmanagement.
2
Simple C++ Program:
Example: C++ Hello world program to simply print "Hello World" on computer
screen.
• 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.
4
Practice Programs:
Set A:
Set B:
1. WriteaC++programtoprintthefollowingpattern.
A
B C
D E F
G H I J
*
* *
* * *
* * * *
3. WriteaC++programtocalculatefollowingseries:
(1*1)+(2*2)+(3*3)+ … +(n*n)
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:
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;
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
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.
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.
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.
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
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.
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 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 &);
};
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.
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.
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.
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.
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.
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.
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;
}
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.
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.
};
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)
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.
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.
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.
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.
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.
#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.
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.
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’.
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;
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);
}
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.
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);
}
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);
}
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);
}
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);
}
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;
}
}
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);
}
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.
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);
}
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;
Practice Programs:
1. WriteaC++program tosortintegerandfloatarrayelementsinascendingorderbyusing
function overloading.
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:
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
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.
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>”.
#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.
// code
return output;
}
manipulator is the name of manipulator under creation.
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
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.
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.
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();
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.
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 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.
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
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
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.
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.
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.
int main()
{
int result1;
72
double result2;
// calling with int parameters
result1 = add(2, 3);
cout << "2 + 3 = " << result1 << 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.
... .....
};
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.
};
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.
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)
{
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;
?>
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.
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
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
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'];?>">
</form>
<?php
echo "Your Name is =". $_POST['name']."<br>";
?>
</body>
</html>
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>
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>
• 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') {
?>
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
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.
• 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" ?>
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>
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
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/>”);
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);
• 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”.
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
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.
• 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()
{
}
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.
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
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
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
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
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