0% found this document useful (0 votes)
30 views52 pages

OOP - Lab Manual

This document is a laboratory manual for the Object Oriented Programming course for B.E. Semester 6 Electrical Engineering students. It outlines the objectives, prerequisites, guidelines for faculty and students, safety instructions, and the vision and mission of the educational institution. The manual includes practical exercises designed to enhance programming skills and competencies relevant to the industry.

Uploaded by

anvitashah33
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)
30 views52 pages

OOP - Lab Manual

This document is a laboratory manual for the Object Oriented Programming course for B.E. Semester 6 Electrical Engineering students. It outlines the objectives, prerequisites, guidelines for faculty and students, safety instructions, and the vision and mission of the educational institution. The manual includes practical exercises designed to enhance programming skills and competencies relevant to the industry.

Uploaded by

anvitashah33
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/ 52

A Laboratory Manual for

Object Oriented Programing


(3160922)
B.E. Semester 6
(Electrical Engineering)

Directorate of Technical Education, Gandhinagar,


Gujarat
L.D. College of Engineering
Certificate

This is to certify that Mr. / Ms. _____________________________________

Enrollment No. __________________________ of B.E. Semester 6th Electrical

Engineering of this Institute (GTU Code:028 ) has satisfactorily completed the

Practical for the subject Object Oriented Programing (3160922) for the academic

year ___________________.

Place: _____________________

Date: _________________

Name and Sign of Faculty member:

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.

Relevant Technical Skills expected from Students:


The following industry relevant competencies are expected to be developed in the student by undertaking the
practical work of this laboratory.
1. Knowledge for installation and using various softwares like Turbo C and C++, Visual Studio Code,
installing various compilers for running the C++ code.

2. Know-how of programming basics like programing benefits, loops, algorithms, flowcharts, debugging
and programming syntax.

3. Logical insights involving cognitive domains.

Guidelines for Faculty members:


1. Teacher should provide the guideline for demonstration the program to the students with all features
of software usage.

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.

Instructions for Students:


1. Students are expected to carefully listen to all the theory classes delivered by the faculty members
and understand the COs, content of the course, teaching and examination scheme, skill set to be
developed etc.
2. Students shall execute the programs individually and understand various concepts for which it is
designed.
3. Students should execute the programs for various cases and test the programs for any logical errors
and write down the final outputs in file pages.
4. Students should organize the work in the group and make record of all observations.
5. Student shall attempt to develop related hand-on skills and build confidence.
6. Student shall develop the habits of evolving more ideas, innovations, skills etc. apart from those
included in scope of manual.
7. Student shall refer technical magazines and data books.
8. Student should develop a habit of submitting the experimentation work as per the schedule and He /
She should be well prepared for the same.

Common Safety Instructions:


1. Students are expected to carefully handle hardware, software and computers.
2. Equipment’s in the laboratory should not be removed, modified, relocated or disassembled
without prior permission of concerned Subject Faculty Member, Lab-In charge and Head of the
Department.
3. Shut down and switch off the computers properly before leaving the computer lab.
4. Switch off all the lights and fans as well as shut all the windows of the computer lab.
Vision of DTE

1. To provide globally competitive technical education;


2. Remove geographical imbalances and inconsistencies;
3. Develop student friendly resources with a special focus on girls’ education and support to weaker
sections;
4. Develop programs relevant to industry and create a vibrant pool of technical professionals.

Vision & Mission of Institute

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:

● Equitable and harmonious growth of students, staff, society, industry.


● Quality services and education to train students enlightened with vision to be committed citizen with
strong civic sense and high moral standards having concern for local and global values.

Vision & Mission of Department

Electrical Department Vision Statement


To Foster Learning Environment for Electrical Engineering Education having High
Technical Skills, Ethical Values and Overall Global Competence.

Electrical Department Mission Statement


To provide high quality graduate program in Electrical Engineering to prepare students for
● Better Employability, Start-ups and Entrepreneurship.
● A professional career with essential technical and managerial skills.
● Collaboration with industries through research and innovation.
● Other avenues for higher education.
● Adapting to change in technology and apply the same for the benefits of society at
large.
● .

