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

Oopcgl

oopcgl manual

Uploaded by

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

Oopcgl

oopcgl manual

Uploaded by

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

Savitribai Phule Pune University

Kalyani Charitable Trust’s

Late G. N. Sapkal College of Engineering,


Anjaneri, Nashik-422212

DEPARTMENT OF COMPUTER ENGINEERING

LABORATORY MANUAL

Object Oriented Programming


And
Computer Graphics Lab
SE COMPUTER

SEMESTER III Practical Assessment: 25


Academic Year -2023-24 TW Assessment: 25

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.

2 Develop a program in C++ to create a database of student’s information system containing


the following information: Name, Roll number, Class, Division, Date of Birth, Blood group,
contact address, Telephone number, Driving license no. and other. Construct the database
with suitable member functions. Make use of constructor, default constructor, copy
constructor, destructor, static member functions, friend class, this pointer, inline code and
dynamic memory allocation operators-new and delete as well as exception handling.
3 Imagine a publishing company which does marketing for book and audio cassette versions.
Create a class publication that stores the title (a string) and price (type float) of publications.
From this class derive two classes: book which adds a page count (type int) and tape which
adds a playing time in minutes (type float).
Write a program that instantiates the book and tape class, allows user to enter data and
displays the data members. If an exception is caught, replace all the data member values with
zero values.
Group B

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.

Prof. K. S. Mali Prof. N. R. Wankhade


Subject In-charge HOD (Dept. Of Computer Engg.)

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.

Roll No: Batch: Date:


CONCEPT:
Operator Overloading

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 2: Create a class complex


Step 3: Define the default constructor.
Step 4: Declare the operator function which are going to be overloaded and display function

Step 5: Define the overloaded functions such as +, -,/,* and the display function For
Addition:

(a+bi) + (x + yi) = ((a+x)+(b+y)i)


For Multiplication:
(a+bi) * (x + yi) = (((a*x)-(b*y)) + ((a*y) + (x*b))i)
Step 6: Create objects for complex class in main() function

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

Step 9: Display the result using display function.

STATE TRANSITION DIAGRAM:

q0 – Start program, initialize state.

q1 –take user input state

q2 – Operator extracting stage.

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.

q5 – Multiply the 2 objects and generate and display the multiplication.


q6 – Divide the 2 objects and generate the division and display.
qe-End state
Input:
Complex numbers with real and imaginary values for two complex numbers.

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

TITLE/PROBLEM STATEMENT: Develop a program in C++ to create a database of a


student's information system containing the following information: Name, Roll
number, Class, Division, Date of Birth, Blood group, Contact address, Telephone
number, Driving license no. and other. Construct the database with suitable member
functions. Make use of constructor, default constructor, copy constructor, destructor,
static member functions, friend class, this pointer, inline code and dynamic memory
allocation operators-new and delete as well as exception handling.

Roll No: Batch: Date:


CONCEPT:
Class, functions, constructor, destructor, new operator, delete operator, friend class, inline
function, this pointer.

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)

A static member function has following properties


● A static function can have access to only other static members (fun or var) declared in the
same class
● A static function can be called using the class name instead of its object name Class_name
::fun_name;

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.

E.g., // static members in classes


class Static Test
{
private:
static int x;
public:
static int count ()
{
return x;
}
};
Int static Test::x = 9;
int main ()
{
prints("%d\n", static Test::count());
}
Output:-
9

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

int width, height;


