SE-OOPCG Lab manual
SE-OOPCG Lab manual
LABORATORY MANUAL
2023-24
Subject Code:210247
-: Name of Faculty:-
Prof. Ketan BProf.
Sonali Murumkar
OOP and Computer Graphics Laboratory K.S.E (Sem-I) [23-24]
INDEX
PART-I : OBJECT ORIENTED PROGRAMMING
Suggested List of Laboratory Experiments/Assignments
(All assignments are compulsory)
GROUP A
Sr.No. Title Page Number
1 Implement a class Complex which represents the Complex Number data type.
Implement the following 1. Constructor (including a default constructor which creates
the complex number 0+0i). 2. Overload operator+ to add two complex numbers. 3.
Overload operator* to multiply two complex numbers. 4. Overload operators << and
>> to print and read Complex Numbers
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
Sr.No. Title Page Number
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
Sr.No. Title Page Number
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
Suggested List of Laboratory Experiments/Assignments
(All assignments are compulsory)
GROUP A
Sr.No. Title Page Number
1 Write C++ program to draw a concave polygon and fill it with desired color using
scan fill algorithm. Apply the concept of inheritance.
3 A) Write C++ program to draw the following pattern. Use DDA line and
Bresenham‘s circle drawing algorithm. Apply the concept of encapsulation.
OR
B) Write C++ program to draw the following pattern. Use DDA line and
Bresenham‘s circle drawing algorithm. Apply the concept of encapsulation.
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
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
GROUP A
Arithmetic operations on complex numbers using operator overloading.
Roll No.
Date
Signature
Assignment No: 1
Title: Arithmetic operations on complex numbers using operator overloading
Problem: Implement a class Complex which represents the Complex Number data type.
Implement the following operations:
Statement:
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
Prerequisites: Object Oriented Programming
Objectives: To learn the concept of constructor, default constructor, operator
overloading using member function and friend function.
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
% Modulus
With C++ feature to overload operators, we can design classes able to perform
+ - * / = <> += -= *= /= <<>>
<<= >>= == != <= >= ++ -- % & ^ ! |
~ &= ^= |= && || %= []
To overload an operator in order to use it with classes we declare operator
functions, which are regular functions whose names are the operator keyword
followed by the operator signthat we want to overload. The format is:
type operator operator-symbol (parameters) {/*...*/ }
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 examiningthe 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
Facilities:
Linux Operating Systems, G++
Algorithm:
Step 1: Start the program
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
Input:
Complex numbers with real and imaginary values for two complex numbers.
Example :
Complex No 1: Real Part : 5
Imaginary part : 4
Complex No 2: Real Part : 5
Imaginary part : 4
Output:
ructor value=0+0i Enter the 1st number
Enter the real part2
Enter the imaginary part4
Enter the 2nd number
Enter the real part4
Enter the imaginary part8
The first number is 2+4i
The second number is 4+8i
The addition is 6+12i
The multiplication is -24+32i
Conclusion:
Hence, we have studied concept of operator overloading.
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. When is Friend function compulsory? Give an example?
Roll No.
Date
Signature
Assignment No: 2
Title: Personnel information system using constructor, destructor, static member functions, friend
class, this pointer, inline codeand dynamic memory allocation.
Problem: Develop an object oriented program in C++ to create a database of the personnel
Statement: information system containing the following information: Name, Date of Birth,
Blood group, Height, Weight, Insurance Policy, number, Contact address, telephone number,
driving license no. etc Construct the database with suitable member functions for initializing and
destroying the data viz constructor, default constructor, copy, destructor, static member functions,
friend class, this pointer, inline code and dynamic memory allocation operators-new and delete as
well as exception handling.
Objectives: To learn the concept of constructor, default constructor, copy, destructor, static
member functions, friend class, this pointer, inline code and dynamic memory allocation
operators- new and delete.
Theory:
Constructor:
A special method of the class that will be automatically invoked when an instance of the class is
created is called as 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 that whose name is same as name of 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
2. Parameterized Constructor: - This is another type constructor which has some Arguments
and same name as class name but it uses some Arguments So For this, we have to create object of
Class by passing some Arguments at the time of creating 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 retrieve 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 the another Object of Class .This is used for Copying the values of
class object into an 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 Destructor.
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
class StaticTest
{ private: static int x;
public: static int
count()
{
return x;
}
};
intStaticTest::x = 9;
int main()
{
printf_s("%d\n", StaticTest::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 function
#include<iostream>
Using namespace std;
Class CRectangle
{
int width, height;
public:
void set_values (int, int);
int area () { return (width * height);
}
friend CRectangle duplicate (CRectangle);
};
Pointers:
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
followsint 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 followsItem *it_ptr ;
Object pointers are useful in creating objects at runtime. We can also access public
members of theclass using pointers.
Eg item X;
item *ptr = &X;
the pointer ‘ptr ‘is initialized with address of X.
we can access the member functions and data using pointers
as followsptr->getdata();
ptr->show();
this pointer:
C++ uses a unique keyword called this to represent an object that invokes a member function.
this is a pointer that points to the object for which this function was called. This unique pointer
Roll No.
Date
Signature
Assignment No: 3
Title: Creating a class which uses the concept of inheritance, displays data and data members
and uses the concept of exception handling.
Problem: Imagine a publishing company which does marketing for book and audio cassette
Statement: 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.
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 behavior 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:
Single Inheritance:
In this type of inheritance one derived class inherits from only one base class. It is the most
simplest form of Inheritance.
Syntax:
#include<iostream>
using namespace std;
class Vehicle
Syntax:
classsubclass_name : access_mode base_class1, access_mode base_class2, ....
{
//body of subclass
};
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.
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking..."<<endl;
}
};
class BabyDog: public Dog
{
public:
void weep( ) {
cout<<"Weeping...";
} };
int main(void)
{ BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
return 0;
}
Output:
Eating...
Barking...
Weeping...
Hierarchical Inheritance:
In this type of inheritance, multiple derived classes inherits from a single base class.
#include <iostream>
using namespace std;
class Shape // Declaration of base class.
{
public:
int a;
int b;
void get_data(int n,int m)
{
a= n;
b=
m;
} };
}
Output: Enter the length and breadth of a rectangle:
23
20
Area of the rectangle is : 460
Enter the base and height of the triangle:
2
5
Area of the triangle is : 5
Hybrid Inheritance:
Hybrid Inheritance is combination of any 2 or more types of inheritances
#include <iostream>
using namespace std;
class A
{ protected:
int a;
public:
void get_a()
{
cout << "Enter the value of 'a' : " << endl;
cin>>a;
}
};
class B : public A
{
protected:
int b;
public:
void get_b()
{ cout << "Enter the value of 'b' : " << endl;
cin>>b;
}
};
class C
{ protected:
int c;
public:
void get_c()
{ cout << "Enter the value of c is : " <<endl;
cin>>c;
}
};
class D : public B, public C
{ protected:
int d;
public:
void mul()
{
get_a();
get_b();
get_c();
cout << "Multiplication of a,b,c is : " <<a*b*c<< endl;
}
};
int main()
{ D d;
d.mul();
return 0;
}
Output:
Enter the value of 'a' : 10
Enter the value of 'b' : 20
Enter the value of c is :30
Multiplication of a,b,c is : 6000
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 ot 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 block. In catch block we take
corrective action on throwing exception. If files are open end , we can take corrective action like
closing file handles ,closing database connections ,saving unsaved work ,etc.
THROW:- Program throws exception when problem occurs. It is possible with throw keyword.
Syntax:
//normal program code
try{
throw exception
}
catch(argument)
{
...
...
1. What is Inheritance?
2. What are types of Inheritance?
3. What is Single Inheritance?
4. What is Multiple Inheritance?
5. What is Hierarchical Inheritance?
6. What is Multilevel Inheritance?
7. What is Hybrid Inheritance?
8. What is Exception handling?
9. What are try catch block of exception handling?
GROUP B
Roll No.
Date
Signature
Assignment No: 4
Title: File handing
Problem Statement: Write a C++ program that creates an output file, writes information to it,
closes the file and open it again as an input file and read the information from the file.
Prerequisites: Object Oriented Programming
Objectives: To learn the concept of 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. Input Stream
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. Output Stream
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.iostream standard library provides cin and cout methods for
reading from standard input and writing to standard output respectively.file handling provides
three new datatypes:
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.
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
and ifstream object is used to open a file for reading purpose only.
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.
ios::ate Open a file for output and move the read/write control to the end of
the file.
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.
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.
• The only difference is that you use an ofstream or fstream object instead of the cout object.
file .read ((char *)&V , sizeof (V)); file . Write ((char *)&V , sizeof (V));
Facilities:
Linux Operating Systems, G++
Algorithm:
1. Start
2. Create a class
3. Define data members roll number and name.
4. Define accept() to take name and roll number from user.
5. Define display() to display the record.
6. In main() create the object of class and fstream class.
Input:
how many record you want 3
1 abc
2 pqr
3 xyz
Output:
name=abc
Roll=1
name=pqr
Roll=2
name=xyz
Roll=3
Conclusion:
Hence, we have studied concept of File handing
Questions:
1. What is file handling?
2. What are the different benefits of file handling?
3. What is fstream class?
4. How to create object of fsream class?
5. Explain the syntax of read() ?
6. Explain the syntax of write()?
Roll No.
Date
Signature
Assignment No: 5
Title: Function Template
Problem Statement: Implement a function template selection Sort. Write a program 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>
#incluede<string>
using namespace std;
<typename T>
inline T const& Max (T const& a, T const& b)
{
return a < b ? b:a;
}
Class Template:
Just as we can define function b 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
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.
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 –
GROUP C
Roll No.
Date
Signature
Assignment No:6
Title: Personnel information system using sorting and searching for STL and vector
container.
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.
Objectives: To learn the concept STL, searching, sorting and 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
Containers
•Containers or container classes store objects and data. There are in total seven standard “first-
class” 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
• list
• deque
• arrays
• forward_list( Introduced in C++11)
• Associative Containers : implement sorted data structures that can be quickly searched
(O(log n) complexity).
• set
• multiset
• map
• multimap
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 built in function in C++ STL by the
name of sort( ). This function internally uses Intro Sort. In more details it is implemented using
hybrid of Quick Sort,
Heap Sort and Insertion Sort. By default, it uses Quick Sort but if Quick Sort is doing unfair
partitioning and taking more than N*log N time, it switches to Heap Sort and when the array
size becomes really small, it switches to Insertion Sort. The prototype for sort is :
sort(startaddress, endaddress)
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>
using namespace std;
void show(int a[])
{
for(inti = 0; i < 10; ++i)
cout<< a[i] << " ";
}
int main()
{
int a[10]= {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
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.
Value to find: the target value which we have to search for.
//Searching
#include <algorithm>
#include <iostream>
using namespace std;
void show(int a[], int arraysize)
{ for(int i = 0; i <arraysize; ++i)
cout<< a[i] << " ";
}
int main() {
int a[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
Roll No.
Date
Signature
Assignment No: 7
Title: To use map associative container.
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
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.
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
map<int,string>mymap;
// mapping integers to strings
mymap[1] = "Hi";
mymap[2] = "This";
mymap[3] = "is";
mymap[4] = "KSE";
// using operator[] to print string
// mapped to integer 4
cout<<mymap[4];
return0;
}
Output: KSE
Facilities:
Linux Operating Systems, G++
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 population Map. 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
Conclusion:
Hence, we have successfully studied the concept of map associative container
Questions:
GROUP A
Roll No.
Date
Signature
Assignment No. 1
Title: A concave polygon filling using scan fill algorithm
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.
Theory:
Polygon:
A polygon is a closed planar path composed of a finite number of sequential line
segments. Apolygon is a two-dimensional shape formed with more than three straight lines.
When starting point and terminal point is same then it is called polygon.
Types of Polygons
Concave
Convex
Complex
A convex polygon is a simple polygon whose interior is a convex set. In a convex polygon,
all interior angles are less than 180 degrees.
Complex polygon is a polygon whose sides cross over each other one or more times.
Complex Polygon
2.
If this scan line
i) Does not pass through any of the vertices then its contribution is equal to the number of
b) Taken as 1 if the other end points of the 2 edges lie on the opposite sides of the scan-
line. c)Here will be total contribution is C + V.
Polygon Filling:
For filling polygons with particular colors, you need to determine the pixels falling on the
border of the polygon and those which fall inside the polygon.
Scan fill algorithm:
A scan-line fill of a region is performed by first determining the intersection positions of the
boundaries of the fill region with the screen scan lines n Then the fill colors are applied to
each section of a scan line that lies within the interior of the fill region n The scan-line fill
algorithm identifies the same interior regions as the odd-even rule.
It is an image space algorithm. It processes one line at a time rather than one pixel at a time. It
uses the concept area of coherence. This algorithm records edge list, active edge list. So accurate
bookkeeping is necessary. The edge list or edge table contains the coordinate of two endpoints.
Active Edge List (AEL) contain edges a given scan line intersects during its sweep. The active
edge list (AEL) should be sorted in increasing order of x. The AEL is dynamic, growing and
shrinking
Algorithm
1. Enter values in Active edge list (AEL) in sorted order using y as value
2. Scan until the flag, i.e. F is on using a background color
3. When one polygon flag is on, and this is for surface S1enter color intensity as
I1into refresh buffer
4. 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
5. Use the concept of coherence for remaining planes.
Step4: Stop Algorithm
Input: Enter the no. of edges
100 200 300 400 500 50
Output:
Roll No.
Date
Signature
Assignment No. 2
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 insidethe area of interest.
Example:
Algorithm
The algorithm divides a two-dimensional space into 9 regions (eight outside regions and
one insideregion) and then efficiently determines the lines and portions of lines that are
visible in the central region of interest (the viewport).
As you seen each region is denoted by a 4 bit code like 0101 for the bottom right region
Four Bit code is calculated by comparing extreme end point of given line (x,y) by four co-
ordinatesx_min, x_max, y_max, y_min which are the coordinates of the area of interest (0000)
Calculate the four bit code as follows:
Set First Bit if 1 Points lies to left of window (x < x_min)
Set Second Bit if 1 Points lies to right of window (x > x_max)
Set Third Bit if 1 Points lies to left of window (y < y_min)
Set Forth Bit if 1 Points lies to right of window (y > y_max)
Output:
Conclusion: Hence, we have studied concept of polygon clipping using Cohen Southerland 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?
Roll No.
Date
Signature
Assignment No. 3
Title: Pattern drawing using line and circle.
Problem Statement: Write C++ program to draw a given pattern. Use DDA line and
Bresenham’s circle drawing algorithm. Apply the concept of
encapsulation.
Prerequisites: 1. Basic programming skills of C++
Objectives: To learn and apply DDA line and Bresenham’s circle drawing algorithm
Theory:
DDA Line Drawing Algorithm:
Pixel is a basic element in graphics. To draw a line, you need two end points between which
you candraw a line. Digital Differential Analyzer (DDA) line drawing algorithm is the
simplest line drawing algorithm in computer graphics. It works on incremental method. It
plots the points from starting point of line to end point of line by incrementing in X and Y
direction in each iteration.
DDA line drawing algorithm works as follows:
Step 1: Get coordinates of both the end points (X1, Y1) and (X2, Y2) from user.
Y direction.dx = X2 – X1;
dy = Y2 – Y1;
Step 3: Based on the calculated difference in step-2, you need to identify the number of steps
to putpixel. If dx > dy, then you need more steps in x coordinate; otherwise in y coordinate.
Step 5: Plot the pixels by successfully incrementing x and y coordinates accordingly and
completethe drawing of the line.
Circle is an eight-way symmetric figure. The shape of circle is the same in all quadrants. In
each quadrant, there are two octants. If the calculation of the point of one octant is done,
then the other seven points can be calculated easily by using the concept of eight-way
symmetry. Bresenham’s Circle Drawing Algorithm is a circle drawing algorithm that selects
the nearest pixel position to complete the arc. The unique part of this algorithm is that is
uses only integer arithmetic which makes it significantly faster than other algorithms using
floating point arithmetic.
To draw this pattern, we require two rectangles and one circle. We can use suitable geometry to
get coordinates to draw rectangles and circle. Then we can call DDA line drawing and
Bresenham’s circle drawing algorithms by passing appropriate parameters to get required
pattern.
Input: Enter the co-ordinates of center of circle
Value Of X: 100
Value Of Y: 70
Value Of Radius: 30
Output:
Conclusions: Hence, we have studied that DDA line and Bresenham’scircle drawing
algorithm and apply the concept of encapsulation.
Questions:
1. Explain the derivation of decision parameters in Bresenham’s circle drawing algorithm.
2. Explain the concept of encapsulation with example.
GROUP B
Roll No.
Date
Signature
Assignment No. 4
Title: Basic 2-D Transformations.
Problem Statement: a) Write C++ program to draw 2-D object and perform following basic
transformations: Scaling, Translation, 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.
.
Prerequisites: Basic programming skills of C++
64-bit Open source Linux
Open Source C++ Programming tool like G++/GCC
Objectives: To learn and apply basic transformations on 2-D objects.
Theory:
Transformation means changing some graphics into something else by applying rules. We
can havevarious 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. Transformationsplay an important role in computer graphics to reposition
the graphics on the screen and change theirsize 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 2Dby 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)
This translation is achieved by adding the translation coordinates to the old coordinates of
the objectas-
Xnew = Xold + Tx (This denotes translation towards X
axis) Ynew = Yold + Ty(This denotes translation owards Y
axis)
In Matrix form, the above translation equations may be represented as-
2) Rotation:
In rotation, we rotate the object at particular angle θ (theta) from its original position. 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 originalcoordinates of the object with the scaling factor (S x, 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
- Scaling factor for Y-axis = Sy
- New coordinates of the object O after scaling = (Xnew, Ynew)
rhombus:
Output:
Conclusion: Hence, we have studied that 2-D object and perform following basic transformations:
Scaling, Translation, Rotation. Apply the concept of operator overloading.
Questions:
1. How to rotate any 2-D object about an arbitrary point? Explain in brief.
2. Explain the concept of operator overloading with example.
Roll No.
Date
Signature
Assignment No. 5
Title: Curves and fractals
Problem Statement: 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..
Prerequisites: Basic programming skills of C++
64-bit Open source Linux
Open Source C++ Programming tool like G++/GCC
Objectives: To study curves and fractals.
Theory:
Koch Curve:
The Koch curve fractal was first introduced in 1904 by Helge von Koch. It was one of the
firstfractal 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 by 60°.
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
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
The function presented below (in the "C" language) computes the Hilbert curve. Note that
the curve is symmetrical around the vertical axis. It would therefore be sufficient to draw
half of the Hilbert curve.
Snowflake curve:
Snowflake curve is drawn using koch curve iterations. In koch curve, we just have a single
line in thestarting iteration and in snowflake curve, we have an equilateral triangle. Draw an
equilateral triangleand repeat the steps of Koch curve generation for all three segments of an
equilateral triangle.
Conclusion: Hence, we have studied that to generate Hilbert curve using concept of fractals.
Questions:
1. What is the importance of curves and fractals in computer graphics?
2. What are applications of curves and fractals?
GROUP C
Roll No.
Date
Signature
Assignment No. 6
Title: Implementation of OpenGL functions
Problem Statement: a) Design and simulate any data structure like stack or queue
visualization using graphics. Simulation should include all operations
performed ondesigned 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.
Prerequisites: Basic programming skills of C++
64-bit Open source Linux
Open Source C++ Programming tool like G++/GCC
Objectives: To implement OpenGL functions.
Theory:
OpenGL Basics:
Open Graphics Library (OpenGL) is a cross-language (language independent), cross-
platform (platform independent) API for rendering 2D and 3D Vector Graphics (use of
polygons to represent image). OpenGL is a low-level, widely supported modeling and
rendering software package, availableacross all platforms. It can be used in a range of
graphics applications, such as games, CAD design, or modeling. OpenGL API is designed
mostly in hardware.
Design: This API is defined as a set of functions which may be called by the client
program.Although functions are similar to those of C language but it is language
independent.
Development: It is an evolving API and Khronos Group regularly releases its new
version having some extended feature compare to previous one. GPU vendors may
also provide some additional functionality in the form of extension.
2. OpenGL Utility Library (GLU): built on-top of the core OpenGL to provide important
utilities and more building models (such as qradric surfaces). GLU functions start with a
prefix "glu"(e.g.,
gluLookAt, gluPerspective).
3. OpenGL Utilities Toolkit (GLUT): provides support to interact with the Operating
System (such as creating a window, handling key and mouse inputs); and more building
models (such as sphere and torus). GLUT functions start with a prefix of "glut"
(e.g., glutCreatewindow, glutMouseFunc). GLUT is designed for constructing small to
medium
sized OpenGL programs. While GLUT is well-suited to learning OpenGL and developing
simple OpenGL applications, GLUT is not a full-featured toolkit so large applications
requiring sophisticateduser interfaces are better off using native window system toolkits.
GLUT is simple, easy, and small.
Alternative of GLUT includes SDL.
4. OpenGL Extension Wrangler Library (GLEW): "GLEW is a cross-platform open-
sourceC/C++ extension loading library. GLEW provides efficient run-time mechanisms for
determining which OpenGL extensions are supported on the target platform.
sudo apt-get install freeglut3-dev
Since OpenGL is a graphics API and not a platform of its own, it requires a language to
operate inand the language of choice is C++.
Getting Started with OpenGL:
Overview of an OpenGL Program:
Main
Open window and configure frame buffer (using GLUT for example)
Initialize GL states and display (Double buffer, color mode, etc.)
Loop
Check for events
if window event (resize, unhide, maximize etc.)modify the view report and Redraw else if input
event(keyboard and mouse etc) handle the event (such as move the camera or change the state)
and usually draw the scene
Redraw
Clear the screen (and buffers e.g., z-buffer)
Change states (if desired)
Render
Swap buffers (if double buffer)
OpenGL order of operations
Construct shapes (geometric descriptions of objects – vertices, edges, polygons etc.)
Use OpenGL to
o Arrange shape in 3D (using transformations)
o Select your vantage point (and perhaps lights)
o Calculate color and texture properties of each object
o Convert shapes into pixels on screen
OpenGL Syntax
All functions have the form: gl*
o glVertex3f() – 3 means that this function take three arguments, and f means that
the type ofthose arguments is float.
o glVertex2i() – 2 means that this function take two arguments, and i means that
the type ofthose arguments is integer
All variable types have the form: GL*
o In OpenGL program it is better to use OpenGL variable types (portability)
Glfloat instead of float
Glint instead of int
Drawing in 3D
Depth buffer (or z-buffer) allows scene to remove hidden surfaces. Use
glEnable(GL_DEPTH_TEST) to enable it.
o glPolygonMode( Face, Mode )
Face: GL_FRONT, GL_BACK, GL_FRONT_AND_BACKMode: GL_LINE,
GL_POINT, GL_FILL
o glCullFace( Mode )
Mode: GL_FRONT, GL_BACK, GL_FRONT_AND_BACK
glFrontFace( Vertex_Ordering )
Vertex Ordering: GL_CW or GL_CCW
Viewing transformation
glMatrixMode ( Mode )
Mode: GL_MODELVIEW, GL_PROJECTION, or GL_TEXTURE
glLoadIdentity()
glTranslate3f(x,y,z)
glRotate3f(angle,x,y,z)
glScale3f(x,y,z)
Evolving
Because of its thorough and forward-looking design, OpenGL allows new hardware
innovations to be accessible through the API via the OpenGL extension mechanism. In this
way, innovations appearin the API in a timely fashion, letting application developers and
hardware vendors incorporate new features into their normal product release cycles.
Scalable
OpenGL API-based applications can run on systems ranging from consumer electronics to
PCs, workstations, and supercomputers. As a result, applications can scale to any class of
machine that thedeveloper chooses to target.
Easy to use
OpenGL is well structured with an intuitive design and logical commands. Efficient
OpenGL routinestypically result in applications with fewer lines of code than those that
make up programs generated using other graphics libraries or packages. In addition,
OpenGL drivers encapsulate information about the underlying hardware, freeing the
application developer from having to design for specific hardware features.
Conclusion: Hence, we have studied that OpenGL program to draw Sun Rise and Sunset.
Questions:
1. What is OpenGL Program Explain in details?
2. what are advantages of Developer-driven ?
Roll No.
Date
Signature
Assignment No. 6
Title: Animation using C++
Problem Statement: 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
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.
int main() {
int gd = DETECT, gm;int angle
= 0; double x, y;
Note: In all above programs, you have to perform translation of an image to show animation
effect.
Input:
Output:
Conclusion: Hence, we have studied that bouncing ball using sine wave form.Apply the concept
of polymorphism.
Questions:
1. What is Animation explain in details?
2. What is an 8 Puzzle Program? Explain in details?