Program Outcomes as defined by NBA (PO)

Engineering Graduates will be able to:

1. Engineering knowledge: Apply the knowledge of mathematics, science,


engineering fundamentals, and an engineering specialization to the solution of complex
engineering problems.

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.

3. Design/development of solutions: Design solutions for complex engineering problems


and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.

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.

Program Educational Objectives (PEOs)

Program Specific Outcomes (PSO)

Course Outcome (COs):

After learning the course, the students should be able to:


L D COLLEGE OF ENGINEERING, AHMEDABAD
Electrical Engineering Department
Subject: Object Oriented Programing (OOP:3160922)
Course Outcome Mapping
Sr. CO- Planned
Title of Practical Platform
No Mapping Week
Revisiting C Language Software Visual
1. CO 1, CO 2 Week 1 & Week 2
Studio/ Code Block
Implement Class & Object Based Software Visual
2. CO 1, CO 2 Week 3
Programing in C++ Studio/ Code Block
C++ Programing using concepts of Software Visual CO2, CO 3 Week 4
3. Member Functions, Default Studio/ Code Block
Arguments, Inline functions.
Investigating the Utilization of Software Visual CO 1, CO 3 Week 5
4.
Static Data Members Studio/ Code Block
Exploring Friend Functions in Software Visual CO1, CO 3 Week 6
5.
C++ Studio/ Code Block
Implementing Constructors and Software Visual CO1, CO 3 Week 7
6.
Destructors in C++ Studio/ Code Block
Exploring Basic Concepts of Software Visual CO1, CO 4 Week 8
7. Inheritance in C++ Studio/ Code Block
Implementing Advance Software Visual CO1, CO 4 Week 9
8.
Concepts of Inheritance in C++ Studio/ Code Block
Implementing Exception Software Visual CO1, CO 4 Week 10
9.
Handling Studio/ Code Block
Implementing Streams & File Software Visual CO1, CO 5 Week 11
10.
management in C++ Studio/ Code Block
Exploring Virtual Base Class, Software Visual CO1, CO 5 Week 12
11. Virtual Functions and Pointers of Studio/ Code Block
C++

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

Class & Object Based


2.
C++ Programs

Exploring Basic C++


3.
Programming Concepts
Investigating the
4. Utilization of Static
Data Members
Exploring Friend
Functions and Call by
5.
Reference Parameter
Passing in C++
Exploring Constructors
6.
and Destructors in C++
Exploring Basic
7. Concepts of
Inheritance in C++
Exploring Advance
8. Concepts of
Inheritance in C++
Implementing
9.
Exception Handling
Exploring Streams &
10. File management in
C++
Exploring the 'this'
Pointer and Utilizing
11.
Virtual Functions in
C++

RUBRICS Unsatisfactory Developing Satisfactory Exemplary


Laboratory (3 to 4 mark) (5 to 6 mark) (7 to 8 mark) (9 to 10 mark)
Assessment. Grade D Grade C Grade B Grade A

Note: Faculty can implement their own marking/grading scheme rubrics


as per the policies adopted by their institutes for
Experiment No: 1 Revisiting C Language
Aim: To revisit and reacquaint ourselves with the essential concepts, principles, and
programming techniques of the 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");
}

int isPrime(int num) {


if (num <= 1) {
return 0;
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0;
}
}
return 1;
}

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;
}

3. Write a program to input a string and display it in reverse order.


#include <stdio.h>
#include <string.h>

