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

Oop Practical Program ?

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Oop Practical Program ?

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

1) Write a C++ program to evaluate the following expressions:

X=(-b-(b2-4ac))/2a
#include <iostream>
#include <math.h>

using namespace std;


int main()
{
float a , b , c , x ;
cout << "Enter value for a ,b ,c :" ;
cin >> a >> b >> c ;
x = (( -b ) - ( (b * b) - ( 4 * a * c ))) / ( 2 * a );
cout << "Result : " << x << endl;
return 0;
}

2) Write a C++ Program which shows the use of function outside


the class using scope resolution operator.

#include <iostream>
using namespace std;

class MyClass {
public:
void display(); // Declaration of member function
};

// Definition of member function outside the class using scope


resolution operator
void MyClass::display() {
cout << "Hello, this is a function outside the class!" << endl;
}

int main() {
MyClass obj;
obj.display(); // Calling the function
return 0;
}

3) Calculate average of two numbers using explicit type casting.

#include <iostream>
using namespace std;

int main() {
int num1, num2;
float average;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
// Calculate the average using explicit type casting
average = (float)(num1 + num2) / 2;
cout << "The average is: " << average << endl;
return 0;
}
4) Define a class Room with data members length, breadth and
height. Member function calculate_area () and
calculate_volume(). Calculate the area and volume of room.
Define the member function inside the class.

#include <iostream>
using namespace std;

class Room {
public:
float length, breadth, height;

// Member function to calculate area


float calculate_area() {
return length * breadth;
}

// Member function to calculate volume


float calculate_volume() {
return length * breadth * height;
}
};

int main() {
Room room;
// Take user input for length, breadth, and height
cout << "Enter length, breadth, and height of the room: ";
cin >> room.length >> room.breadth >> room.height;

// Calculate and display area and volume


cout << "Area of the room: " << room.calculate_area() << endl;
cout << "Volume of the room: " << room.calculate_volume() <<
endl;

return 0;
}

5) Write a program to find area of circle such that the class circle
must have three functions namely: a)read() to accept the radius
from user. b)compute() for calculating the area c)display() for
displaying the result.(Use Scope resolution operator)

#include <iostream>
using namespace std;

class Circle {
private:
float radius;
float area;
public:
void read();
void compute();
void display();
};

void Circle::read() {
cout << "Enter the radius of the circle: ";
cin >> radius;
}

void Circle::compute() {
area = 3.14159 * radius * radius;
}

void Circle::display() {
cout << "The area of the circle with radius " << radius << " is: " <<
area << endl;
}

int main() {
Circle c;
c.read();
c.compute();
c.display();
return 0;
}
6) Write a C++ program to create a class "Number" having data
members n1 and n2 and perform mathematical operations like
addition, subtraction, multiplication and division on two numbers
using inline functions.

#include <iostream>
using namespace std;

class Number
{
private:
float n1, n2;

public:
// Inline function to set the values of n1 and n2
void setValues()
{
cout << "Enter two numbers: ";
cin >> n1 >> n2;
}

// Inline function for addition


inline float add()
{
return n1 + n2;
}

// Inline function for subtraction


inline float subtract()
{
return n1 - n2;
}

// Inline function for multiplication


inline float multiply()
{
return n1 * n2;
}

// Inline function for division


inline float divide()
{
return n1 / n2;
}
};

int main()
{
Number num;

num.setValues();
cout << "Addition: " << num.add() << endl;
cout << "Subtraction: " << num.subtract() << endl;
cout << "Multiplication: " << num.multiply() << endl;
cout << "Division: " << num.divide() << endl;
return 0;
}

7) WAP to create two classes test1 and test2 which stores marks
of a student. Read value for class objects and calculate average of
two tests using friend function.
#include <iostream>
using namespace std;

class Test2; // Forward declaration of class Test2


