Oopcgl
Oopcgl
LABORATORY MANUAL
Prepared By,
Prof. K. S. Mali
1|P a g e
OBJECT ORIENTED PROGRAMMING LABORATORY
List of Assignments
Part I- Object Oriented Programming Lab
Group A
1 Implement a class Complex which represents the Complex Number data type. Implement the
following operations:
1.Constructor (including a default constructor which creates the complex number 0+0i).
2. Overloaded operator+ to add two complex numbers.
3. Overloaded operator* to multiply two complex numbers.
4. Overloaded << and >> to print and read Complex Numbers.
4 Write a C++ program that creates an output file, writes information to it, closes the file, open
it again as an input file and read the information from the file.
5 Write a function template for selection sort that inputs, sorts and outputs an integer array and
a float array.
Group c
6 Write C++ program using STL for sorting and searching user defined records such as
personal records (Name, DOB, Telephone number etc) using vector container.
OR
Write C++ program using STL for sorting and searching user defined records such as Item
records (Item code, name, cost, quantity etc) using vector container.
7 Write a program in C++ to use map associative container. The keys will be the names of
states and the values will be the populations of the states. When the program runs, the user is
prompted to type the name of a state. The program then looks in the map, using the state
name as an index and returns the population of the state.
Part II- Computer Graphics
Group A
1 Write C++ program to draw a concave polygon and fill it with desired color using scan fill
algorithm. Apply the concept of inheritance.
2 Write C++ program to implement Cohen Southerland line clipping algorithm.
2|P a g e
3 a)Write C++ program to draw the following pattern. Use DDA line and Bresenham‘s circle
drawing algorithm. Apply the concept of encapsulation.
b) Write C++ program to draw the following pattern. Use DDA line and Bresenham‘s circle
drawing algorithm. Apply the concept of encapsulation.
Group B
4 a) Write C++ program to draw 2-D object and perform following basic transformations,
Scaling b) Translation c) Rotation. Apply the concept of operator overloading.
OR
b) Write C++ program to implement translation, rotation and scaling transformations on
equilateral triangle and rhombus. Apply the concept of operator overloading.
5 a) Write C++ program to generate snowflake using concept of fractals.
OR
b) Write C++ program to generate Hilbert curve using concept of fractals.
OR
c)Write C++ program to generate fractal patterns by using Koch curves.
Group C
6 a) Design and simulate any data structure like stack or queue visualization using graphics.
Simulation should include all operations performed on designed data structure. Implement the
same using OpenGL.
OR
b) Write C++ program to draw 3-D cube and perform following transformations on it using
OpenGL i) Scaling ii) Translation iii) Rotation about an axis (X/Y/Z).
OR
c)Write OpenGL program to draw Sun Rise and Sunset.
7 a) Write a C++ program to control a ball using arrow keys. Apply the concept of
polymorphism.
OR
b) Write a C++ program to implement bouncing ball using sine wave form. Apply the
concept of polymorphism.
OR
c)Write C++ program to draw man walking in the rain with an umbrella. Apply the concept
of polymorphism.
OR
3|P a g e
Write a C++ program to implement the game of 8 puzzle. Apply the concept of
polymorphism.
OR
d)Write a C++ program to implement the game Tic Tac Toe. Apply the concept of
polymorphism.
Mini-Projects/ Case Study
8 Design and implement game / animation clip / Graphics Editor using open source
graphics library. Make use of maximum features of Object-Oriented Programming.
4|P a g e
Object Oriented Programming and Computer Graphics Lab
Assignment No: 1
TITLE/PROBLEM STATEMENT: Implement a class Complex which represents the
Complex Number data type. Implement the following operations:
1. Constructor (including a default constructor which creates the complex number 0+0i).
2. Overloaded operator+ to add two complex numbers.
3. Overloaded operator* to multiply two complex numbers.
4. Overloaded << and >> to print and read Complex Numbers.
THEORY:
Operator Overloading
It is a specific case of polymorphism where different operators have different
implementations
depending on their arguments. In C++ the overloading principle applies not only to functions,
but to
operators too. That is, of operators can be extended to work not just with built-in types but
also classes.
A programmer can provide his or her own operator to a class by overloading the built-in
operator to
perform some specific computation when the operator is used on objects of that class.
An Example of Operator Overloading
Complex a(1.2,1.3); //this class is used to represent complex numbers
Complex b(2.1,3); //notice the construction taking 2 parameters for the real and imaginary
part
Complex c = a+b; //for this to work the addition operator must be overloaded
Arithmetic Operators
Arithmetic Operators are used to do basic arithmetic operations like addition, subtraction,
multiplication, division, and modulus.
The following table list the arithmetic operators used in C++.
Operator Action
+ Addition
- Subtraction
* Multiplication
/ Division
5|P a g e
Object Oriented Programming and Computer Graphics Lab
% Modulus
With C++ feature to overload operators, we can design classes able to perform operations
using
standard operators. Here is a list of all the operators that can be overloaded:
Over loadable operators
+ - * / = <> += -= *= /= <<>>
<<= >>= == !=<=>=++--% & ^ ! |
~ &= ^= |= && || %= []
• The operator keyword declares a function specifying what operator-symbol means when
applied to
instances of a class. This gives the operator more than one meaning, or "overloads" it. The
compiler
distinguishes between the different meanings of an operator by examining the types of its
operands.
Syntax:
return_typeclass_name :: operator op(arg_list)
{
//function body
}
where,
• Return type is the value returned by the specified operation
• op is the operator to be overload.
• op is proceeding by the keyword operator.
• operator op is the function name
Process of the overloading has 3 steps
1. Create a class that define a data types that is used in the overloading operation 2. Declare
the operator
function operator op() in the public part of the class.
It may be either a member function or a friend function.
3. Define the operator function to implement the required operation
e.g.
Overloading Binary operators:
A statement like
C = sum (A, B); // functional notation
This functional notation can be replaced by a natural looking expression
Complex No 1:
Real Part :5
Imaginary part :4
Complex No 2:
Real Part :3
Imaginary part :4
Facilities:
Linux Operating Systems, G++
ALGORITHM:
Step 1: Start the program
6|P a g e
Object Oriented Programming and Computer Graphics Lab
Step 5: Define the overloaded functions such as +, -,/,* and the display function For
Addition:
Step 7: Create a menu for addition, multiplication of complex numbers and display the result
Step 8:Depending upon the choice from the user the arithmetic operators will invoke the
overloaded operator automatically and returns the result
q3 – Using concept of operator overloading add the 2 objects and generate and display sum.
q4 – Subtract the 2 objects and generate and display difference.
CONCLUSION:
Thus, we have studied and implemented concept of operator overloading for addition,
subtraction, multiplication of two complex numbers.
7|P a g e
Object Oriented Programming and Computer Graphics Lab
Questions:
1. What is operator overloading?
2. What are the rules for overloading the operators?
3. State clearly which operators are overloaded and which operator are not overloaded?
4.State the need for overloading the operators.
5. Explain how the operators are overloaded using the friend function.
6.What is the difference between “overloading” and “overriding”?
7. What is operator function? Describe the syntax?
8|P a g e
Object Oriented Programming and Computer Graphics Lab
Assignment No: 2
THEORY:
Constructor:
A special method of the class that will be automatically invoked when an instance of the class
is created
is called a constructor.
Following are the most useful features of constructor.
1) Constructor is used for Initializing the values to the data members of the Class.
2) Constructor is the one whose name is same as the name of the class.
3) Constructor gets Automatically called when an object of class is created.
4) Constructors never have a Return Type, even void.
5) Constructor is of Default, Parameterized and Copy Constructors.
The various types of Constructor are as follows: -
Constructors can be classified into 3 types
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
1. Default Constructor: -
Default Constructor is also called an Empty Constructor which has no arguments and It is
Automatically
called when we create the object of class but Remember name of Constructor is same as
name of class
and Constructor never declared with the help of Return Type. Means we can’t declare a
Constructor with
the help of void Return Type., if we never Pass or declare any Arguments then this is called
the Copy
Constructors.
2. Parameterized Constructor: -
This is another type constructor which has some Arguments and the same name as class name
but it uses
some Arguments So For this, we have to create an object of Class by passing some
Arguments at the time
9|P a g e
Object Oriented Programming and Computer Graphics Lab
of creating an object with the name of class. When we pass some Arguments to the
Constructor then this
will automatically pass the Arguments to the Constructor and the values will be retrieved by
the
Respective Data Members of the Class.
3. Copy Constructor:
This is also another type of Constructor. In this Constructor we pass the object of class into
the Another Object of Same Class. As name Suggests you Copy, means Copy the values of
one Object into another Object of Class. This is used for Copying the values of class object
into another object of class So we call them as Copy Constructor and For Copying the values
We have to pass the name of object whose values we wants to Copying and When we are
using or passing an Object to a Constructor then we must have to use the & Ampersand or
Address Operator. Destructor: As we know that Constructor is that which is used for
Assigning Some Values to data Members and For Assigning Some Values this May also
used Some Memory so that to free up the Memory which is Allocated by Constructor,
destructor is used which gets Automatically Called at the End of Program and we doesn’t
have to Explicitly Call a Destructor and Destructor Can’t be Parameterized or a Copy This
can be only one Means Default Destructor which Have no Arguments. For Declaring a
Destructor, we have to use ~tiled Symbol in front of the Destructor
int main()
Static members
A class can contain static members, either data or functions.
A static member variable has following properties:
● It is initialized to zero when the first object of its class is created.
● No other initialization is permitted.
● Only one copy of that member is created for the entire class and is shared by all the objects
of that
class.
● It is the visible only within the class but its lifetime is the entire program
Static data members of a class are also known as "class variables", because there is only one
unique value for all the objects of that same class. Their content is not different from one
object static members have the same properties as global variables but they enjoy class scope.
For that reason, and to avoid them to be declared several times, we can only include the
prototype (its declaration) in the class declaration but not its definition (its initialization). In
order to initialize a static data-member we must include a formal definition outside the class,
in the global scope of this class to another. Because it is a unique variable value for all the
objects of the same class, it can be referred to as a member of any object of that class or even
directly by the
class name (of course this is only valid for static members)
10 | P a g e
Object Oriented Programming and Computer Graphics Lab
Static member functions are considered to have class scope. In contrast to non-static member
functions, these functions have no implicit this argument; therefore, they can use only static
data members, enumerators, or nested types directly. Static member functions can be
accessed without using an object of the corresponding class type. The following restrictions
apply to such static functions:
1. They cannot access non static class member data using the member-selection operators (.
or – >).
2. They cannot be declared as virtual.
3. They cannot have the same name as a non-static function that has the same argument
types.
Friend functions:
In principle, private and protected members of a class cannot be accessed from outside the
same class in which they are declared. However, this rule does not affect friends. Friends are
functions or classes declared as such. If we want to declare an external function as friend of a
class, thus allowing this function to have access to the private and protected members of this
class, we do it by declaring a prototype of this external function within the class, and
preceding it with the keyword friend.
Properties of friend function:
● It is not in the scope of the class to which it has been declared as friend.
● Since it is not in the scope of the class, it cannot be called using the object of that class
● It can be invoked like a normal function w/o the help of any object.
● It can be declared in private or in the public part of the class.
● Unlike member functions, it cannot access the member names directly and has to use an
object name and dot operator with each member name
// friend functions
#include <iostream>
using namespace std;
class CRectangle
{
11 | P a g e
Object Oriented Programming and Computer Graphics Lab
12 | P a g e
Object Oriented Programming and Computer Graphics Lab
Pointers:
A pointer is a derived data type that refers to another data variable by storing the variables
memory address rather than data. Declaration of pointer variable is in the following form :
Data_type * ptr_var;
Eg int *ptr;
Here ptr is a pointer variable and points to an integer data type.
We can initialize pointer variable as follows
int a, *ptr; // declaration
ptr = &a //initialization Pointers to objects:
Consider the following
eg item X; // where item is class and X is object
Similarly, we can define a pointer it_ptr of type item as follows
Item *it_ptr ;
Object pointers are useful in creating objects at runtime. We can also access public members
of the
class using pointers.
Eg item X;
item *ptr = &X;
the pointer ‘ptr ‘is initialized with the address of X.
we can access the member functions and data using pointers as follows
ptr->getdata();
ptr->show();
this pointer: C++ uses a unique keyword called this to represent an object that invokes a
member
function. thisis a pointer that points to the object for which this function was called. This
unique pointer
is automatically passed to a member function when it is called. Important notes on this
pointer:
● this pointer stores the address of the class instance, to enable pointer access of the members
to the
13 | P a g e
Object Oriented Programming and Computer Graphics Lab
q1 –take values of the 2 polynomials in the 2 different objects of classes and choose
operation to perform.
q3 – Using concept of operator overloading add the 2 objects and generate and display.
q4 – Multiply the 2 objects and generate and display the multiplication.
q5 – Enter another polynomial and call function eval.
q6 – Enter new polynomial and call calc() display result. Q7- Error handling in operator
qe-End state
14 | P a g e
Object Oriented Programming and Computer Graphics Lab
CONCLUSION:
Hence, we have successfully studied concept of constructor, default constructor, copy
constructor, destructor, static member functions, friend class, this pointer, inline code and
dynamic memory allocation operators-new and delete.
Questions:
1. What is static Function?
2. What is a friend function? State the advantage of using the friend function.
3. What is a friend class? Explain with examples.
4. Explain with examples pointers to objects.
5. What is this pointer? Explain with examples.
6. State the advantages of this pointer.
7. What are inline functions?
15 | P a g e
Object Oriented Programming and Computer Graphics Lab
Assignment No: 3
THEORY:
Inheritance:
Inheritance in Object Oriented Programming can be described as a process of creating new
classes from existing classes. New classes inherit some of the properties and behaviour of the
existing classes. An existing class that is "parent" of a new class is called a base class. New
class that inherits properties of the base class is called a derived class. Inheritance is a
technique of code reuse. It also provides possibility to extend existing classes by creating
derived classes.
The basic syntax of inheritance is:
Public:
This inheritance mode is used mostly. In this the protected member of Base class
becomes protected members of Derived class and public becomes public.
Protected:
In protected mode, the public and protected members of Base class becomes protected
members of Derived class.
Private:
In private mode the public and protected members of Base class become private members of
Derived class.
Types of Inheritance
16 | P a g e
Object Oriented Programming and Computer Graphics Lab
Multiple Inheritance:
In this type of inheritance a single derived class may inherit from two or more than two
base classes.
Syntax:
classsubclass_name : access_mode base_class1, access_mode base_class2, ....
{
//body of subclass
};
// Multiple Inheritence
#include <iostream>
usingnamespacestd;
classVehicle {
public:
Vehicle()
{
cout<< "This is a Vehicle"<<endl;
}
};
classFourWheeler {
public:
FourWheeler()
{
cout<< "This is a 4 wheeler Vehicle"<<endl;
17 | P a g e
Object Oriented Programming and Computer Graphics Lab
}
};
classCar: publicVehicle, publicFourWheeler
{
};
int main()
{
Car obj;
return 0;
}
Output:
This is a Vehicle
This is a 4 wheeler Vehicle
Multilevel Inheritance:
In this type of inheritance the derived class inherits from a class, which in turn
inherits from some other class. The Super class for one, is sub class for the
other.Assignment operator
// Multilevel Inheritance
#include <iostream>
using namespace std;
classVehicle
{
public:
Vehicle()
{
cout<< "This is a Vehicle"<<endl;
}
};
Class fourWheeler : public Vehicle
{ public:
fourWh
eeler()
{
cout<<"Objects with 4 wheels are vehicles"<<endl;
}
};
Class Car: public fourWheeler{
public:
car()
{
cout<<"Car has 4 Wheels"<<endl;
}
};
int main()
{
Car obj;
return0;
}
18 | P a g e
Object Oriented Programming and Computer Graphics Lab
output:
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels
Hierarchical Inheritance:
In this type of inheritance, multiple derived classes inherits from a single base class. //
Hierarchical Inheritance
classVehicle
{
public:
Vehicle()
{
cout<< "This is a Vehicle"<<endl;
}
};
classCar: publicVehicle
{
};
classBus: publicVehicle
{
};
intmain()
{
Car obj1;
Bus obj2;
return0;
}
Output:
This is a Vehicle
This is a Vehicle
Hybrid Inheritance:
Hybrid Inheritance is combination of any 2 or more types of inheritances.
//Hybrid Inheritance
#include <iostream>
using namespace std;
classVehicle
{
public:
Vehicle()
{
cout<< "This is a Vehicle"<<endl;
}
};
classFare
{
public:
Fare()
{
cout<<"Fare of Vehicle\n";
}
19 | P a g e
Object Oriented Programming and Computer Graphics Lab
};
classCar: publicVehicle
{
};
classBus: publicVehicle, publicFare
{
};
int main({
Bus obj2;
return0;
}
Output:
This is a Vehicle
Fare of Vehicle
Exception Handling:
Exception handling is part of C++ and object oriented programming. they are added in C++
to handle the unwanted situations during program execution. If we do not type the program
correctly then to might result in errors. Main purpose of exception handling is to identify and
report the runtime error in the program.
Famous examples are divide by zero, array index out of bound error, file not found, device
not
found, etc.
C++ exception handling is possible with three keywords iz. try, catch and throw. Exception
handling performs the following tasks:-
•Find the problem in the given code. It is also called as hit exception.
• It informs error has occurred. It is called as throwing the exception.
• We receive the roe info. It is called as catching the exception.
•It takes the corrective action.It is called as exception handling.
TRY:- It is block code in which there are chances of runtime error.This block is followed by
one or
more catch block.Most error prone code is added in try block.
CATCH:- This is used to catch th exception thrown by the try blok. In catch block we take
corrective action on throwing exception. If files are openend , we can take corrective action
likeclosing file handles,closing database connetions,saving unsaved work ,etc.
THROW:- Program throws exception when problem occurs.It is possible with throw
keyword. SNYTAX:=
//normal program code
try{
throw exception
}
catch(argument)
{
...
...
}
//rest of the code
20 | P a g e
Object Oriented Programming and Computer Graphics Lab
// Exception
#include
<iostream>
using
namespace
std; int main()
{
int x = -1;
// Some code
cout<< "Before try \n";
try {
cout<< "Inside try \n";
if (x < 0)
{
throw x;
cout<< "After throw (Never executed) \n";
}
}
catch (int x ) {
cout<< "Exception Caught \n";
}
cout<< "After catch (Will be executed) \n";
return 0;
}
Output:
Before try
Inside try
Exception Caught
After catch (Will be executed)
Algorithm:
1. Start.
2. Create classes Publication, book and tape.
3 .Publication class having data members title, price.
4.Class Book having data members pages and member functions getdata() and pudata().
5. Class Tape having data members minutes and member functions getdata() and
pudata(). 6. Create an object bof class book and object t of class tape.
7. Stop.
I
: A class publication that stores the title (a string) and price (type float) of publications.
Derives two classes Book and Tape.
Display title and price from publication class. The result in following format:
Enter Title: OOP
Enter Price: 300
Enter Pages: 250
21 | P a g e
Object Oriented Programming and Computer Graphics Lab
Enter Minutes: 60
Title: OOP
Price: 300
Pages: 250
Title: POP
Price: 200
Minutes: 60
Conclusion:
Hence, we have successfully studied concept of inheritance and exception
handling.
CONCLUSION:
Hence, we have successfully studied concept of Inheritance, types of inheritance, Exception
Handling.
Questions:
1. What is Inheritance?
2. What are types of Inheritance?
3. What is Single Inheritance?
4. What is Multiple Inheritance?
5. What is Multilevel Inheritance?
6. What is Exception handling?
7. What are try catch block of exception handling?
22 | P a g e
Object Oriented Programming and Computer Graphics Lab
Assignment Number: 4
TITLE/PROBLEM STATEMENT: Write a C++ program that creates an output file, writes
information to it, closes the file, open it again as an input file and read the information from
the file.
1.InputStream
Input Streams are used to hold input from a data producer, such as a keyboard, a file, or a
network. The source stream that provides data to the program is called the input stream. A
program extracts the bytes from the input stream. In most cases the standard input device is
the keyboard. With the cin and “extraction” operator ( >>) it is possible to read input from the
keyboard.
2.OutputStream
Output Streams are used to hold output for a particular data consumer, such as a monitor, a
file, or a printer. The destination stream that receives data from the program is called the
output stream. A program inserts the bytes into an output stream. By default, the standard
output of a program points at the screen. So with the cout operator and the “insertion”
operator (<<) you can print a message onto the screen. the iostream standard library provides
cin and cout methods for reading from standard input and writing to standard output
respectively. file handling provides three new data types:
ofstream This data type represents the output file stream and is used to create files and
to write information to files.
ifstream This data type represents the input file stream and is used to read information
from files.
fstream This data type represents the file stream generally, and has the capabilities of
both ofstream and ifstream which means it can create files, write information
to files, and read information from files.
23 | P a g e
Object Oriented Programming and Computer Graphics Lab
ios::app Append mode. In this All output to that file to be appended to the end.
ios::ate Open a file for output and move the read/write control to the end of thefile.
ios::trunk If the file already exists, its contents will be truncated before opening the file.
●You can combine two or more of these values by ORing them together.
●For example, if you want to open a file in write mode and want to truncate it in case it
already exists, following will be the syntax:
ofstreamoutfile;
Similar way, you can open a file for reading and writing purpose asfollows: fstreamafile;
afile.open("file.dat", ios::out | ios::in );
Closing a File
●When a C++ program terminates it automatically closes flushes all the streams, release all
the allocated memory and close all the opened files
●It is always a good practice that a programmer should close all the opened files before
program termination.
●Following is the standard syntax for close() function, which is a member of fstream,
ifstream, and ofstream objects. void close();
Writing to a File
●While doing C++ programming, you write information to a file from your program using
the stream insertion operator (<<) just as you use that operator to output information to the
screen.
24 | P a g e
Object Oriented Programming and Computer Graphics Lab
●The only difference is that you use an ofstream or fstream object instead of the cout object.
Algorithm:
1. Start
2. Create aclass
3. Define data members roll number andname.
4.Define accept() to take name and roll number fromuser.
5. Define display() to display therecord.
6. In main() create the object of class and fstream class.
7.Take a limit from user in nvariable.
8. Open the file in out mode , call accept() to take record from user,then call write() to write
that record into
the file and at the end close that file.
9. Open the file in in mode, read the record from the file ,call display() function to display the
record and at
the end close that file. 10. Stop
Input:
how many record
you want3
1 abc
2 pqr
3 xyz
Output:
name=abc
Roll=1
name=pqr
Roll=2
name=xyz
Roll=3
CONCLUSION:
Hence, we have successfully studied concept of File Handling.
Questions:
1. What is file handling?
2. What are the different benefits of file handling?
3. What is fstream class?
25 | P a g e
Object Oriented Programming and Computer Graphics Lab
26 | P a g e
Object Oriented Programming and Computer Graphics Lab
Assignment No: 05
TITLE/PROBLEM STATEMENT: Write a function template for selection sort that inputs,
sorts and outputs an integer array and a float array.
THEORY:
Templates
Templates are the foundation of generic programming, which involves writing code in a
way that is independent of any particular type.
A template is a blueprint or formula for creating a generic class or a function. The library
containers like iterators and algorithms are examples of generic programming and have
been developed using template concept. There is a single definition of each container, such
as vector, but we can define many different kinds of vectors for example, vector <int> or
vector <string>.
You can use templates to define functions as well as classes, let us see how do they work:
Function Template:
The general form of a template function definition is shown here:
template <class type> ret-type func-name(parameter list)
{
// body of function
}
Here, type is a placeholder name for a data type used by the function. This name can be
used within the function definition.
The following is the example of a function template that returns the maximum of two values:
#include
<iostream>
#include
<string>
using
namespace
std;
template <typename T>
inline T const& Max (T const& a, T const& b)
{
return a < b ? b:a;
}
int main ()
{
inti = 39; int j = 20;
cout<< "Max(i, j): " << Max(i, j)
<<endl; double f1 =13.5;
double f2 =20.7;
cout<< "Max(f1, f2): " << Max(f1, f2)
<<endl; string s1 = "Hello";
27 | P a g e
Object Oriented Programming and Computer Graphics Lab
string s2 = "World";
cout<< "Max(s1, s2): " << Max(s1, s2)
<<endl; return 0;
}
If we compile and run above code, this would produce the following result:
Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World
Class Template:
Just as we can define functionb templates, we can also define class templates. The general
form
of a generic class declaration is shown here:
template <class type> class class-name
{
.
.
.
}
Here, type is the placeholder type name, which will be specified when a class is instantiated.
You can define more than one generic data type by using a comma-separated list.
Following is the example to define class Stack<> and implement generic methods to push
and
pop
the elements from the stack:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>
using namespace std;
template <class T> class Stack
{
private:
vector<T>elems; // elements
public:
void push(T const&); //push element
voidpop(); // pop element
Ttop()const; // return top element bool empty()const
{ // return
true if empty.
returnelems.em
pty();
}
};
template <class T>
void Stack<T>::push (T const&elem)
{
// append copy of passed element
elems.push_back(elem);
}
28 | P a g e
Object Oriented Programming and Computer Graphics Lab
template<class T>
void Stack<T>::pop ()
{
if (elems.empty())
{
throw out_of_range("Stack<>::pop(): empty stack");
}
// remove last element
elems.pop_back();
}
template <class T>
T Stack<T>::top () const
{
if (elems.empty())
{
throw out_of_range("Stack<>::top(): empty stack");
}
// return copy of last element
return elems.back();
}
int main()
{
try
{
Stack<int> intStack; // stack of ints Stack<string>stringStack; // stack of strings
// manipulate int stack int Stack.push(7);
cout<<intStack.top() <<endl;
// manipulate string stack stringStack.push("hello");
cout<<stringStack.top() <<std::endl; stringStack.pop();
stringStack.pop();
}
catch (exception const& ex)
{
cerr<< "Exception: " <<ex.what()
<<endl; return -1;
}
}
If we compile and run above code, this would produce the following result: 7
hello
Exception: Stack<>::pop(): empty stack
Selection Sort:
Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2)
time complexity, making it inefficient on large lists, and generally performs worse than the
similar insertion sort. Selection sort is noted for its simplicity, and it has performance
29 | P a g e
Object Oriented Programming and Computer Graphics Lab
ALGORITHM:
Algorithm:
1.Start
2.Declare the template parameterT.
3.Define template function for selectionsort.
4.In main() Define two arrays, one for integer and another for float. and take a input for both
the arrays and call sorting function template to sort the number.
5.Stop
Input:
Selection sort Integer Element Enter how many elements you want 5
Enter the Integer element 7
5
8
9
3
Float Element
Enter how many elements you want 5
Enter the float element 3.8
9.4
5.5
2.2
6.7
Output:
Sorted list= 3 5 7 8 9
For the first position in the sorted list, the whole list is scanned sequentially. The first
position where 14 is stored presently, we search the whole list and find that 10 is the lowest
value.
So we replace 14 with 10. After one iteration 10, which happens to be the minimum value in
the list, appears in the first position of sorted list.
30 | P a g e
Object Oriented Programming and Computer Graphics Lab
For the second position, where 33 is residing, we start scanning the rest of the list in linear
manner.
We find that 14 is the second lowest value in the list and it should appear at the second place.
We swap these values.
After two iterations, two least values are positioned at the beginning in the sorted manner.
The same process is applied on the rest of the items in the array.
Pictorial depiction of entire sorting process is as follows −
Sorted list=
2.2 3.8 5.5 6.7 9.4
Conclusion:
Hence, we have studied concept of Function Template.
Questions:
1. What is template?
2. What is Function template?
3. What is Class template?
4. Explain template with function overloading.
5. Explain template with non-type argument.
31 | P a g e
Object Oriented Programming and Computer Graphics Lab
Assignment No: 06
TITLE/PROBLEM STATEMENT: Write C++ program using STL for sorting and
searching user defined records such as personal records (Name, DOB, Telephone number etc)
using vector container.
OR
Write C++ program using STL for sorting and searching user defined records such as Item
records (Item code, name, cost, quantity etc) using vector container.
THEORY:
STL:
The Standard Template Library (STL) is a set of C++ template classes to provide common
programming data structures and functions such as lists, stacks, arrays, etc. It is a library of
container classes, algorithms, and iterators. It is a generalized library and so, its components
are parameterized.
A working knowledge of template classes is a prerequisite for working with STL.
STL has four components
• Algorithms
• Containers
• Functions
• Iterators
Algorithms
• The algorithm defines a collection of functions especially designed to be used on ranges of
elements.They act on containers and provide means for various operations for the contents of
the containers.
• Algorithm
• Sorting
• Searching
• Important STL Algorithms
• Useful Array algorithms
• Partition Operations
• Numeric
Containers
• Containers or container classes store objects and data. There are in total seven standard
“firstclass”
container classes and three container adaptor classes and only seven header files that
provide access to these containers or container adaptors.
• Sequence Containers: implement data structures which can be accessed in a sequential
manner.
• vector
32 | P a g e
Object Oriented Programming and Computer Graphics Lab
• list
• deque
• arrays
• forward_list( Introduced in C++11)
• Container Adaptors : provide a different interface for sequential containers.
• queue
• priority_queue
• stack
• Associative Containers : implement sorted data structures that can be quickly searched
(O(log
n) complexity).
• set
• multiset
• map
• multimap
• Unordered Associative Containers : implement unordered data structures that can be
quickly searched
• unordered_set
• unordered_multiset
• unordered_map
• unordered_multimap
Functions
The STL includes classes that overload the function call operator. Instances of such classes
are called function objects or functors. Functors allow the working of the associated function
to be customized with the help of parameters to be passed.
Iterators
• As the name suggests, iterators are used for working upon a sequence of values. They are
the
major feature that allow generality in STL.
Utility Library
• Defined in header <utility>.
• pair
Sorting:
It is one of the most basic functions applied to data. It means arranging the data in a particular
fashion, which can be increasing or decreasing. There is a builtin function in C++ STL by the
name of sort(). This function internally uses IntroSort. In more details it is implemented using
hybrid of QuickSort, HeapSort and InsertionSort.By default, it uses QuickSort but if
QuickSort is doing unfair partitioning and taking more than N*logN time, it switches to
HeapSort and when the array size becomes really
small, it switches to InsertionSort.
The prototype for sort is :
sort(startaddress, endaddress)
33 | P a g e
Object Oriented Programming and Computer Graphics Lab
34 | P a g e
Object Oriented Programming and Computer Graphics Lab
Algorithm:
1. Start.
2. Give a header file to use ‘vector’.
3. Create a vector naming ‘personal_records’.
4. Initialize variables to store name, birth date and telephone number.
5. Using iterator store as many records you want to store using predefined functions as
push_back().
6. Create another vector ‘item_record’
35 | P a g e
Object Oriented Programming and Computer Graphics Lab
7. Initialize variables to store item code, item name, quantity and cost.
8. Using iterator and predefined functions store the data.
9. Using predefined function sort(), sort the data stored according to user requirements.
10. Using predefined function search, search the element from the vector the user wants to
check.
11. Display and call the functions using a menu.
12. End.
Input:
Personnel information such as name, DOB, telephone number.
Output:
Conclusion:
Hence, we have successfully studied the concept of STL(Standard Template Library) and
how it makes many data structures easy. It briefs about the predefined functions of STL and
their uses such a search() and sort().
Questions:
1. What is STL?
2. What are four components of STL?
3. What is Sorting?
4. What is Searching?
5. What vector container?
36 | P a g e
Object Oriented Programming and Computer Graphics Lab
Assignment No: 07
THEORY:
37 | P a g e
Object Oriented Programming and Computer Graphics Lab
map<int,string>mymap;
// mapping integers to strings
mymap[1] = "Hi";
mymap[2] = "This";
mymap[3] = "is";
mymap[4] = "NBN";
// using operator[] to print string
// mapped to integer 4
cout<<mymap[4];
return0;
}
Output:
NBN
ALGORITHM:
1. Start.
2. Give a header file to map associative container.
3. Insert states name so that we get values as population of that state.
4. Use populationMap.insert().
5. Display the population of states.
6. End.
Input:
Information such as state name to map associative container.
Output:
Size of population Map: 5
Brasil: 193 million
China: 1339 million
India: 1187 million
Indonesia: 234 million
Pakistan: 170 million
Indonesia's populations is 234 million
Conclusion:
Hence, we have successfully studied the concept of map associative container
Questions:
38 | P a g e
Object Oriented Programming and Computer Graphics Lab
Assignment No: 08
CONCEPT:
Scan line polygon fill algorithm
THEORY:
Polygon
Polygon is a representation of the surface. It is primitive which is closed in nature. It is
formed using a collection of lines. It is also called as many-sided figure. The lines combined
to form polygon are called sides or edges. The lines are obtained by combining two
vertices. Some of the polygons are
1. Triangle
2. Rectangle
3. Hexagon
4. Pentagon
Types of Polygons
1.Concave
2. Convex
A polygon is called convex of line joining any two interior points of the polygon lies inside
the polygon. A non-convex polygon is said to be concave. A concave polygon has one
interior angle greater than 180°. So that it can be clipped into similar polygons.
39 | P a g e
Object Oriented Programming and Computer Graphics Lab
40 | P a g e
Object Oriented Programming and Computer Graphics Lab
Algorithm
Step 1 : Accept the vertex number and each vertex coordinate as input from user.
Step 2 : Initialize the data structure
a) Create a polygon table having color, edge pointers, coefficients
b) Establish edge table contains information regarding, the endpoint of edges,
pointer to polygon, inverse slope.
c) Create Active edge list. This will be sorted in increasing order of x.
d) Create a flag F. It will have two values either on or off.
Step 3: Perform the following steps for all scan lines
a) Enter values in Active edge list (AEL) in sorted order using y as value
b) Scan until the flag, i.e. F is on using a background color
c) When one polygon flag is on, and this is for surface S1enter color intensity as
I1into refresh buffer
d) When two or image surface flag are on, sort the surfaces according to depth
and use intensity value Sn for the nth surface. This surface will have least z depth value
e) Use the concept of coherence for remaining planes.
Step 4: Stop the process
Conclusion:
We learn and implemented the scan filling algorithm.
Questions:
1. Explain types of Polygon.
2. What are the advantages and disadvantages of Scan fill algorithm?
3. What are different approaches to fill polygon?
41 | P a g e
Object Oriented Programming and Computer Graphics Lab
Assignment No: 09
TITLE/PROBLEM STATEMENT:
Write C++ program to implement Cohen Southerland line clipping algorithm.
CONCEPT:
Cohen Southerland line clipping algorithm.
THEORY:
Cohen Sutherland Algorithm is a line clipping algorithm that cuts lines to portions which
are within a rectangular area. It eliminates the lines from a given set of lines and rectangle
area of interest (view port) which belongs outside the area of interest and clips those
lines which are partially inside the area of interest. Example:
Algorithm
The algorithm divides a two-dimensional space into 9 regions (eight outside regions and
one inside region) and then efficiently determines the lines and portions of lines that are
visible in the central region of interest (the viewport). Following image illustrates the 9
regions:
42 | P a g e
Object Oriented Programming and Computer Graphics Lab
Algorithm:
43 | P a g e
Object Oriented Programming and Computer Graphics Lab
Step 3: If step 2 fails, perform the logical AND operation for both region codes.
Step 3.1: If the result is not 0000, then given line is completely outside.
Conclusion:
Questions:
1. What is the limitation of Cohen Sutherland Line Clipping algorithm?
2. What are the advantages of Cohen Sutherland Line Clipping?
3. Explain Cohen Sutherland Line Clipping Algorithm.
44 | P a g e
Object Oriented Programming and Computer Graphics Lab
Assignment No: 10
TITLE/PROBLEM STATEMENT: Write C++ program to draw the following pattern. Use
DDA line and Bresenham‘s circle drawing algorithm. Apply the concept of encapsulation.
45 | P a g e
Object Oriented Programming and Computer Graphics Lab
Consider a line from (0,0) to (-5,5) . Use DDA algorithm to rasterize of line.
46 | P a g e
Object Oriented Programming and Computer Graphics Lab
Step 1. Accept radius & centre coordinators from user & plot first point on circumference of
circle (x,y)=(0,r)
Step 2. Calculate initial value of decision parameter s=3-2r
Step 3. By octant symmetric property plot pixels until x<y & perform steps If s<=0
Else
Update by s=s+4x+6 & Increase x by 1
s=s+4(x-y)+10
Increase x by 1 Decrease y by 1
Step 4. Determine symmetry point in other octants
Step 5. Move each calculated pixel position (x,y) on circular path centred on (xc,yc) & plot
coordinate values as x=x+xc, y=y+yc
Plot a circle using Bresenham’s Algorithm with radius 3 and center (0,0).
Conclusion:
Hence, we have successfully studied the concept of DDA Line Drawing Algorithm and
Bresenham‘s circle drawing algorithm
Questions:
47 | P a g e
Object Oriented Programming and Computer Graphics Lab
Assignment No: 11
TITLE/PROBLEM STATEMENT: Write C++ program to draw 2-D object and perform
following basic transformations: Scaling, Translation, Rotation. Apply the concept of
operator overloading
CONCEPT:
Basic transformations: Scaling, Translation, Rotation
THEORY:
Transformation means changing some graphics into something else by applying rules. We
can have various types of transformations such as translation, scaling up or down, rotation,
shearing, reflection etc. When a transformation takes place on a 2D plane, it is called 2D
transformation. Transformations play an important role in computer graphics to reposition the
graphics on the screen and change their size or orientation. Translation, Scaling and Rotation
are basic transformations.
1)TRANSLATION:
A translation moves an object to a different position on the screen. You can translate a point
in 2D by adding translation coordinate or translation vector (Tx, Ty) to the original
coordinates.
Consider Initial coordinates of the object O = (Xold, Yold)
New coordinates of the object O after translation = (Xnew, Ynew) Translation vector or Shift
vector = (Tx, Ty)
Xnew = Xold + Tx (This denotes translation towards X axis)
Ynew = Yold + Ty (This denotes translation towards Y axis)
48 | P a g e
Object Oriented Programming and Computer Graphics Lab
In rotation, we rotate the object at particular angle θ (theta) from its original position.
2)ROTATION:
Consider
Initial coordinates of the object O = (Xold, Yold) Initial angle of the object O with respect to
origin = Φ Rotation angle = θ
New coordinates of the object O after rotation = (Xnew, Ynew)
3)SCALING:
Scaling transformation is used to change the size of an object. In the scaling process, you
either expand or compress the dimensions of the object. Scaling can be achieved by
multiplying the original coordinates of the object with the scaling factor (Sx, Sy). If scaling
factor > 1, then the object size is increased. If scaling factor < 1, then the object size is
reduced. Consider
Initial coordinates of the object O = (Xold, Yold)
Scaling factor for X-axis = Sx
49 | P a g e
Object Oriented Programming and Computer Graphics Lab
4)HOMOGENEOUS COORDINATES
50 | P a g e
Object Oriented Programming and Computer Graphics Lab
Conclusion:
51 | P a g e
Object Oriented Programming and Computer Graphics Lab
Assignment No: 12
CONCEPT:
THEORY:
Koch Curve:
The Koch curve fractal was first introduced in 1904 by Helge von Koch. It was one of
the first fractal objects to be described. To create a Koch curve
52 | P a g e
Object Oriented Programming and Computer Graphics Lab
In our curve, middle segment ((x3,y3),(x4,y4)) will not be drawn. Now, in order to find out
coordinates of the top vertex (x,y) of equilateral triangle, we have rotate point (x4,y4) with
respect to arbitrary point (x3,y3) by angle of 60 degree in anticlockwise direction. After
performing this rotation, we will get rotated coordinates (x, y) as:
Step 3: In iteration 2, you will repeat step 2 for every segment obtained in iteration1. In this
way, you can generate Koch curve for any number of iterations.
Snowflake curve:
Snowflake curve is drawn using koch curve iterations. In koch curve, we just have a single
line in the starting iteration and in snowflake curve, we have an equilateral triangle. Draw an
equilateral triangle and repeat the steps of Koch curve generation for all three segments of an
equilateral triangle.
53 | P a g e
Object Oriented Programming and Computer Graphics Lab
Conclusion:
Hence, we have successfully studied the concept of Curves and Fractals
Questions:
54 | P a g e
Object Oriented Programming and Computer Graphics Lab
Assignment No: 13
TITLE/PROBLEM STATEMENT: Write OpenGL program to draw Sun Rise and Sunset.
CONCEPT:
Concept of OpenGL
THEORY:
OpenGL
-OpenGL is acronym for Open Graphics Library.
-OpenGL is a graphics API and not a platform of its own, it requires a language to operate in
and the language of choice is C++
1. OpenGL Utility -
Provides routines for setting up viewing and projections
2. Glut – GLUT (OpenGL Utility Toolkit) –
provides library functions for interacting with the screen. Glut is portable windowing API
and it is not officially part of OpenGL.
55 | P a g e
Object Oriented Programming and Computer Graphics Lab
Conclusion: In the program a screen showing the mountains and sunrise and sunset is
coded using opengl library functions. Thus we learned some concepts of OpenGL
Questions:
1.What is OpenGL?
2.What is the latest version of OpenGL?
3. Write down Open GL primitives.
56 | P a g e
Object Oriented Programming and Computer Graphics Lab
Assignment No: 14
TITLE/PROBLEM STATEMENT: Write C++ program to draw man walking in the rain
with an umbrella. Apply the concept of polymorphism.
CONCEPT:
THEORY:
Computer Animation:
• It is the process used for generating animated images (moving images) using computer
graphics.
• Animators are artists who specialize in the creation of animation.
• From Latin animātiō, "the act of bringing to life"; from animō ("to animate" or "give life
to") and -ātiō ("the act of").
1. Layout of Storyboard: Storyboard layout is the action outline utilized to illustrate the
motion sequence as a set of storyboard comprises a set of rough sketches or a list of basic
concepts for the motion.
2. Definition of Object &Path : The object definition is specified for all participant objects
in action. The objects can be explained in terms of fundamental shapes, related
movements or movement with shapes.
3. Specification of Key Frame: this is the detailed drawing of the scene at an exact time in
the animation sequence. Inside each key frame, all objects are positioned as per to time
for that frame. Several key frames are selected at the extreme positions in the action;
More key frames are given for intricate motion than for easy, slowly varying motions.
4. In-between frames Generation: In-among frames are the middle frames among the key
frames. In common, film needs twenty-four frames per second, and graphic terminals are
refreshed on the rate of 30 to 60 frames per second. Classically the time interval for the
motion is set up hence there are 3 to 5 among for each pair of key frames. Based upon the
speed identified for the motion, several key frames can be duplicated.
Motion Specifications
57 | P a g e
Object Oriented Programming and Computer Graphics Lab
Goal-Directed Systems :
We can specify the motions that are to take place in general
terms that abstractly describe the actions. These systems are referred to as goal directed
because they determine specific motion parameters given the goals of the animation.
For example, We could specify that we want an object to "walk " or to "run" to a
particular destination. Or We could state that we want an object to "pick up " some other
specified object.
Inverse kinematics, specify the initial and final positions of object at specified times and
motion parameters are computed by system.
Dynamic description, require the specification of the forces that produce the velocities abs
accelerations.
58 | P a g e
Object Oriented Programming and Computer Graphics Lab
Conclusion:
Questions:
1. Explain the significance of "Key Frames" in animation. How do they contribute to creating
smooth and realistic motion?
2. What are "Goal-Directed Systems" in animation, and why are they called so? Provide an
example of a scenario where goal-directed animation is appropriate.
3. Differentiate between "Kinematics" and "Dynamics" descriptions in animation. How does
each approach contribute to defining motion in an animation?
59 | P a g e