int main() {
char str[100];

printf("Enter a string: ");


fgets(str, sizeof(str), stdin);

int length = strlen(str);


printf("Reversed string: ");
for (int i = length - 1; i >= 0; i--) {
if (str[i] != '\n') { // Exclude the newline character from the output
printf("%c", str[i]);
}
}

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>

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
// Swap arr[j] and arr[j + 1] if they are in the wrong order
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

int main()
{
int arr[10];

printf("Enter 10 integers:\n");
for (int i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}

bubbleSort(arr, 10);

printf("Sorted array in descending order:\n");


for (int i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}

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>

// Define the book_shop structure


struct book_shop {
char name[100];
char author[100];
int copies_available;
float price;
int book_id;
};

// Function to search for a book by name


int searchBook(struct book_shop books[], int num_books, char search_name[]) {
for (int i = 0; i < num_books; i++) {
if (strcmp(books[i].name, search_name) == 0) {
return i;
}
}
return -1; // Book not found
}

// Function to update the database after a purchase


void updateDatabase(struct book_shop books[], int index, int num_copies) {
books[index].copies_available -= num_copies;
}

int main() {
struct book_shop books[5]; // Create a list of 5 books

// Initialize the book data


books[0] = (struct book_shop){"Book 1", "Author 1", 10, 15.0, 1};
books[1] = (struct book_shop){"Book 2", "Author 2", 5, 20.0, 2};
books[2] = (struct book_shop){"Book 3", "Author 3", 8, 18.0, 3};
books[3] = (struct book_shop){"Book 4", "Author 4", 12, 12.0, 4};
books[4] = (struct book_shop){"Book 5", "Author 5", 7, 25.0, 5};

char search_name[100];
int num_copies;

printf("Enter the name of the book you want to search: ");


fgets(search_name, sizeof(search_name), stdin);
search_name[strcspn(search_name, "\n")] = '\0'; // Remove the newline
character

int book_index = searchBook(books, 5, search_name);

if (book_index != -1) {
printf("Enter the number of copies you want to purchase: ");
scanf("%d", &num_copies);

if (num_copies <= books[book_index].copies_available) {


float total_cost = num_copies * books[book_index].price;
printf("Total cost: $%.2f\n", total_cost);
// Update the database
updateDatabase(books, book_index, num_copies);
} else {
printf("Sufficient copies are not available for your
purchase.\n");
}
} else {
printf("Book not found in the database.\n");
}

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>

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

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:

RUBRICS Unsatisfactory Developing Satisfactory Exemplary


Laboratory (3 to 4 mark) (5 to 6 mark) (7 to 8 mark) (9 to 10 mark)
Assessment. Grade D Grade C Grade B Grade A
Experiment No: 2 Implement Class & Object Based Programing in C++

1. Write a C++ Program To demonstrate use of class


#include <iostream>
#include <string>
using namespace std;

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() {

Student student1("Alice", 20, 3.7);


cout << "Student 1 Information:" << endl;
student1.displayInfo();
Student student2("Bob", 22, 3.9);
cout << "\nStudent 2 Information:" << endl;
student2.displayInfo();
return 0;
}

2. Write a C++ program to convert feet into inches using class.


#include <iostream>
class FeetToInchesConverter {
private:
double feet;

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;
}

4. Write a C++ program to demonstrate Scope resolution operator using class.


#include <iostream>
int globalVar = 10;
class Demo {
public:
static int globalVar;
static void displayGlobalVar()
{
std::cout << "Global variable from the class: " << ::globalVar <<
std::endl;
}
};
int Demo::globalVar = 5;
int main() {
std::cout << "Global variable from the class: " << Demo::globalVar <<
std::endl;
Demo::displayGlobalVar();
return 0;
}

Output on File Page:

Conclusion:

RUBRICS Unsatisfactory Developing Satisfactory Exemplary


Laboratory (3 to 4 mark) (5 to 6 mark) (7 to 8 mark) (9 to 10 mark)
Assessment. Grade D Grade C Grade B Grade A
Experiment No: 3 C++ Programing using concepts of Member Functions,
Default Arguments, Inline functions.

1. Write a C++ program to demonstrate use of nesting of member function.


#include <iostream>
class Calculator {
private:
int num;

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;

std::cout << "Enter a number: ";


std::cin >> number;
Calculator calc(number);
calc.square();
return 0;
}

2. Write a C++ program to use of manipulators and private member function.


#include <iostream>
#include <iomanip>

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;
}

3. Write a C++ program to print array in ascending order.


#include <iostream>
class ArraySorter
{
private:
int arr[100];
int size;

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;
}

3. Write a C++ program to demonstrate inline function.


#include <iostream>
inline double square(double x)
{
return x * x;
}

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>

using namespace std;

float baseArea(float r,float p=3.14)// prototype with default argument


{
return ((p*r*r));//returning area
}
float coneLSurArea(float r,float l=10,float p=3.14 )
{
return (p*l*r);
}
int main()
{
float a;
cout << "Enter radius of base: ";
cin >> a;
cout << "Area of Base: "<< baseArea(a)<< endl;
cout << "Lateral Surface area of Cone[if l=10] : "<< coneLSurArea(a) <<
endl;
cout << "Lateral Surface area of Cone[if l=15] : "<< coneLSurArea(a,15)<<
endl;//overwrite default arguments with actual arguments
return 0;
}

5. Write a C++ program to compute volume using function overloading.


#include <iostream>
#include <cmath>

double calculateVolume(double sideLength)


{
return std::pow(sideLength, 3);
}

double calculateVolume(double radius, double height)


{
return M_PI * std::pow(radius, 2) * height;
}

double calculateVolume(double radius)


{
return (4.0 / 3.0) * M_PI * std::pow(radius, 3);
}
int main()
{
double side, radius, height;
std::cout << "Enter the side length of a cube: ";
std::cin >> side;
std::cout << "Volume of the cube: " << calculateVolume(side) << std::endl;
std::cout << "Enter the radius and height of a cylinder: ";
std::cin >> radius >> height;
std::cout << "Volume of the cylinder: " << calculateVolume(radius, height)
<< std::endl;
std::cout << "Enter the radius of a sphere: ";
std::cin >> radius;
std::cout << "Volume of the sphere: " << calculateVolume(radius) <<
std::endl;
return 0;
}

Output on File Page:

Conclusion:

RUBRICS Unsatisfactory Developing Satisfactory Exemplary


Laboratory (3 to 4 mark) (5 to 6 mark) (7 to 8 mark) (9 to 10 mark)
Assessment. Grade D Grade C Grade B Grade A
Experiment No: 4 Investigating the Utilization of Static Data Members
1. Write a C++ program to demonstrate use of static data members.
#include<iostream>

using namespace std;

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;

cout << "Enter Your First Name : ";


cin >> fname;
cout << "Enter Your Last Name : ";
cin >> lname;
cout<<"Enter your Division: ";
cin >> div;

}
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 sta :: getObjCount;

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;
}

3. Write a C++ program to demonstrate use of array of objects.


#include<iostream>
#include<iomanip>
using namespace std;
class arobj
{
char fname[10],lname[10];
char div;
public:
void getData(int a)
{
cout <<"USER : "<< a << endl;
cout << "Enter Your First Name : ";
cin >> fname;
cout << "Enter Your Last Name : ";
cin >> lname;
cout<<"Enter your Division: ";
cin >> div;
}
void putData(int b)
{
cout<<b<<setw(15)<<fname<<" "<<lname <<setw(5)<<div<<endl;
}
};
int main()
{
int c;
cout <<"Enter no. of Entries :";
cin >> c;
arobj s[c];
for(int i=0;i<c;i++)
{
s[i].getData(i);
}
cout << "Enterd details : "<<endl;
cout<<setw(15)<<"fname"<<" lname "<<setw(5)<<"div"<<endl;
for(int i=0;i<c;i++)
{
s[i].putData(i);
}
return 0;
}

4. Write a C++ program to pass objects as function arguments.


#include<iostream>
using namespace std;
class weight
{
int kilogram;
int gram;
public:
void getdata ()
{
cout<<endl<<"Kilograms: ";
cin>>kilogram;
cout<<"Grams: ";
cin>>gram;
}
void putdata ()
{
cout<<kilogram<<" Kgs. and "<<gram<<" grms."<<endl;
}
void sumWeight (weight w1,weight w2)
{
gram = w1.gram + w2.gram;
kilogram=gram/1000;
gram=gram%1000;
kilogram+=w1.kilogram+w2.kilogram;
}
};
int main ()
{
weight w1,w2 ,w3;
cout<<"Enter weight in kilograms and grams"<<endl;
cout<<endl<<"Enter weight 1" ;
w1.getdata();
cout<<endl<<"Enter weight 2" ;
w2.getdata();
w3.sumWeight(w1,w2);
cout<<endl<<"Weight 1 = ";
w1.putdata();
cout<<"Weight 2 = ";
w2.putdata();
cout<<endl<<"Total Weight = ";
w3.putdata();
return 0;
}

Output on File Page:

Conclusion:

RUBRICS Unsatisfactory Developing Satisfactory Exemplary


Laboratory (3 to 4 mark) (5 to 6 mark) (7 to 8 mark) (9 to 10 mark)
Assessment. Grade D Grade C Grade B Grade A
Experiment No: 5 Exploring Friend Functions in C++

1. Write a C++ program to demonstrate use of friend function.


#include <iostream>

class MyClass;
void display(const MyClass &obj);
class MyClass
{
private:
int data;

public:
MyClass(int value) : data(value) {}
friend void display(const MyClass &obj);
};

void display(const MyClass &obj)


{
std::cout << "Data from MyClass: " << obj.data << std::endl;
}

int main() {
MyClass obj(42);
display(obj);
return 0;
}

2. Write a C++ program to use friend function with call by reference.


#include <iostream>

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;
};