public:
void set_values (int, int);
int area () {return (width * height);
}
friend CRectangle duplicate (CRectangle);
};
void CRectangle::set_values (int a, int b)
{
width = a;
height = b;
}
CRectangle duplicate (CRectanglerectparam)
{
CRectanglerectres;
rectres.width = rectparam.width*2;
rectres.height = rectparam.height*2;
return (rectres);
}
int main () {
CRectanglerect, rectb;
rect.set_values (2,3);
rectb = duplicate (rect);
cout<<rectb.area();
return 0;
}
The duplicate function is a friend of CRectangle. From within that function we have been
able to access the members width and height of different objects of type CRectangle, which
are private members. Notice that neither in the declaration of duplicate() nor in its later use in
main() have we considered duplicate a member of class CRectangle.
Friend classes
Just as we have the possibility to define a friend function, we can also define a class as friend
of another one, granting that second class access to the protected and private members of the
first one.
// friend class
#include <iostream>
using namespace std;
class CSquare;
class CRectangle
{
int width, height;
public:
int area ()
{return (width * height);}
void convert (CSquare a);
};
class CSquare {
private:
int side;
public:

12 | P a g e
Object Oriented Programming and Computer Graphics Lab

void set_side (int a)


{side=a;}
friend class CRectangle;
};
void CRectangle::convert (CSquare a) {
width = a.side;
height = a.side;
}
int main () {
CSquaresqr;
CRectanglerect;
sqr.set_side(4);
rect.convert(sqr);
cout<<rect.area();
return 0;
}
In this example, we have declared CRectangle as a friend of CSquare so that CRectangle
member functions could have access to the protected and private members of CSquare, more
concretely to CSquare::side, which describes the side width of the square..

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

member functions of the class.


● this pointer is not counted for calculating the size of the object.
● this pointers are not accessible for static member functions.
● this pointers are not modifiable.
Algorithm:
1. Start
2. Read personnel information such as Name, Date of Birth, Blood group, Height, Weight,
Insurance
Policy, number, Contact address, telephone number, driving license no..
3. Print all information from database.
4. Stop
Input:
Personnel information such as Name, Date of Birth, Blood group, Height, Weight, Insurance
Policy,
number, contact address, telephone number, driving license no.
Output:
Display personnel information from database. The result in following format:
Name DOB ……. Driving License No
1
2
.
.
N

State Transition diagram:

q0 – Start program, initialize variables.

q1 –take values of the 2 polynomials in the 2 different objects of classes and choose
operation to perform.

q2 – Operator extracting stage.

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

TITLE/PROBLEM STATEMENT: Imagine a publishing company which does marketing


for book and audio cassette versions. Create a class publication that stores the title (a string)
and price (type float) of publications. From this class derive two classes: book which adds a
page count (type int) and tape which adds a playing time in minutes (type float).
Write a program that instantiates the book and tape class, allows user to enter data and
displays the data members. If an exception is caught, replace all the data member values with
zero values.

Roll No: Batch: Date:

CONCEPTS : Inheritance and Exception handling.

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:

Class DerivedClass : accessSpecifier BaseClass

There are 3 access specifiers:


Namely public, private and protected.

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

In C++, we have 5 different types of Inheritance. Namely,


1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance
Single Inheritance:
In this type of inheritance one derived class inherits from only one base class. It is the

16 | P a g e
Object Oriented Programming and Computer Graphics Lab

most simplest form of Inheritance.


Syntax:
class subclass_name : access_modebase_class
{
//body of subclass
}; // Single Inheritence
#include <iostream>
usingnamespacestd;
classVehicle
{
public:
Vehicle()
{
cout<< "This is a Vehicle"<<endl;
}
};
classCar: publicVehicle
{
};
int main()
{
Car obj;
return0;
}
Output:
This is a vehicle

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

Enter Title: POP


Enter Price: 200

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.

Roll No: Batch: Date:

CONCEPTS: File Handling


THEORY:
Stream:
A stream is a sequence of bytes. It acts as source from which the input data can be obtained
or as a destination to which the output data can be sent.

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:

Data Type Description

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

To perform file processing in C++, header file


<iostream> and <fstream> must be included in your C++ source file.
Opening a File
● A file must be opened before you can read from it or write toit.
● Either the ofstream or fstream object may be used to open a file for writing
andifstream object is used to open a file for reading purposeonly.
● Following is the standard syntax for open() function which is a member of fstream,
ifstream and ofstreamobjects.
void open(const char *filename, ios::openmode mode);
● Here, the first argument specifies the name and location of the file to be opened and
the second argument of the open() member function defines the mode in which the
file should be opened.

Mode Flag Description

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::in Open a file for reading.

ios::out Open a file for writing.

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;

outfile.open("file.dat", ios::out | ios::trunc );

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.

Reading from a File