class Test1 {
public:
float marks1; // Marks of the first test
// Function to read marks for the first test
void readMarks() {
cout << "Enter marks for Test 1: ";
cin >> marks1;
}
// Friend function declaration
friend float calculateAverage(Test1, Test2);
};
class Test2 {
public:
float marks2; // Marks of the second test
// Function to read marks for the second test
void readMarks() {
cout << "Enter marks for Test 2: ";
cin >> marks2;
}
// Friend function declaration
friend float calculateAverage(Test1, Test2);
};

// Friend function definition to calculate average


float calculateAverage(Test1 t1, Test2 t2) {
return (t1.marks1 + t2.marks2) / 2.0; // Calculating average of
the two tests
}

int main() {
Test1 t1;
Test2 t2;
float average;
// Reading marks for both tests
t1.readMarks();
t2.readMarks();
// Calculating and displaying the average using the friend
function
average = calculateAverage(t1, t2);
cout << "The average marks of the two tests are: " << average
<< endl;
return 0;
}
8) Write a Program to define a class having data members
principal, duration and rate of interest. Declare rate _of_ interest
as static member variable .calculate the simple interest and
display it.
#include <iostream>
using namespace std;

class Loan {
public:
float principal;
int duration;
static float rate_of_interest;

void accept() {
cout << "Enter the principal amount: ";
cin >> principal;
cout << "Enter the duration of the loan (in years): ";
cin >> duration;
}

// Function to calculate simple interest


float calculateInterest() {
return (principal * duration * rate_of_interest) / 100;
}

// Function to display the details


void displayDetails() {
cout << "Principal Amount: " << principal << endl;
cout << "Duration: " << duration << " years" << endl;
cout << "Rate of Interest: " << rate_of_interest << "%" << endl;
cout << "Simple Interest: " << calculateInterest() << endl;
}
};

// Initialize static member outside the class


float Loan::rate_of_interest = 5.0; // Default rate of interest

int main() {
Loan l;
l.accept();
l.displayDetails();
return 0;
}

9) Write a C++ program to declare class ‘Account’ having data


members as Account_No and Balance. Accept this data for 5
accounts and display data of Accounts having balance greater
than 10000.
#include <iostream>
using namespace std;

class Account {
public:
int Account_No; // Account number
float Balance; // Account balance

// Function to accept account details


void acceptData() {
cout << "Enter Account Number: ";
cin >> Account_No;
cout << "Enter Account Balance: ";
cin >> Balance;
}

// Function to display account details if balance is greater than


10000
void displayData() {
cout << "Account Number: " << Account_No << endl;
cout << "Account Balance: " << Balance << endl;
cout << "------------------------------" << endl;
}
};

int main() {
Account accounts[5]; // Array of 5 Account objects

// Accept data for 5 accounts


for (int i = 0; i < 5; i++) {
cout << "Enter details for Account " << i + 1 << endl;
accounts[i].acceptData();
cout << endl;
}

// Display data of accounts with balance greater than 10000


cout << "Accounts with balance greater than 10000:" << endl;
for (int i = 0; i < 5; i++) {
if (accounts[i].Balance > 10000) {
accounts[i].displayData();
}
}
return 0;
}

10) Define a class student which contain member variables as


ro no ,name and course. Write a program using constructor as
"Computer Engineering" for course. Accept this data for objects of
class and display the data.
#include <iostream>
#include <string>
using namespace std;

class Student {
private:
int rollno;
string name;
string course;

public:
Student() {
course = "Computer Engineering";
}

void acc() {
cout << "Enter Roll Number: ";
cin >> rollno;
cout << "Enter Name: ";
cin >> name;
}
void dis() {
cout << "Roll Number: " << rollno << endl;
cout << "Name: " << name << endl;
cout << "Course: " << course << endl;
}
};

int main() {
Student s1;
Student s2;
Student s3;

s1.acc();
s2.acc();
s3.acc();

s1.dis();
s2.dis();
s3.dis();

return 0;
}

11) Write a C++ program to define a class "Employee" having data