void FriendClass::display(const MyClass& obj)


{
std::cout << "Data from MyClass: " << obj.data << std::endl;
}

int main()
{
MyClass obj(42);
FriendClass::display(obj);

return 0;
}

3. Write a C++ program to use function with call by reference.


#include<iostream>

using namespace std;

void ex(int &,int &);


int main()
{
int a,b;
cout << "Enter two numbers : ";
cin >> a >> b;
cout << endl<<"Before exchange : ";
cout << a << " "<< b << endl;
ex(a,b);
cout <<"After exchange : ";
cout << a << " " << b << endl;
return 0;
}

void ex(int &m,int &n)


{
int t;
t=n;
n=m;
m=t;
cout << endl ;
}
Output on File Page:

Conclusion:

RUBRICS Unsatisfactory Developing Satisfactory Exemplary


Laboratory (3 to 4 mark) (5 to 6 mark) (7 to 8 mark) (9 to 10 mark)
Assessment. Grade D Grade C Grade B Grade A
Experiment No: 6 Implementing Constructors and Destructors in C++
1. Write a C++ program to demonstrate use of constructors.
#include <iostream>

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()
{

Rectangle defaultRect; // Default constructor


Rectangle customRect(5.0, 3.0); // Parameterized constructor

std::cout << "For the default rectangle:" << std::endl;


defaultRect.calculateArea();

std::cout << "For the custom rectangle:" << std::endl;


customRect.calculateArea();

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;
}