● You read information from a file into your program using the stream extraction operator
(>>) just as
you use that operator to input information from the keyboard.
● The only difference is that you use an ifstream or fstream object instead of the cinobject.
Example
file .read ((char *)&V , sizeof (V)); file . Write ((char *)&V , sizeof (V));
● These function take two arguments. The first is the address of the variable V , and the
second is the
length of that variable in bytes . The address of variable must be cast to type char * (i.e
pointer to
character type) .

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

4. How to create object of fsream class?


5. Explain the syntax of read() ?
6. .Explain the syntax of write()?

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.

Roll No: Batch: Date:

CONCEPTS: Function Template

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

advantages over more complicated algorithms in certain situations, particularly where


auxiliary memory is limited
How selection sort works?
14 33 27 10 35 19 42 44

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.

Roll No: Batch: Date:


CONCEPT:
Standard Template Library(STL)

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

startaddress: the address of the first element of the array


endaddress: the address of the next contiguous location of the last element of the array.
So actually sort() sorts in the range of [startaddress,endaddress)
//Sorting
#include <iostream>
#include <algorithm>
usingnamespacestd;
voidshow(inta[])
{
for(inti = 0; i < 10; ++i)
cout<< a[i] << " ";
}
intmain()
{
inta[10]= {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
cout<< "\n The array before sorting is : ";
show(a);
sort(a, a+10);
cout<< "\n\n The array after sorting is : ";
show(a);
return0;
}
The output of the above program is :
The array before sorting is : 1 5 8 9 6 7 3 4 2 0
The array after sorting is : 0 1 2 3 4 5 6 7 8 9
Searching:
It is a widely used searching algorithm that requires the array to be sorted before search is
applied. The main idea behind this algorithm is to keep dividing the array in half (divide and
conquer) until the element is found, or all the elements are exhausted.
It works by comparing the middle item of the array with our target, if it matches, it returns
true otherwise if the middle term is greater than the target, the search is performed in the left
sub-array.
If the middle term is less than target, the search is performed in the right sub-array.
The prototype for binary search is :
binary_search(startaddress, endaddress, valuetofind)
startaddress: the address of the first element of the array.
endaddress: the address of the last element of the array.
valuetofind: the target value which we have to search for.
//Searching
#include <algorithm>
#include <iostream>
using namespace std;
void show(inta[], intarraysize)
{

34 | P a g e
Object Oriented Programming and Computer Graphics Lab

for(inti = 0; i <arraysize; ++i)


cout<< a[i] << " ";
}
int main()
{
inta[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
intasize = sizeof(a) / sizeof(a[0]);
cout<< "\n The array is : ";
show(a, asize);
cout<< "\n\nLet's say we want to search for 2 in the array";
cout<< "\n So, we first sort the array";
sort(a, a + asize);
cout<< "\n\n The array after sorting is : ";
show(a, asize);
cout<< "\n\nNow, we do the binary search";
if(binary_search(a, a + 10, 2))
cout<< "\nElement found in the array";
else
cout<< "\nElement not found in the array";
cout<< "\n\nNow, say we want to search for 10";
if(binary_search(a, a + 10, 10))
cout<< "\nElement found in the array";
else
cout<< "\nElement not found in the array";
return0;
}
Output:
The array is : 1 5 8 9 0 6 7 3 4 2 0
Let's say we want to search for 2 in the array
So, we first sort the array
The array after sorting is : 0 1 2 3 4 5 6 7 8 9
Now, we do the binary search
Element found in the array
Now, say we want to search for 10
Element not found in the array

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:

Display personnel information from database. The result in following format:


***** Menu *****
1.Insert
2.Display
3.Search
4.Sort
5.Delete
6.Exit
Enter your choice:1
Enter Item Name: bat
Enter Item Quantity:2
Enter Item Cost:50
Enter Item Code:1

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

TITLE/PROBLEM STATEMENT: 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.

Roll No: Batch: Date:

CONCEPT: File Maps

THEORY:

Map associative container:


Map associative container are associative containers that store elements in a mapped fashion.
Each element has a key value and a mapped value. No two mapped values can have same key
values.
map::operator[]
This operator is used to reference the element present at position given inside the operator. It
is similar to the at() function, the only difference is that the at() function throws an out-of-
range exception when the position is not in the bounds of the size of map, while this operator
causes undefined behaviour.
Syntax :
mapname[key]
Parameters :
Key value mapped to the element to be fetched.
Returns :
Direct reference to the element at the given key value.
Examples:
Input : map mymap;
mymap['a'] = 1;
mymap['a'];
Output : 1
Input : map mymap;
mymap["abcd"] = 7;
mymap["abcd"];
Output : 7
//Program
#include <map>
#include <iostream>
#include<string>
using namespace std;
int main()
{
// map declaration

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:

1. What is an associative container in C++?


2. What is map in C++?
3. How to do declare a map?
4. Explain Associative mapping with example?

38 | P a g e
Object Oriented Programming and Computer Graphics Lab

Assignment No: 08

TITLE/PROBLEM STATEMENT: Write C++ program to draw a concave polygon and


fill it with desired color using scan fill algorithm. Apply the concept of inheritance

Roll No: Batch: Date:

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

Following figures shows some polygons

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

Scan fill Algorithm:


This algorithm lines interior points of a polygon on the scan line and these points are done on
or off according to requirement. The polygon is filled with various colors by coloring various
pixels. In below figure polygon and a line cutting polygon in shown. First of all, scanning is
done. Scanning is done using raster scanning concept on display device. The beam starts
scanning from the top left corner of the screen and goes toward the bottom right corner as
the endpoint. The algorithms find points of intersection of the line with polygon while
moving from left to right and top to bottom. The various points of intersection are
stored in the frame buffer. The intensities of such points is keep high. Concept of coherence
property is used. According to this property if a pixel is inside the polygon, then its next pixel
will be inside the polygon.

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.

Roll No: Batch: Date:

CONCEPT:
Cohen Southerland line clipping algorithm.

THEORY:

Cohen Sutherland Algorithm

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

The more efficient Cohen-Sutherland Algorithm performs initial tests on a line to


determine whether intersection calculations can be avoided.

Algorithm:

Step 1 : Assign a region code for two endpoints of given line


Step 2 : If both endpoints have a region code 0000 then given line is completely inside and
we will keep this line.

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.

Step 3.2: Else line is partially inside.


Step 3.2.a: Choose an endpoint of the line that is outside the given rectangle.
Step 3.2.b: Find the intersection point of the rectangular boundary (based on region
code)
Step 3.2.c: Replace endpoint with the intersection point and upgrade the region code.
Step 3.2.d: Repeat step 2 until we find a clipped line either trivially accepted or
rejected.
Step 4: Repeat step 1 for all lines.

Conclusion:

We learn and implemented the Cohen Sutherland Line clipping algorithm.

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.

Roll No: Batch: Date:


CONCEPT:
DDA Line Drawing Algorithm and Bresenham‘s circle drawing algorithm
THEORY:

Description for Scan Conversion


The process of representing continuous graphics object as a collection of discrete pixels is
called Scan Conversion.
For e.g a line is defined by its two end points & the line equation
It is the responsibility of graphics system or the application program to convert each
primitive from its geometric definition into a set of pixels that make up the primitive in
image space. This conversion task is generally referred to as a scan conversion or
rasterization.

DDA Line Drawing Algorithm


Step 1. Read the line end points (𝑥1, y1) and (𝑥2, y2) such that they are not equal. [If equal
then plot that point and exit]
Step 2. Δ𝑥 = |𝑥2 − 𝑥1| and Δ𝑦 = |𝑦2 − 𝑦1|
Step 3. If (Δ𝑥 ≥ Δ𝑦) 𝑡ℎ𝑒𝑛
Length=Δ𝑥
Else
End if
Length=Δ𝑦

45 | P a g e
Object Oriented Programming and Computer Graphics Lab

Step 4. Δ𝑥 = (𝑥2 − 𝑥1)/𝑙𝑒𝑛𝑔𝑡ℎ


Δ𝑦 = (𝑦2 − 𝑦1)/𝑙𝑒𝑛𝑔𝑡ℎ
[This makes either Δ𝑥 or Δ𝑦 equal to 1 because length is either 𝑥2 − 𝑥1 or
𝑦2− 𝑦1 .Therefore, the incremental value for either x or y is one.]
Step 5. 𝑥 = 𝑥1 + 0.5 sign (Δ𝑥)
𝑌 = 𝑦1 + 0.5 sign (Δ𝑦)
[Here, sign function makes the algorithm work in all quadrants. It returns -1, 0, 1 depending
on whether its argument is <0, =0, >0, respectively.]
Step 6. i=1
[begins the loop, in this points are plotted] While ( i ≤ length)
Begin
Plot (integer (x), integer (y))
𝑥 = 𝑥 + Δ𝑥
𝑦 = 𝑦 + Δ𝑦
𝑖=𝑖+1
End.
Stop

Graphical Characteristics inscribed circle in the rectangle.


Given a rectangle of length l & breadth b, we have to find the largest circle that can be
inscribed in the rectangle. /Students are instructed to find out coordinates of the inscribed
rectangle and circle/

Consider a line from (0,0) to (-5,5) . Use DDA algorithm to rasterize of line.

Advantages and Disadvantage of DDA Line drawing Algorithm.

Advantages of DDA Line drawing Algorithm


1.The DDA algorithm is a faster method for calculating pixel positions than direct use of
line equation y = mx+b
2.Very easy to understand

46 | P a g e
Object Oriented Programming and Computer Graphics Lab

Disadvantage of DDA Line drawing Algorithm:


1.The rounding operation & floating point arithmetic are time consuming procedures.
2.The accumulation of round-off error in successive addition of floating point increment can
cause the calculated pixel position to drift away from the true line path for long line segment.

Bresenham’s Circle Drawing Algorithm.

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:

1. What is the use of abs function in DDA Line drawing algorithm?


2. What is the equation to find slope of the line?
3. What do you mean by sharp slope and steep slope?
4. What will happen for DDA Line drawing algorithm if slope of the line is negative?
5. How to find midpoint of line?
6. What are the steps for Bresenham’ Circle Drawing Algorithm?
7. What are the steps for DDA Circle Drawing Algorithm?
8. Explain the difference between DDA & Bresenham’s circle drawing algorithms?

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

Roll No: Batch: Date:

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 Matrix form, the above translation equations may be represented as-

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)

This anti-clockwise rotation is achieved by using the following rotation equations-

Xnew = Xold x cosθ – Yold x sinθ


Ynew = Xold x sinθ + Yold x cosθ

In Matrix form, the above rotation equations may be represented as-

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

Scaling factor for Y-axis = Sy


New coordinates of the object O after scaling = (Xnew, Ynew)

This scaling is achieved by using the following scaling equations-


Xnew = Xold x Sx
Ynew = Yold x Sy
In Matrix form, the above scaling equations may be represented as-

4)HOMOGENEOUS COORDINATES

Matrix multiplication is easier to implement in hardware and software as compared to matrix


addition. Hence we want to replace matrix addition by multiplication while performing
transformation operations. So the solution is homogeneous coordinates , which allows us to
express all transformations (including translation) as matrix multiplications.
To obtain homogeneous coordinates we have to represent transformation matrices in 3x3
matrices instead of 2x2. For this we add dummy coordinate. Each 2 dimensional position
(x,y) can be represented by homogeneous coordinate as (x,y,1).

Translation Matrix (Homogeneous Coordinates representation)


x' 1 0 T x x 
y'  0 1 T  y
   y  

1  0 0 1 1 

Rotation Matrix (Homogeneous Coordinates representation)

x' cos  sin  0  x 


  
y'  sin  cos 0 y
    
1   0 0 1 1 

50 | P a g e
Object Oriented Programming and Computer Graphics Lab

Scaling Matrix (Homogeneous Coordinates representation)

x' Sx 0 0x 


 y'   0 S 0 y
   y  
1   0 0 1 1 

Conclusion:

Hence, we have successfully studied the concept of Basic transformations: Scaling,


Translation, Rotation
Questions:

1. State and explain different 2D transformation?


2. Explain the concept of Homogeneous coordinates?
3. Explain 2D Translation & Scaling?
4. Explain the clockwise and anticlockwise 2D rotation?

51 | P a g e
Object Oriented Programming and Computer Graphics Lab

Assignment No: 12

TITLE/PROBLEM STATEMENT: Write C++ program to generate fractal patterns by


using Koch curves.

Roll No: Batch: Date:

CONCEPT:

Curves and Fractals

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

1. Create a line and divide it into three parts.


2. The second part is now rotated by60°.
3. Add another part which goes from the end of part 2 to the beginning of part 3
4. Repeat step 1 to step 3 with each part of the line.

We will get following Koch curve as number of iteration goes on increasing

52 | P a g e
Object Oriented Programming and Computer Graphics Lab

Step 1: In Iteration 0, we have a horizontal line.


Step 2: In Iteration 1, line is divided into 3 equal parts. Middle part of a line is rotated in 600,
because it forms a perfect an equilateral triangle as shown below:

Here, (x1,y1) and (x2, y2) is accepted from user.


Now, we can see line is divided into 3 equal segments: segment((x1,y1),(x3,y3)),
segment((x3,y3),(x4,y4)),segment((x4,y4),(x2,y2)) in above figure.

Coordinates of middle two points will be calculated as follows: x3 = (2*x1+x2)/3;


y3 = (2*y1+y2)/3; x4 = (x1+2*x2)/3; y4 = (y1+2*y2)/3;

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:

𝑥 = 𝑥3 + (𝑥4 − 𝑥3) ∗ cos 𝜃 + (𝑦4 − 𝑦3) ∗ sin 𝜃


𝑦 = 𝑦3 − (𝑥4 − 𝑥3) ∗ sin 𝜃 + (𝑦4 − 𝑦3) ∗ cos𝜃

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.

The Hilbert curve


The Hilbert curve is a space filling curve that visits every point in a square grid with a size of
2×2, 4×4, 8×8, 16×16, or any other power of 2. It was first described by David Hilbert in
1892. Applications of the Hilbert curve are in image processing: especially image
compression and dithering. It has advantages in those operations where the coherence
between neighbouring pixels is important. The Hilbert curve is also a special version of a
quadtree; any image processing function that benefits from the use of quadtrees may also use
a Hilbert curve.

Cups and joins


The basic elements of the Hilbert curves are what I call "cups" (a square with one open side)
and "joins" (a vector that joins two cups). The "open" side of a cup can be top, bottom, left or
right. In addition, every cup has two end-points, and each of these can be the "entry" point or
the "exit" point. So, there are eight possible varieties of cups. In practice, a Hilbert curve uses
only four types of cups. In a similar vein, a join has a direction: up, down, left or right.

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:

1.What is the importance of curves and fractals in computer graphics?


2.What are applications of curves and fractals?

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.

Roll No: Batch: Date:

CONCEPT:

Concept of OpenGL

THEORY:

OpenGL
-OpenGL is acronym for Open Graphics Library.

-OpenGL was developed in 1990 by silicon graphics inc.

-OpenGL is a cross-language, cross-platform application programming interface (API) for


rendering 2D and 3D vector graphics. The API is typically used to interact with a graphics
processing unit (GPU), to achieve hardware-accelerated rendering

-OpenGL is a basically Graphics rendering API which is operating system independent,


window system independent and has high-quality colour images composed of geometric and
image primitives.

-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++

-OpenGL gives the programmer an interface with the graphics hardware.

-OpenGL API implementation provides you set of libraries.

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.

How to install OpenGL on out Ubuntu OS


GLUT (OpenGL Utility Toolkit) depends upon OpenGL and a number of other related
libraries, if we install GLUT then OpenGL will be automatically be installed.
Run the following commands to install OpenGL.
-$ sudo apt-get update

55 | P a g e
Object Oriented Programming and Computer Graphics Lab

-$ sudo apt-get install libglu1-mesa-dev freeglut3-dev mesa-common-dev

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.

Roll No: Batch: Date:

CONCEPT:

Concept of Computer Animation

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").

Design of Animation Sequences

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

In Various ways in which motions of objects can be specified as:

57 | P a g e
Object Oriented Programming and Computer Graphics Lab

Direct Motion Specification:


Here the rotation angles and translation vectors are
explicitly given. Then the geometric transformation matrices are applied to transform
coordinate positions. We can approximate the path of a bouncing ball with a damped,
rectified, sine curve

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.

Kinematics and Dynamics :


Kinematics description, specify the animation by giving motion parameters (position,
velocity and acceleration) No reference to causes or goals of the motions

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:

Hence, we have successfully studied the concept of Animation

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

You might also like