members emp_no, emp_name and emp_designation. Derive a
class "Salary" from "Employee" having data members basic, hra,
da, gross_sal. Accept and display data for one employee.
#include <iostream>
#include <string>
using namespace std;
// Base class Employee
class Employee {
protected:
int emp_no; // Employee number
string emp_name; // Employee name
string emp_designation; // Employee designation

public:

void acceptEmployeeData() {
cout << "Enter Employee Number: ";
cin >> emp_no;
cout << "Enter Employee Name: ";
cin >> emp_name;
cout << "Enter Employee Designation: ";
cin >> emp_designation;
}

void displayEmployeeData() {
cout << "Employee Number: " << emp_no << endl;
cout << "Employee Name: " << emp_name << endl;
cout << "Employee Designation: " << emp_designation << endl;
}
};

class Salary : public Employee {


private:
float basic;
float hra;
float da;
float gross_sal;
public:
void acceptSalaryData() {
cout << "Enter Basic Salary: ";
cin >> basic;
cout << "Enter HRA: ";
cin >> hra;
cout << "Enter DA: ";
cin >> da;
}

void calculateAndDisplayGrossSalary() {
gross_sal = basic + hra + da;
cout << "Gross Salary: " << gross_sal << endl;
}
};

int main() {
Salary employee1;

// Accept employee and salary details


employee1.acceptEmployeeData();
employee1.acceptSalaryData();

// Display employee details


cout << "\nEmployee Details:\n";
employee1.displayEmployeeData();
employee1.calculateAndDisplayGrossSalary();

return 0;
}
#include <iostream>
using namespace std;

// Base class Employee


class Employee {
protected:
int Emp_id;
string Emp_name;
public:
void acce() {
cout << "Enter Employee ID: ";
cin >> Emp_id;
cout << "Enter Employee Name: ";
cin >> Emp_name;
}
void dise() {
cout << "Employee ID: " << Emp_id << endl;
cout << "Employee Name: " << Emp_name << endl;
}
};

// Another base class Emp_union


class Emp_union {
protected:
string Member_id;
public:
void accu() {
cout << "Enter Member ID: ";
cin >> Member_id;
}
void disu() {
cout << "Member ID: " << Member_id << endl;
}
};

class Emp_Info : public Employee, public Emp_union {


protected:
float Basic_Salary;
public:
void acci() {
acce();
accu();
cout << "Enter Basic Salary: ";
cin >> Basic_Salary;
}
void disi() {
dise();
disu();
cout << "Basic Salary: " << Basic_Salary << endl;
}
};

int main(){
Emp_Info e;
e.acci();
cout<<endl<<"Employee Information"<<endl;
e.disi();

return 0;
}

13) Write a C++ program to implement the fo owing inheritance.


Accept and display data for one programmer and one manager.
Make display function virtual.
#include <iostream>
#include <string>
using namespace std;
class Employee
{
protected:
int empid;
string empcode;

public:
void accept()
{
cout << "Enter Employee ID: ";
cin >> empid;
cout << "Enter Employee Code: ";
cin >> empcode;
}
virtual void display()
{
cout << "Employee ID: " << empid << endl;
cout << "Employee Code: " << empcode << endl;
}
};
class Programmer : public Employee
{
string skill;

public:
void accept()
{
Employee::accept();
cout << "Enter Programmer's Skill: ";
cin >> skill;
}
void display() override
{
Employee::display();
cout << "Skill: " << skill << endl;
}
};
class Manager : public Employee
{
string department;

public:
void accept()
{
Employee::accept();
cout << "Enter Manager's Department: ";
cin >> department;
}
void display() override
{
Employee::display();
cout << "Department: " << department << endl;
}
};
int main()
{
Programmer p;
Manager m;
cout << "Enter details for Programmer:\n";
p.accept();
cout << "\nEnter details for Manager:\n";
m.accept();
Employee *e;
e = &p;
cout << "\nDisplaying Programmer Details:\n";
e->display();
e = &m;
cout << "\nDisplaying Manager Details:\n";
e->display();
return 0;
}

#include <iostream>
using namespace std;