Student(const Student &other) {


name = other.name;
age = other.age;
}

// Member function to display student information


void displayInfo() {
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << " years" << std::endl;
}
};

int main()
{
Student student1("Alice", 20);

Student student2 = student1;

std::cout << "Student 1 Information:" << std::endl;


student1.displayInfo();

std::cout << "\nStudent 2 Information (Copy of Student 1):" << std::endl;


student2.displayInfo();

return 0;
}

3. Write a C++ program to implement the destructor.


#include <iostream>
class MyClass
{
public:
MyClass() {
std::cout << "Constructor called" << std::endl;
}

~MyClass() {
std::cout << "Destructor called" << std::endl;
}
};

int main()
{
MyClass obj1;
MyClass obj2;

return 0;
}

Output on File Page:

Conclusion:

RUBRICS Unsatisfactory Developing Satisfactory Exemplary


Laboratory (3 to 4 mark) (5 to 6 mark) (7 to 8 mark) (9 to 10 mark)
Assessment. Grade D Grade C Grade B Grade A
Experiment No: 7 Exploring Basic Concepts of Inheritance in C++
1. Write a C++ program to overload binary operators using friend function.
#include <iostream>

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;
}
};

// Friend function to overload the addition operator


Complex operator+(const Complex& c1, const Complex& c2)
{
double realSum = c1.real + c2.real;
double imagSum = c1.imag + c2.imag;
return Complex(realSum, imagSum);
}

