OOP - Lab Manual
OOP - Lab Manual
Practical for the subject Object Oriented Programing (3160922) for the academic
year ___________________.
Place: _____________________
Date: _________________
Head of Department
Preface
Main motto of any laboratory/practical/field work is to enhance required skills as well as to create ability
amongst students to solve any real time problem by developing relevant competencies in Cognitive domain.
To fulfil these requirements, competency focused outcome-based curriculum is designed for engineering
degree programs where sufficient weightage is given to the practical work.
Each experiment in the laboratory manual is keenly designed to serve as a tool to develop and
enhance relevant competency required by various industries among every student. Each experiment is
mapped with Course Outcome which in turn will help satisfying each Course Outcome and to achieve
certain level of attainment. The step-by-step procedure is described to help students in setting-up and
configuring the experimental test bench for performance. Necessary tables for observations, program
outputs, and conclusion are to be kept in flow with required guidelines.
The laboratory manual also provides the guidelines for the subject faculty member to facilitate
student centric laboratory activities through each experiment by arranging and managing necessary
resources. The evaluation rubrics are well-defined and have been given a certain Weightage for fair
assessment.
The Object-Oriented Programing course deals with the realizing real world entities as objects in
the programming logic and corresponding attributes to be deal with. The approach is quite different than
conventional sequential top down C language. These concepts of object-oriented Programing approach is
used in making website, computer applications, mobile applications and many other softwares. The concepts
of class, objects, constructors, destructors, methods function overloading and inheritances of OOP helps in
virtualizing and realizing the complex real-world inside the computer and thus making problem solving easy
for computer. The OOP practical’s so designed will act as the stepping stone to the many in fact most of the
higher and advance Programing language.
Pre-Requisite
Softwares Required:
Creating a comprehensive C++ program necessitates the utilization of specific software tools to facilitate a
productive learning experience. In this context, two essential software components are Visual Studio Code
and MinGW32. Visual Studio Code serves as the integrated development environment (IDE) of choice,
offering a user-friendly interface and extensive features for code editing, debugging, and version control.
Meanwhile, MinGW32, which stands for Minimalist GNU 32-bit for Windows, provides the necessary
compiler and toolchain for C and C++ programming, ensuring that students can compile and run their code
on Windows systems. Together, these software solutions empower students to explore the intricacies of C
programming with a versatile and accessible environment, making the lab manual an effective resource for
honing their coding skills.
Faculty and students must be aware that some of syntax of programming may change depending upon
compilers and softwares used by them.
2. Know-how of programming basics like programing benefits, loops, algorithms, flowcharts, debugging
and programming syntax.
2. Teacher shall explain basic concepts/theory related to the programs the students before starting of
each practical
3. Teacher should Guide the students to solve programming errors on their own to help them memorize
the syntax.
4. Teacher should Discuss the logical insights of the programs and motivate the students to develop
similar logics or different logics for other such applications.
5. Teacher should Guide the students to find out the logical errors if any in the program.
6. Teacher should Guide the student to take different case studies/parameters/ possibilities for the same
program written and write the output in file pages.
7. Teacher is expected to share the skills and competencies to be developed in the students and ensure
that the respective skills and competencies are developed in the students after the completion of the
experimentation.
8. Teacher may provide additional knowledge and skills to the students even though not covered in the
manual but are expected from the students by concerned industry.
9. Give practical assignment and assess the performance of students based on task assigned to check
whether it is as per the instructions or not.
10. Teacher is expected to refer complete curriculum of the course and follow the guidelines for
implementation.
Vision
To be a leading institution ensuring Academic Excellence, Research, Nurturing Innovation and
Entrepreneurial Attitude to produce competent technocrats for service to Nation.
Mission
1. To be a student centric institute imbibing experiential, innovative and lifelong learning skills,
addressing societal problems.
2. To create a conducive ecosystem for Research, innovation & extension services.
3. To inculcate entrepreneurial attitude and values amongst Learners.
4. To Collaborate with Industries and other institutions to strengthen symbiotic relations.
5. To mentor aspiring Institutions to unleash their potential, towards nation building.
Core Values
Our core values are quality, equality, morality, environmental sustainability, energy saving and strong
commitment to the cause of technical education and services. We believe and put efforts towards:
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences,
and engineering sciences.
4. Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information
to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports
and design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.
COURSE OUTCOMES
Sr. No Outcomes Domain, Levels & Dimensions of Learning
Understand Object Oriented Programming Cognitive Domain
CO1
concepts and basic characteristics of C++ Conceptual Dimension, Understand Level
Cognitive Domain
CO2 Differentiate OOP & POP Conceptual Dimension (Analyse and Create
Level)
Cognitive Domain
Implement Functions and Function
CO3 Conceptual Dimension (Apply and Create
overloading concepts of OOP in Programing
Level)
Implement Data encapsulation, Inheritance, Cognitive Domain
CO4 Polymorphism, Access specifiers and Conceptual Dimension (Apply and Create
exceptions Level)
Psychomotor
Execute file management using streams in
CO5 Conceptual Dimension (Apply and Create
OOP Programing
Level)
INDEX
Pg. Marks/
Start Date End Date Sign
No Grade
1. Revisiting C Language
Programs:
1. Write simple programs that read numbers and text, process the input and display the
results.
#include <stdio.h>
#include <string.h>
int main() {
int num;
char text[100];
printf("Enter a number: ");
scanf("%d", &num);
while (getchar() != '\n');
printf("Enter some text: ");
fgets(text, sizeof(text), stdin);
printf("\nYou entered the number: %d\n", num);
printf("You entered the text: %s", text);
return 0;
}
2. Write a program to find the factors of any number. Also find the prime factors of that
number.
#include <stdio.h>
void findFactors(int n) {
printf("Factors of %d are: ", n);
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
printf("%d ", i);
}
}
printf("\n");
}
void findPrimeFactors(int n) {
printf("Prime factors of %d are: ", n);
for (int i = 2; i <= n; i++) {
while (n % i == 0 && isPrime(i)) {
printf("%d ", i);
n /= i;
}
}
printf("\n");
}
int main()
{
int number;
printf("Enter a number: ");
scanf("%d", &number);
findFactors(number);
findPrimeFactors(number);
return 0;
}
int main() {
char str[100];
printf("\n");
return 0;
}
4. Write a C program to demonstrate Bubbles sort of an array of 10 integers. Arrange
them in descending order
#include <stdio.h>
int main()
{
int arr[10];
printf("Enter 10 integers:\n");
for (int i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
bubbleSort(arr, 10);
return 0;
}
5. Define a structure book_shop. It should contain the name of the book, name of the
author, number of copies available, price of the book and a Book ID No. Create a list of 5
such books. Write a function to search for a book using the name of the book. Ask the
user for the number of copies he wants. Calculate the cost. If sufficient copies are not
available, display appropriate message. Write a function to update the database after
each purchase.
#include <stdio.h>
#include <string.h>
int main() {
struct book_shop books[5]; // Create a list of 5 books
char search_name[100];
int num_copies;
if (book_index != -1) {
printf("Enter the number of copies you want to purchase: ");
scanf("%d", &num_copies);
return 0;
}
6. Write a function to exchange the values of two variables. Use pass by reference method
to exchange the data.
#include <stdio.h>
int main() {
int num1, num2;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);
swap(&num1, &num2);
printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);
return 0;
}
Output on File Page:
Conclusion:
class Student {
public:
string name;
int age;
double gpa;
Student(string n, int a, double g) {
name = n;
age = a;
gpa = g;
}
void displayInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << " years" << endl;
cout << "GPA: " << gpa << endl;
}
};
int main() {
public:
FeetToInchesConverter(double f) {
feet = f;
}
double convertToInches() {
return feet * 12.0;
}
};
int main() {
double feet;
std::cout << "Enter the length in feet: ";
std::cin >> feet;
FeetToInchesConverter converter(feet);
double inches = converter.convertToInches();
std::cout << feet << " feet is equal to " << inches << " inches." <<
std::endl;
return 0;
}
3. Write a C++ program to demonstrate Scope resolution operator without using class
#include <iostream>
int globalVar = 10;
void globalFunction()
{
std::cout << "This is a global function." << std::endl;
}
int main()
{
int globalVar = 5;
std::cout << "Local variable 'globalVar': " << globalVar << std::endl;
std::cout << "Global variable 'globalVar': " << ::globalVar << std::endl;
globalFunction();
::globalFunction();
return 0;
}
Conclusion:
public:
Calculator(int n) {
num = n;
}
void square() {
int result = num * num;
displaySquare(result);
}
void displaySquare(int square) {
std::cout << "Square of " << num << " is: " << square << std::endl;
}
};
int main() {
int number;
class Employee {
private:
std::string name;
double salary;
void displaySalary() const {
std::cout << "Salary: $" << std::fixed << std::setprecision(2) <<
salary << std::endl;
}
public:
Employee(std::string n, double s)
{
name = n;
salary = s;
}
void displayInfo() const {
std::cout << "Name: " << name << std::endl;
displaySalary(); // Call the private member function to display salary
}
};
int main()
{
Employee emp("John Doe", 50000.75);
std::cout << "Employee Information:" << std::endl;
emp.displayInfo();
return 0;
}
public:
ArraySorter(int elements[], int n) {
size = n;
for (int i = 0; i < size; i++) {
arr[i] = elements[i];
}
}
void selectionSort() {
for (int i = 0; i < size - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < size; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
void printArray() {
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
};
int main()
{
int elements[] = {9, 3, 6, 1, 8, 2};
int size = sizeof(elements) / sizeof(elements[0]);
ArraySorter sorter(elements, size);
std::cout << "Original Array: ";
sorter.printArray();
sorter.selectionSort();
std::cout << "Array in Ascending Order: ";
sorter.printArray();
return 0;
}
int main()
{
double num;
std::cout << "Enter a number: ";
std::cin >> num;
double result = square(num);
std::cout << "The square of " << num << " is: " << result << std::endl;
return 0;
}
4. Write a C++ program to use of default arguments.
#include<iostream>
Conclusion:
class Sym
{
static int c;
public:
int getSym()
{ char a;
cout << endl<<"Enter any Charcter:";
cin >> a;
c++;
return a;
}
void printSym(int a)
{ for(int i=0;i<c;i++)
{
cout << a<<" ";
}
cout << endl;
}
};
int Sym :: c;
int main()
{
Sym a1,a2,a3;
int b1,b2,b3;
b1=a1.getSym();
a1.printSym(b1);
b2=a2.getSym();
a2.printSym(b2);
b3=a3.getSym();
a3.printSym(b3);
return 0;
}
2. Write a C++ program to demonstrate use of static data member functions.
#include<iostream>
#include<iomanip>
using namespace std;
class sta
{
char fname[10],lname[10];
char div;
static int getObjCount;
public:
void getData(int a)
{
cout <<"USER : "<< a << endl;
}
static int getCount()
{
getObjCount++;
return getObjCount;
}
void putData()
{
cout << "Enterd details : ";
cout<<setw(10)<<fname<<" "<<lname <<setw(5)<<div<<endl;
void totalObj(int c)
{
cout << endl<< "Total Entries : " <<c;
}
};
int main()
{
int c;
sta s1,s2,s3;
c =s1.getCount();
s1.getData(c);
c=s2.getCount();
s2.getData(c);
c=s3.getCount();
s3.getData(c);
s1.putData();
s2.putData();
s3.putData();
s3.totalObj(c);
return 0;
}
Conclusion:
class MyClass;
void display(const MyClass &obj);
class MyClass
{
private:
int data;
public:
MyClass(int value) : data(value) {}
friend void display(const MyClass &obj);
};
int main() {
MyClass obj(42);
display(obj);
return 0;
}
class MyClass;
class FriendClass
{
public:
static void display(const MyClass& obj);
};
class MyClass
{
private:
int data;
public:
MyClass(int value) : data(value) {}
friend class FriendClass;
};
int main()
{
MyClass obj(42);
FriendClass::display(obj);
return 0;
}
Conclusion:
class Rectangle
{
private:
double length;
double width;
public:
Rectangle()
{
length = 0.0;
width = 0.0;
}
Rectangle(double l, double w)
{
length = l;
width = w;
}
void calculateArea()
{
double area = length * width;
std::cout << "Area of the rectangle: " << area << std::endl;
}
};
int main()
{
return 0;
}
2. Write a C++ program to demonstrate use of copy constructors.
#include <iostream>
class Student
{
private:
std::string name;
int age;
public:
Student(std::string n, int a)
{
name = n;
age = a;
}
int main()
{
Student student1("Alice", 20);
return 0;
}
~MyClass() {
std::cout << "Destructor called" << std::endl;
}
};
int main()
{
MyClass obj1;
MyClass obj2;
return 0;
}
Conclusion:
class Complex {
private:
double real;
double imag;
public:
Complex(double r, double i) : real(r), imag(i) {}
friend Complex operator+(const Complex& c1, const Complex& c2);
void display() const
{
std::cout << real << " + " << imag << "i" << std::endl;
}
};
int main()
{
Complex num1(2.5, 3.0);
Complex num2(1.5, 2.5);
return 0;
}
2. Write a C++ program to demonstrate use single inheritance by public derivation.
#include <iostream>
// Base class
class Shape
{
public:
void display() {
std::cout << "This is a shape." << std::endl;
}
};
int main()
{
Circle circle;
circle.display();
circle.displayCircle();
return 0;
}
// Base class
class Vehicle
{
public:
void start() {
std::cout << "Vehicle started." << std::endl;
}
};
int main()
{
Car myCar;
return 0;
}
Conclusion:
// Base class
class Animal
{
public:
void speak() {
std::cout << "Animal speaks." << std::endl;
}
};
int main()
{
Dog myDog;
myDog.speak(); // Access the base class function
myDog.giveBirth(); // Access the first derived class function
myDog.bark(); // Access the second derived class function
return 0;
}
// Base class 1
class Parent1 {
public:
void display1() {
std::cout << "This is Parent1." << std::endl;
}
};
// Base class 2
class Parent2 {
public:
void display2() {
std::cout << "This is Parent2." << std::endl;
}
};
int main() {
Child myChild;
return 0;
}
// Base class
class Animal {
public:
void speak() {
std::cout << "Animal speaks." << std::endl;
}
};
int main() {
Dog myDog;
Cat myCat;
return 0;
}
// Base class
class Animal {
public:
void speak() {
std::cout << "Animal speaks." << std::endl;
}
};
int main() {
Bat myBat;
return 0;
}
Conclusion:
public:
};
int main() {
try {
Conclusion:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ofstream outputFile("output.txt");
if (!outputFile) {
std::cerr << "Failed to open output.txt" << std::endl;
return 1;
}
std::streambuf* originalOutputBuffer = std::cout.rdbuf();
std::cout.rdbuf(outputFile.rdbuf());
std::cout << "This text will be written to output.txt." << std::endl;
std::cout.rdbuf(originalOutputBuffer);
outputFile.close();
std::ifstream inputFile("input.txt");
if (!inputFile) {
std::cerr << "Failed to open input.txt" << std::endl;
return 1;
}
std::streambuf* originalInputBuffer = std::cin.rdbuf();
std::cin.rdbuf(inputFile.rdbuf());
std::string input;
std::cin >> input;
std::cin.rdbuf(originalInputBuffer);
inputFile.close();
std::cout << "Input from input.txt: " << input << std::endl;
return 0;
}
2. Write a c++ program to Create a custom stream class by overloading operators for
specialized I/O.
#include <iostream>
#include <string>
class CustomStream
{
public:
CustomStream& operator<<(const std::string& data)
{
// Customize the output behavior here
std::cout << "Custom Output: " << data << std::endl;
return *this;
}
CustomStream& operator>>(std::string& data) {
// Customize the input behavior here
std::cout << "Enter custom input: ";
std::cin >> data;
return *this;
}
};
int main()
{
CustomStream customIO;
std::string inputData;
customIO >> inputData; // Customized input
std::string outputData = "This is custom output.";
customIO << outputData; // Customized output
return 0;
}
3. Write a c++ program to explain the use of seekg and tellg for positioning within a
file.
##include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ofstream outputFile("positioning_example.txt");
if (!outputFile)
{
std::cerr << "Failed to open positioning_example.txt" << std::endl;
return 1;
}
outputFile << "This is line 1." << std::endl;
outputFile << "This is line 2." << std::endl;
outputFile << "This is line 3." << std::endl;
outputFile.close();
std::ifstream inputFile("positioning_example.txt");
if (!inputFile) {
std::cerr << "Failed to open positioning_example.txt for reading" << std::endl;
return 1;
}
std::streampos initialPosition = inputFile.tellg();
std::cout << "Current position in the file: " << initialPosition << std::endl;
inputFile.seekg(initialPosition + std::streamoff(18));
std::string line;
std::getline(inputFile, line);
std::cout << "Contents from the new position: " << line << std::endl;
std::streampos newPosition = inputFile.tellg();
std::cout << "New position in the file: " << newPosition << std::endl;
inputFile.close();
return 0;
}
4. Write a c++ program to demonstrate the use of buffering and manual flushing with
flush().
#include <iostream>
#include <chrono>
#include <thread>
int main() {
std::cout << "This text is buffered and will be printed all at once." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "This text will be printed immediately because of manual flushing." <<
std::flush;
std::this_thread:: sleep_for(std::chrono::seconds(2));
std::cout << "This text is buffered again." << std::endl;
return 0;
}
Conclusion:
Animal(int n) : legs(n) {
std::cout << "Animal constructor called with " << legs << " legs." << std::endl;
}
};
int main()
{
Bat bat(2);
return 0;
}
void displayInfo() {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
};
int main()
{
Student student1("Alice", 20);
Student student2("Bob", 22);
Student* ptr1 = &student1;
Student* ptr2 = &student2;
ptr1->displayInfo();
ptr2->displayInfo();
return 0;
}
3. Write a C++ program to demonstrate use of this pointer.
#include <iostream>
class MyClass {
private:
int value;
public:
MyClass(int val) : value(val) {}
void printValue()
{
std::cout << "Value: " << this->value << std::endl;
}
bool isSameValue(const MyClass& other)
{
return this->value == other.value;
}
};
int main() {
MyClass obj1(42);
MyClass obj2(37);
obj1.printValue();
obj2.printValue();
if (obj1.isSameValue(obj2)) {
std::cout << "The values are the same." << std::endl;
} else {
std::cout << "The values are different." << std::endl;
}
return 0;
}
Circle(double r) : radius(r) {}
void displayArea() override {
double area = 3.14159265 * radius * radius;
std::cout << "Area of the circle: " << area << std::endl;
}
};
class Rectangle : public Shape {
public:
double length;
double width;
int main() {
Shape* shape1 = new Circle(5.0);
Shape* shape2 = new Rectangle(4.0, 3.0);
shape1->displayArea();
shape2->displayArea();
delete shape1;
delete shape2;
return 0;
}
Object Oriented Programing (3160922)
Branch Coordinator
Dr. J. R. Iyer Professor,
Electrical Engineering
L.D. College of Engineering Ahmedabad
Committee Chairman
Dr. N. M. Bhatt
Professor of Mechanical Engineering
L. E. College, Morbi