// Virtual Base Class Student


class Student {
protected:
string name;
int roll_no;

public:
void acceptStudentData() {
cout << "Enter Student Name: ";
cin >> name;
cout << "Enter Roll Number: ";
cin >> roll_no;
}

void displayStudentData() {
cout << "Student Name: " << name << endl;
cout << "Roll Number: " << roll_no << endl;
}
};

// Derived class Test (from Student)


class Test : virtual public Student {
protected:
float marks;

public:
void acceptTestData() {
cout << "Enter Marks: ";
cin >> marks;
}

void displayTestData() {
cout << "Marks: " << marks << endl;
}
};
// Derived class Sports (from Student)
class Sports : virtual public Student {
protected:
int score;

public:
void acceptSportsData() {
cout << "Enter Sports Score: ";
cin >> score;
}

void displaySportsData() {
cout << "Sports Score: " << score << endl;
}
};

// Derived class Result (from Test and Sports)


class Result : public Test, public Sports {
public:
void acceptData() {
acceptStudentData();
acceptTestData();
acceptSportsData();
}

void displayData() {
displayStudentData();
displayTestData();
displaySportsData();
}
};
int main() {
Result result;

cout << "Enter details for Student, Test, and Sports:\n";


result.acceptData();

cout << "\nStudent Result:\n";


result.displayData();

return 0;
}

15) Write a program which shows the use of constructor in derived


class
#include <iostream>
using namespace std;

// Base class
class Base {
public:
Base(int a) {
cout << "Base class constructor called with value: " << a <<
endl;
}
};

// Derived class
class Derived : public Base {
public:
Derived(int a, int b) : Base(a) {
cout << "Derived class constructor called with value: " << b <<
endl;
}
};

int main() {
// Create an object of the derived class with parameters
Derived obj(10, 20);

return 0;
}

16) Write a C++ program to declare a class birthday having data


members day, month, year. Accept this information for five objects
using pointer to the array of objects

#include <iostream>
using namespace std;

// Class Declaration
class Birthday {
public:
int day;
int month;
int year;

// Member function to accept data for the birthday


void acceptData() {
cout << "Enter Day: ";
cin >> day;
cout << "Enter Month: ";
cin >> month;
cout << "Enter Year: ";
cin >> year;
}

// Member function to display the birthday


void displayData() {
cout << "Birthday: " << day << "/" << month << "/" << year <<
endl;
}
};

int main() {
// Pointer to an array of 5 objects of the Birthday class
Birthday* birthdays = new Birthday[5]; // Dynamically allocate
memory for 5 Birthday objects

// Accept birthday data for 5 objects


for (int i = 0; i < 5; ++i) {
cout << "\nEnter details for birthday " << (i + 1) << ":\n";
birthdays[i].acceptData();
}

// Display birthday data for all 5 objects


cout << "\nDisplaying all birthday details:\n";
for (int i = 0; i < 5; ++i) {
cout << "\nBirthday " << (i + 1) << ": ";
birthdays[i].displayData();
}

// Deallocate memory for the array of objects


delete[] birthdays;

return 0;
}

17) Write a C++ program declare a class "polygon" having data


members width and height. Derive classes "rectangle" and
"triangle" from "polygon" having area () as a member function.
Calculate area of triangle and rectangle using pointer to derived
class object.
#include <iostream>
using namespace std;

// Base class Polygon


class Polygon {
protected:
float width, height;

public:
// Function to get dimensions from the user
void get() {
cout << "Enter width: ";
cin >> width;
cout << "Enter height: ";
cin >> height;
}

// Pure virtual function to calculate the area


virtual float area() = 0; // Must be overridden by derived
classes
};

// Derived class Rectangle


class Rectangle : public Polygon {
public:
// Override the area() function to calculate the area of the
rectangle
float area() override {
return width * height;
}
};

// Derived class Triangle


class Triangle : public Polygon {
public:
// Override the area() function to calculate the area of the
triangle
float area() override {
return 0.5 * width * height;
}
};