int main()
{
Complex num1(2.5, 3.0);
Complex num2(1.5, 2.5);

Complex sum = num1 + num2;

std::cout << "Sum of complex numbers:" << std::endl;


num1.display();
std::cout << "+ ";
num2.display();
std::cout << "= ";
sum.display();

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;
}
};

class Circle : public Shape


{
public:
void displayCircle() {
std::cout << "This is a circle." << std::endl;
}
};

int main()
{
Circle circle;

circle.display();

circle.displayCircle();

return 0;
}

3. Write a C++ program to demonstrate use single inheritance by private derivation.


#include <iostream>

// Base class
class Vehicle
{
public:
void start() {
std::cout << "Vehicle started." << std::endl;
}
};

class Car : private Vehicle {


public:
void startCar()
{
start(); // Access the base class member using the derived class
std::cout << "Car started." << std::endl;
}
};

int main()
{
Car myCar;

// Access the derived class function


myCar.startCar();

return 0;
}

Output on File Page:

Conclusion:

RUBRICS Unsatisfactory Developing Satisfactory Exemplary


Laboratory (3 to 4 mark) (5 to 6 mark) (7 to 8 mark) (9 to 10 mark)
Assessment. Grade D Grade C Grade B Grade A
Experiment No: 8 Implementing Advance Concepts of Inheritance in C++
1. Write a C++ program to demonstrate multilevel inheritance.
#include <iostream>

// Base class
class Animal
{
public:
void speak() {
std::cout << "Animal speaks." << std::endl;
}
};

class Mammal : public Animal


{
public:
void giveBirth()
{
std::cout << "Mammal gives birth." << std::endl;
}
};

class Dog : public Mammal


{
public:
void bark() {
std::cout << "Dog barks." << 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;
}

2. Write a C++ program to demonstrate multiple inheritance.


#include <iostream>

// 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;
}
};

class Child : public Parent1, public Parent2 {


public:
void displayChild() {
std::cout << "This is the Child." << std::endl;
}
};

int main() {
Child myChild;

// Access the functions of all three classes


myChild.display1(); // Access the function of Parent1
myChild.display2(); // Access the function of Parent2
myChild.displayChild(); // Access the function of Child

return 0;
}

3. Write a C++ program to demonstrate hierarchical inheritance.


#include <iostream>

// Base class
class Animal {
public:
void speak() {
std::cout << "Animal speaks." << std::endl;
}
};

// First derived class


class Dog : public Animal {
public:
void bark() {
std::cout << "Dog barks." << std::endl;
}
};

// Second derived class


class Cat : public Animal {
public:
void meow() {
std::cout << "Cat meows." << std::endl;
}
};

int main() {
Dog myDog;
Cat myCat;

myDog.speak(); // Access the function of Animal


myDog.bark(); // Access the function of Dog

myCat.speak(); // Access the function of Animal


myCat.meow(); // Access the function of Cat

return 0;
}

4. Write a C++ program to demonstrate hybrid inheritance.


#include <iostream>

// Base class
class Animal {
public:
void speak() {
std::cout << "Animal speaks." << std::endl;
}
};

// First derived class using virtual inheritance


class Mammal : virtual public Animal {
public:
void giveBirth() {
std::cout << "Mammal gives birth." << std::endl;
}
};

// Second derived class using virtual inheritance


class Bird : virtual public Animal {
public:
void layEggs() {
std::cout << "Bird lays eggs." << std::endl;
}
};

// Third derived class


class Bat : public Mammal, public Bird {
public:
void fly() {
std::cout << "Bat flies." << std::endl;
}
};

int main() {
Bat myBat;

// Access the functions of all classes through the Bat object


myBat.speak(); // Access the function of Animal
myBat.giveBirth(); // Access the function of Mammal
myBat.layEggs(); // Access the function of Bird
myBat.fly(); // Access the function of Bat

return 0;
}

Output on File Page:

Conclusion:

RUBRICS Unsatisfactory Developing Satisfactory Exemplary


Laboratory (3 to 4 mark) (5 to 6 mark) (7 to 8 mark) (9 to 10 mark)
Assessment. Grade D Grade C Grade B Grade A
Experiment No: 9 Implementing Exception Handling in C++
1. Write a C++ program to demonstrate Exception Handling.
#include <iostream>

class MyException : public std::exception {

public:

const char* what() const noexcept override {

return "Custom Exception: Something went wrong!";

};

int main() {

try {

int numerator, denominator;


std::cout << "Enter the numerator: ";
std::cin >> numerator;
std::cout << "Enter the denominator: ";
std::cin >> denominator;
if (denominator == 0)
{
throw MyException();
}
int result = numerator / denominator;
std::cout << "Result: " << result << std::endl;
} catch (const MyException& e)
{
std::cerr << e.what() << std::endl;
} catch (const std::exception& e)
{
std::cerr << "Standard Exception: " << e.what() << std::endl;
}
return 0;
}
Output on File Page:

Conclusion:

RUBRICS Unsatisfactory Developing Satisfactory Exemplary


Laboratory (3 to 4 mark) (5 to 6 mark) (7 to 8 mark) (9 to 10 mark)
Assessment. Grade D Grade C Grade B Grade A
Experiment No: 10 Implementing Streams & File management in C++
1. Write a c++ program to redirect standard input and output streams to files.

#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;
}

Output on File Page:

Conclusion:

RUBRICS Unsatisfactory Developing Satisfactory Exemplary


Laboratory (3 to 4 mark) (5 to 6 mark) (7 to 8 mark) (9 to 10 mark)
Assessment. Grade D Grade C Grade B Grade A
Experiment No: 11 Exploring Virtual Base Class, Virtual Functions and
Pointers of C++.
1. Write a C++ program to implement concept of virtual base class.
#include <iostream>

// Virtual base class


class Animal {
public:
int legs;

Animal(int n) : legs(n) {
std::cout << "Animal constructor called with " << legs << " legs." << std::endl;
}
};

class Mammal : virtual public Animal {


public:
Mammal(int n) : Animal(n) {
std::cout << "Mammal constructor called." << std::endl;
}
};

class Bird : virtual public Animal {


public:
Bird(int n) : Animal(n) {
std::cout << "Bird constructor called." << std::endl;
}
};

class Bat : public Mammal, public Bird {


public:
Bat(int n) : Animal(n), Mammal(n), Bird(n) {
std::cout << "Bat constructor called." << std::endl;
}
};

int main()
{
Bat bat(2);
return 0;
}

2. Write a C++ program to demonstrate use of pointer to objects.


#include <iostream>
class Student {
public:
std::string name;
int age;
Student (const std::string& n, int a) : name(n), age(a) {}

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;
}

4. Write a C++ program to demonstrate use of virtual functions.


#include <iostream>
class Shape {
public:
virtual void displayArea()
{
std::cout << "Area of the shape is unknown." << std::endl;
}
};

class Circle : public Shape


{
public:
double radius;

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;

Rectangle(double l, double w) : length(l), width(w) {}


void displayArea() override {
double area = length * width;
std::cout << "Area of the rectangle: " << area << std::endl;
}
};

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)

Lab manual prepared by:


Asst. Prof. Sajid M. Patel & Asst. Prof. Fedrik A. Macwan
Electrical Engineering Department
L. D. College of Engineering
Ahmedabad

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

You might also like