int main() {
Rectangle rect; // Object of Rectangle
Triangle tri; // Object of Triangle
Polygon* poly; // Pointer to base class

// Get dimensions for the rectangle


cout << "Enter dimensions for Rectangle:" << endl;
rect.get();

// Get dimensions for the triangle


cout << "Enter dimensions for Triangle:" << endl;
tri.get();

// Use the pointer to calculate area for Rectangle


poly = &rect;
cout << "Area of Rectangle: " << poly->area() << endl;

// Use the pointer to calculate area for Triangle


poly = &tri;
cout << "Area of Triangle: " << poly->area() << endl;

return 0;
}

18) Write a C++ Program that find the sum of two int and double
number using function overloading.
#include <iostream>
using namespace std;

// Class to perform sum operations


class Calculator {
public:
// Function to calculate the sum of two integers
int sum(int a, int b) {
return a + b;
}

// Function to calculate the sum of two doubles


double sum(double a, double b) {
return a + b;
}
};
int main() {
Calculator calc; // Create an object of the Calculator class
int int1, int2;
double double1, double2;

// Input two integers


cout << "Enter two integers: ";
cin >> int1 >> int2;

// Input two double numbers


cout << "Enter two double numbers: ";
cin >> double1 >> double2;

// Calculate and display the sums


cout << "Sum of integers: " << calc.sum(int1, int2) << endl;
cout << "Sum of doubles: " << calc.sum(double1, double2) <<
endl;

return 0;
}

19) Write a C++ program to overload unary operators (++)


increment and (--) decrement by using member function and
friend function.
#include <iostream>
using namespace std;

class Number {
int value;
public:
// Constructor to initialize the value
Number(int val = 0) : value(val) {}

// Display the value


void display() {
cout << "Value: " << value << endl;
}

// Overload ++ (increment) using member function


Number operator++() {
++value; // Pre-increment
return *this;
}

// Overload -- (decrement) using friend function


friend Number operator--(Number& num);
};

// Overload -- (decrement) using a friend function


Number operator--(Number& num) {
--num.value; // Pre-decrement
return num;
}

int main() {
Number n1(10); // Initialize n1 with value 10

cout << "Initial value:" << endl;


n1.display();

// Use the increment operator (++)


++n1;
cout << "After increment (++):" << endl;
n1.display();

// Use the decrement operator (--)


--n1;
cout << "After decrement (--):" << endl;
n1.display();

return 0;
}

20) Write a C++ program to compare two strings using'==' operator


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

class String {
string str; // String data

public:
// Constructor to initialize the string
String( string s = "") : str(s) {}

// Overload '==' operator


bool operator==( String other) {
return str == other.str;
}

// Function to display the string


void display() {
cout << str;
}
};

int main() {
String s1("Hello"), s2("World"), s3("Hello");

cout << "Comparing s1 and s2: ";


if (s1 == s2)
cout << "Strings are equal" << endl;
else
cout << "Strings are not equal" << endl;

cout << "Comparing s1 and s3: ";


if (s1 == s3)
cout << "Strings are equal" << endl;
else
cout << "Strings are not equal" << endl;

return 0;
}

21) Write a program which shows the use of function overriding.


#include <iostream>
using namespace std;

class Base {
public:
// Virtual function to be overridden
virtual void display() {
cout << "Display function of Base class." << endl;
}
};

class Derived : public Base {


public:
// Overriding the Base class function
void display() override {
cout << "Display function of Derived class." << endl;
}
};

int main() {
Base* basePtr; // Pointer to Base class
Derived d; // Object of Derived class

basePtr = &d;

// Call the display function using the Base class pointer


basePtr->display();

return 0;
}

22) Write a program which shows the use of Abstract class.


#include <iostream>
using namespace std;

// Abstract class
class Shape {
public:
virtual void area() = 0; // Pure virtual function
};
// Derived class: Rectangle
class Rectangle : public Shape {
public:
void area() override {
cout << "This shape is Rectangle" << endl;
}
};

// Derived class: Circle


class Circle : public Shape {
public:
void area() override {
cout << "This shape is Circle" << endl;
}
};

int main() {
Shape* shape; // Pointer to base class

Rectangle rect;
Circle circ;

// Use Rectangle
shape = &rect;
shape->area();

// Use Circle
shape = &circ;
shape->area();

return 0;
}
23) Write a program to read from a file using constructor function.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
ifstream file("sample.txt"); // Open the file using constructor

if (!file) {
cout << "Error: File could not be opened." << endl;
return 1; // Return error code if file can't be opened
}

string line;
while (getline(file, line)) {
cout << line << endl; // Display each line of the file
}

file.close(); // Close the file after reading


return 0;
}

24) Write a program to write into file using open function.


#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create an object of ofstream and open the file in write mode
ofstream file;
file.open("output.txt"); // Open the file for writing

if (!file) {
cout << "Error: File could not be opened." << endl;
return 1; // Return error code if file can't be opened
}

// Write some data to the file


file << "Hello, World!" << endl;
file << "This is a test file." << endl;
file << "Writing to file using open function." << endl;

// Close the file after writing


file.close();

cout << "Data has been written to the file." << endl;

return 0;
}

25) WAP to copy content of one file into another using open
function.
#include <iostream>
#include <fstream>
using namespace std;

int main() {
string sourceFile = "sample.txt"; // Source file name
string destFile = "destination.txt"; // Destination file name

// Open the source file in read mode


ifstream src;
src.open(sourceFile);
if (!src) {
cout << "Error: Source file could not be opened." << endl;
return 1; // Return error code if source file can't be opened
}

// Open the destination file in write mode


ofstream dest;
dest.open(destFile);
if (!dest) {
cout << "Error: Destination file could not be opened." << endl;
return 1; // Return error code if destination file can't be
opened
}

// Copy contents from source file to destination file


char ch;
while (src.get(ch)) {
dest.put(ch); // Write each character to the destination file
}

// Close both files


src.close();
dest.close();

cout << "Content copied successfully from " << sourceFile << " to
" << destFile << endl;

return 0;
}

26) WAP to copy content of one file into another using constructor.
#include <iostream>
#include <fstream>
using namespace std;

int main() {
string sourceFile = "output.txt"; // Source file name
string destFile = "destination.txt"; // Destination file name

// Open the source file using the constructor of ifstream


ifstream src(sourceFile);
if (!src) {
cout << "Error: Source file could not be opened." << endl;
return 1; // Return error code if source file can't be opened
}

// Open the destination file using the constructor of ofstream


ofstream dest(destFile);
if (!dest) {
cout << "Error: Destination file could not be opened." << endl;
return 1; // Return error code if destination file can't be
opened
}

// Copy content from source file to destination file


char ch;
while (src.get(ch)) {
dest.put(ch); // Write each character to the destination file
}
// Close both files
src.close();
dest.close();

cout << "Content copied successfully from " << sourceFile << " to
" << destFile << endl;

return 0;
}

27) Write programs to copy the contents of one file into another
file using forma ed input/output function.
#include <iostream>
#include <fstream>
using namespace std;

int main() {
string sourceFile = "sample.txt"; // Source file name
string destFile = "destination.txt"; // Destination file name

// Open the source file for reading


ifstream src(sourceFile);
if (!src) {
cout << "Error: Source file could not be opened." << endl;
return 1; // Return error code if source file can't be opened
}

// Open the destination file for writing


ofstream dest(destFile);
if (!dest) {
cout << "Error: Destination file could not be opened." << endl;
return 1; // Return error code if destination file can't be
opened
}

// Read from source and write to destination with formatted


input/output
char ch;
while (src.get(ch)) { // Use get() to read character by
character
dest.put(ch); // Use put() to write character by character
}

// Close both files


src.close();
dest.close();

cout << "Content copied successfully from " << sourceFile << " to
" << destFile << endl;

return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy