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

Astha doc

Uploaded by

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

Astha doc

Uploaded by

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

1 . An electricity board charges the following rates to user.

For the first


100 units → 60p per unit. For the next 200 units→80p per unit. Beyond
300 units→90p per unit. All users are charged a minimum of Rs. 50; if
the total amount is more than 300 then an additional surcharges of 15%
is added. Write a program to accept name of user consumed and print
charges with the its rates.

#include <iostream>
#include <iomanip> // For formatting the output
using namespace std;

int main() {
string name;
double units, totalCharges = 0.0, surcharge = 0.0;

// Accept the user's name and the number of units consumed


cout << "Enter the name of the user: ";
getline(cin, name);
cout << "Enter the number of units consumed: ";
cin >> units;

// Minimum base charge of Rs. 50


totalCharges = 50;

// Calculate charges based on the number of units consumed


if (units <= 100) {
totalCharges += units * 0.60;
} else if (units <= 300) {
totalCharges += (100 * 0.60) + ((units - 100) * 0.80);
} else {
totalCharges += (100 * 0.60) + (200 * 0.80) + ((units - 300) * 0.90);
}

// Apply 15% surcharge if totalCharges are more than Rs. 300


if (totalCharges > 300) {
surcharge = totalCharges * 0.15;
totalCharges += surcharge;
}

// Display the total charges


cout << fixed << setprecision(2);
cout << "\n----- Electricity Bill -----\n";
cout << "Name of user: " << name << endl;
cout << "Units consumed: " << units << endl;
cout << "Total charges: Rs. " << totalCharges << endl;
if (surcharge > 0) {
cout << "Surcharge added: Rs. " << surcharge << endl;
}
cout << "----------------------------\n";

return 0;
}

2. Define a class to represent a bank account. Include the following


members: a. Name of the depositor b. Account number c. Type of
Account d. Balance amount in the Account Member Functions: a. To
assign initial values. b. To deposit an amount. c. To withdraw an amount
after checking the balance. d. To display name and balance. Write main
program and handle accounts of 5 customers

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

class BankAccount {
private:
string depositorName;
int accountNumber;
string accountType;
double balance;

public:
// Function to assign initial values
void initialize(string name, int accNum, string accType, double
initialBalance) {
depositorName = name;
accountNumber = accNum;
accountType = accType;
balance = initialBalance;
}

// Function to deposit an amount


void deposit(double amount) {
balance += amount;
cout << amount << " deposited successfully.\n";
}

// Function to withdraw an amount after checking balance


void withdraw(double amount) {
if (amount > balance) {
cout << "Insufficient balance! Withdrawal failed.\n";
} else {
balance -= amount;
cout << amount << " withdrawn successfully.\n";
}
}

// Function to display name and balance


void display() {
cout << "Depositor Name: " << depositorName << endl;
cout << "Account Number: " << accountNumber << endl;
cout << "Account Type: " << accountType << endl;
cout << "Balance: Rs. " << balance << endl;
}
};

int main() {
// Array to store 5 customers' bank accounts
BankAccount customers[5];

// Initialize 5 bank accounts


for (int i = 0; i < 5; i++) {
string name;
int accNum;
string accType;
double initialBalance;

cout << "\nEnter details for customer " << i + 1 << ":\n";
cout << "Name: ";
cin >> name;
cout << "Account Number: ";
cin >> accNum;
cout << "Account Type: ";
cin >> accType;
cout << "Initial Balance: ";
cin >> initialBalance;

customers[i].initialize(name, accNum, accType, initialBalance);


}

// Perform operations for the first customer as an example


int customerIndex = 0; // For the first customer
cout << "\nPerforming operations for " << customerIndex + 1 << "
customer:\n";

// Deposit 5000
customers[customerIndex].deposit(5000);

// Withdraw 2000
customers[customerIndex].withdraw(2000);

// Display account details


customers[customerIndex].display();

return 0;
}

3. Program to create a class person having members name and age.


Derive a class student having member percentage. Derive another class
teacher having member salary. Write necessary member function to
initialize, read and write data. Also write the main function.
#include <iostream>
#include <string>
using namespace std;
// Base class: Person
class Person {
protected:
string name;
int age;

public:
// Function to read data for a person
void readPersonData() {
cout << "Enter name: ";
cin >> name;
cout << "Enter age: ";
cin >> age;
}

// Function to display person data


void displayPersonData() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};

// Derived class: Student (inherits from Person)


class Student : public Person {
protected:
float percentage;

public:
// Function to read data for a student
void readStudentData() {
readPersonData(); // Call base class function
cout << "Enter percentage: ";
cin >> percentage;
}

// Function to display student data


void displayStudentData() {
displayPersonData(); // Call base class function
cout << "Percentage: " << percentage << "%" << endl;
}
};

// Derived class: Teacher (inherits from Person)


class Teacher : public Person {
protected:
double salary;

public:
// Function to read data for a teacher
void readTeacherData() {
readPersonData(); // Call base class function
cout << "Enter salary: ";
cin >> salary;
}

// Function to display teacher data


void displayTeacherData() {
displayPersonData(); // Call base class function
cout << "Salary: Rs. " << salary << endl;
}
};

// Main function
int main() {
// Create a Student object and read/display data
cout << "\n--- Student Data ---" << endl;
Student student;
student.readStudentData();
student.displayStudentData();

// Create a Teacher object and read/display data


cout << "\n--- Teacher Data ---" << endl;
Teacher teacher;
teacher.readTeacherData();
teacher.displayTeacherData();

return 0;
}

4. Program to create a class name student having date member name,


no & three marks. Write a member function to input name, rollno &
marks& calculate percentage.
#include <iostream>
#include <string>
using namespace std;

class Student {
private:
string name;
int rollNo;
float marks1, marks2, marks3;
float percentage;

public:
// Function to input student data
void inputData() {
cout << "Enter student's name: ";
cin >> name;
cout << "Enter roll number: ";
cin >> rollNo;
cout << "Enter marks for 3 subjects (out of 100): \n";
cout << "Subject 1: ";
cin >> marks1;
cout << "Subject 2: ";
cin >> marks2;
cout << "Subject 3: ";
cin >> marks3;
}

// Function to calculate percentage


void calculatePercentage() {
percentage = (marks1 + marks2 + marks3) / 3;
}

// Function to display student details


void displayData() {
cout << "\nStudent Name: " << name << endl;
cout << "Roll Number: " << rollNo << endl;
cout << "Marks: " << marks1 << ", " << marks2 << ", " << marks3 <<
endl;
cout << "Percentage: " << percentage << "%" << endl;
}
};

int main() {
// Create a Student object
Student student;

// Input student data


student.inputData();

// Calculate the percentage


student.calculatePercentage();

// Display student data


student.displayData();

return 0;
}
5. Create one class time which has hour, minute and second as data
member. Now write input function to input class values and find time in
the form of minute

#include <iostream>
using namespace std;

class Time {
private:
int hours;
int minutes;
int seconds;
public:
// Function to input time values (hours, minutes, seconds)
void inputTime() {
cout << "Enter hours: ";
cin >> hours;
cout << "Enter minutes: ";
cin >> minutes;
cout << "Enter seconds: ";
cin >> seconds;
}

// Function to convert time to total minutes


int convertToMinutes() {
int totalMinutes = hours * 60 + minutes + seconds / 60;
return totalMinutes;
}

// Function to display the time in the form of total minutes


void displayTimeInMinutes() {
cout << "Total time in minutes: " << convertToMinutes() << "
minutes" << endl;
}
};
int main() {
// Create a Time object
Time time;

// Input time values


time.inputTime();

// Display time in total minutes


time.displayTimeInMinutes();

return 0;
}

6. Create a class called "Vehicle" which contains data members


registration number and fuel type Make getdata() function to input data
value. Create class "two-Wheeler "from vehicle which contains data
member’s distance and mileage Make getdata() function to input data.
Use overloading techniques for getdata()function and display the
information with fuel used.
#include <iostream>
#include <string>
using namespace std;

// Base class: Vehicle


class Vehicle {
protected:
string registrationNumber;
string fuelType;

public:
// Function to input vehicle data
void getData() {
cout << "Enter registration number: ";
cin >> registrationNumber;
cout << "Enter fuel type (Petrol/Diesel/Electric): ";
cin >> fuelType;
}

// Function to display vehicle information


void displayData() {
cout << "Registration Number: " << registrationNumber << endl;
cout << "Fuel Type: " << fuelType << endl;
}
};

// Derived class: TwoWheeler (inherits from Vehicle)


class TwoWheeler : public Vehicle {
private:
float distance; // Distance traveled in kilometers
float mileage; // Mileage in km per liter
public:
// Overloaded function to input two-wheeler data
void getData() {
Vehicle::getData(); // Call base class function to input registration
number and fuel type
cout << "Enter distance traveled (in km): ";
cin >> distance;
cout << "Enter mileage (in km/l): ";
cin >> mileage;
}

// Function to display two-wheeler information with fuel used


void displayData() {
Vehicle::displayData(); // Call base class function to display
registration number and fuel type
cout << "Distance Traveled: " << distance << " km" << endl;
cout << "Mileage: " << mileage << " km/l" << endl;
cout << "Fuel Used: " << calculateFuelUsed() << " liters" << endl;
}

// Function to calculate fuel used based on distance and mileage


float calculateFuelUsed() {
return distance / mileage; // Fuel used = distance / mileage
}
};
int main() {
// Create an object of TwoWheeler class
TwoWheeler bike;

// Input data for two-wheeler


bike.getData();

// Display data for two-wheeler


bike.displayData();

return 0;
}
7. Write a program that consists of two classes: Time12 and Time24. •
Time12: This class maintains time in a 12-hour format (e.g., 3:45 PM). •
Time24: This class maintains time in a 24-hour format (e.g., 15:45). The
program should allow: 1. Conversion between the two time formats
(Time12 to Time24 and vice versa). 2. Display of the time in both
formats. 3. Input of time in either format and updating it accordingly. 4.
Any additional functionality to manipulate or compare time objects if
required. Make sure to implement the necessary methods to achieve
these functionalities in both classes
#include <iostream>
#include <iomanip>
using namespace std;

// Class to maintain 12-hour time format


class Time12 {
private:
int hours; // 1 to 12
int minutes;
bool isPM; // true if PM, false if AM

public:
// Default constructor
Time12(int h = 12, int m = 0, bool pm = false) : hours(h), minutes(m),
isPM(pm) {}

// Function to input time in 12-hour format


void input() {
char period[3]; // AM or PM
cout << "Enter time in 12-hour format (HH:MM AM/PM): ";
scanf("%d:%d %s", &hours, &minutes, period);

// Convert AM/PM to boolean


isPM = (period[0] == 'P' || period[0] == 'p');
}

// Display time in 12-hour format


void display() const {
cout << setw(2) << setfill('0') << hours << ":"
<< setw(2) << setfill('0') << minutes << " "
<< (isPM ? "PM" : "AM") << endl;
}

// Function to convert Time12 to Time24


friend class Time24;
};

// Class to maintain 24-hour time format


class Time24 {
private:
int hours; // 0 to 23
int minutes;

public:
// Default constructor
Time24(int h = 0, int m = 0) : hours(h), minutes(m) {}

// Function to input time in 24-hour format


void input() {
cout << "Enter time in 24-hour format (HH:MM): ";
scanf("%d:%d", &hours, &minutes);
}

// Display time in 24-hour format


void display() const {
cout << setw(2) << setfill('0') << hours << ":"
<< setw(2) << setfill('0') << minutes << endl;
}

// Function to convert Time24 to Time12


Time12 toTime12() const {
int h = hours;
bool pm = false;
if (h == 0) {
h = 12;
pm = false;
} else if (h == 12) {
pm = true;
} else if (h > 12) {
h -= 12;
pm = true;
}

return Time12(h, minutes, pm);


}

// Function to convert Time12 to Time24


Time24(Time12 t12) {
hours = t12.hours % 12; // Convert to 24-hour format (0 to 11 for
AM/PM times)
if (t12.isPM) {
hours += 12; // Add 12 for PM times
}
if (t12.hours == 12 && !t12.isPM) {
hours = 0; // Handle 12 AM as 00 in 24-hour format
}
minutes = t12.minutes;
}

// Function to compare two Time24 objects


bool isEqual(const Time24& other) const {
return hours == other.hours && minutes == other.minutes;
}
};

// Main program
int main() {
Time12 t12;
Time24 t24;

// Input time in 12-hour format


t12.input();
cout << "Time in 12-hour format: ";
t12.display();

// Convert 12-hour time to 24-hour format


t24 = Time24(t12);
cout << "Converted time in 24-hour format: ";
t24.display();

// Input time in 24-hour format


t24.input();
cout << "Time in 24-hour format: ";
t24.display();

// Convert 24-hour time to 12-hour format


t12 = t24.toTime12();
cout << "Converted time in 12-hour format: ";
t12.display();

return 0;
}

8. Create two classes DM and DB which store the values of distance. DM


stores distance in meters and centimeters. DB stores distances in feet
and inches. Writea program that can read values for the class object and
add one object of DM with another object of DB. Use a friend function
to carry out the addition Operation and this function will display answer
in meter and centimeters.
#include <iostream>
using namespace std;
class DB; // Forward declaration for DB class

class DM {
private:
float meters; // Distance in meters
float centimeters; // Distance in centimeters

public:
DM(float m = 0, float cm = 0) : meters(m), centimeters(cm) {}

// Function to input distance in meters and centimeters


void input() {
cout << "Enter distance in meters and centimeters (separated by
space): ";
cin >> meters >> centimeters;
}

// Friend function to add DM and DB objects


friend DM addDistances(const DM& dm, const DB& db);

// Function to display the result in meters and centimeters


void display() const {
float totalMeters = meters + centimeters / 100;
cout << "Total distance: " << totalMeters << " meters" << endl;
}
};

class DB {
private:
float feet; // Distance in feet
float inches; // Distance in inches

public:
DB(float ft = 0, float in = 0) : feet(ft), inches(in) {}

// Function to input distance in feet and inches


void input() {
cout << "Enter distance in feet and inches (separated by space): ";
cin >> feet >> inches;
}

// Friend function to add DM and DB objects


friend DM addDistances(const DM& dm, const DB& db);
};

// Friend function to add a DM object and a DB object


DM addDistances(const DM& dm, const DB& db) {
// Conversion factors
const float metersPerFoot = 0.3048; // 1 foot = 0.3048 meters
const float centimetersPerInch = 2.54; // 1 inch = 2.54 cm
// Convert feet and inches to meters and centimeters
float dbMeters = db.feet * metersPerFoot;
float dbCentimeters = db.inches * centimetersPerInch;

// Calculate total meters and centimeters


float totalMeters = dm.meters + dbMeters;
float totalCentimeters = dm.centimeters + dbCentimeters;

// If total centimeters exceeds 100, convert to meters


if (totalCentimeters >= 100) {
totalMeters += totalCentimeters / 100;
totalCentimeters = fmod(totalCentimeters, 100);
}

// Return the result as a DM object


return DM(totalMeters, totalCentimeters);
}

int main() {
DM dm;
DB db;

// Input distances for DM and DB


cout << "Enter distance in DM (meters and centimeters):" << endl;
dm.input();

cout << "Enter distance in DB (feet and inches):" << endl;


db.input();

// Add distances
DM result = addDistances(dm, db);

// Display the result


result.display();

return 0;
}

9. Write a program to maintain a telephone directory use add() and


show() Methods to add new entries and display the telephone numbers
of a person when the name of the person is given.
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;

class TelephoneDirectory {
private:
// Map to store the name as the key and phone number as the value
unordered_map<string, string> directory;
public:
// Method to add a new entry in the directory
void add(string name, string phoneNumber) {
directory[name] = phoneNumber;
cout << "Entry added for " << name << endl;
}

// Method to show the phone number of a person by their name


void show(string name) {
// Check if the name exists in the directory
if (directory.find(name) != directory.end()) {
cout << "Phone number of " << name << ": " << directory[name]
<< endl;
} else {
cout << name << " not found in the directory." << endl;
}
}
};

int main() {
TelephoneDirectory directory;
int choice;
string name, phoneNumber;
// Menu-driven program to manage the telephone directory
while (true) {
cout << "\nTelephone Directory" << endl;
cout << "1. Add new entry" << endl;
cout << "2. Show telephone number" << endl;
cout << "3. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
// Add a new entry
cout << "Enter name: ";
cin.ignore(); // To consume the newline character left in the
buffer
getline(cin, name);
cout << "Enter phone number: ";
cin >> phoneNumber;
directory.add(name, phoneNumber);
break;

case 2:
// Show the telephone number for a given name
cout << "Enter name to search: ";
cin.ignore(); // To consume the newline character left in the
buffer
getline(cin, name);
directory.show(name);
break;

case 3:
// Exit the program
cout << "Exiting..." << endl;
return 0;

default:
cout << "Invalid choice! Please try again." << endl;
}
}

return 0;
}

10. Create a base class named Shape to store a double-type value that
can be used to compare areas. Derive two specific classes, Triangle and
Rectangle, from the base class Shape. Include a member function,
getData, in the base class to initialize the base data members, and
another function, displayArea, to display the area.
#include <iostream>
using namespace std;

// Base class Shape


class Shape {
protected:
double dimension1, dimension2; // Dimensions to be used for area
calculation

public:
// Function to get data for dimensions
void getData(double d1, double d2) {
dimension1 = d1;
dimension2 = d2;
}

// Virtual function to display the area


virtual void displayArea() = 0; // Pure virtual function
};

// Derived class for Triangle


class Triangle : public Shape {
public:
// Overriding the displayArea() function for Triangle
void displayArea() override {
double area = 0.5 * dimension1 * dimension2;
cout << "Area of the Triangle: " << area << endl;
}
};
// Derived class for Rectangle
class Rectangle : public Shape {
public:
// Overriding the displayArea() function for Rectangle
void displayArea() override {
double area = dimension1 * dimension2;
cout << "Area of the Rectangle: " << area << endl;
}
};

int main() {
// Create objects of Triangle and Rectangle
Triangle triangle;
Rectangle rectangle;

double base, height, length, width;

// Input data for triangle


cout << "Enter base and height of the triangle: ";
cin >> base >> height;
triangle.getData(base, height); // Initialize dimensions for triangle

// Input data for rectangle


cout << "Enter length and width of the rectangle: ";
cin >> length >> width;
rectangle.getData(length, width); // Initialize dimensions for
rectangle

// Display areas
triangle.displayArea();
rectangle.displayArea();

return 0;
}

11. Write a program for Tower of Hanoi


#include <iostream>
using namespace std;

// Function to perform the Tower of Hanoi algorithm


void towerOfHanoi(int n, char source, char destination, char auxiliary) {
// Base case: If there's only one disk to move
if (n == 1) {
cout << "Move disk 1 from " << source << " to " << destination <<
endl;
return;
}

// Move n-1 disks from source to auxiliary, using destination as


auxiliary
towerOfHanoi(n - 1, source, auxiliary, destination);

// Move the nth disk from source to destination


cout << "Move disk " << n << " from " << source << " to " <<
destination << endl;

// Move the n-1 disks from auxiliary to destination, using source as


auxiliary
towerOfHanoi(n - 1, auxiliary, destination, source);
}

int main() {
int n; // Number of disks

// Get user input for number of disks


cout << "Enter the number of disks: ";
cin >> n;

// Function call to solve Tower of Hanoi


towerOfHanoi(n, 'A', 'C', 'B'); // A, B, and C are names of the rods

return 0;
}

12. Write Program to implement Stack Operations like PUSH, POP, PEEP,
UPDATE and DISPLAY using class and object.
#include <iostream>
using namespace std;

class Stack {
private:
int* arr; // Array to hold the stack elements
int top; // Index of the top element
int capacity; // Maximum number of elements in the stack

public:
// Constructor to initialize stack
Stack(int size) {
capacity = size;
arr = new int[capacity]; // Dynamic array allocation
top = -1; // Stack is initially empty
}

// Destructor to free allocated memory


~Stack() {
delete[] arr;
}

// Function to add an element to the stack


void push(int x) {
if (top >= capacity - 1) {
cout << "Stack Overflow! Cannot push " << x << endl;
return;
}
arr[++top] = x; // Increment top and add element
cout << x << " pushed to stack" << endl;
}

// Function to remove the top element from the stack


void pop() {
if (top < 0) {
cout << "Stack Underflow! Cannot pop from empty stack" <<
endl;
return;
}
cout << arr[top--] << " popped from stack" << endl; // Decrement
top and return element
}

// Function to return the top element without removing it


int peep() {
if (top < 0) {
cout << "Stack is empty!" << endl;
return -1; // Indicates an empty stack
}
return arr[top]; // Return top element
}
// Function to update the top element
void update(int x) {
if (top < 0) {
cout << "Stack is empty! Cannot update" << endl;
return;
}
arr[top] = x; // Update top element
cout << "Top element updated to " << x << endl;
}

// Function to display the stack elements


void display() {
if (top < 0) {
cout << "Stack is empty!" << endl;
return;
}
cout << "Stack elements: ";
for (int i = top; i >= 0; i--) {
cout << arr[i] << " "; // Display elements from top to bottom
}
cout << endl;
}
};
int main() {
int size;
cout << "Enter stack size: ";
cin >> size;

Stack stack(size); // Create stack of given size

int choice, value;

do {
cout << "\nStack Operations Menu:\n";
cout << "1. PUSH\n";
cout << "2. POP\n";
cout << "3. PEEP\n";
cout << "4. UPDATE\n";
cout << "5. DISPLAY\n";
cout << "6. EXIT\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
cout << "Enter value to push: ";
cin >> value;
stack.push(value);
break;
case 2:
stack.pop();
break;
case 3:
value = stack.peep();
if (value != -1) {
cout << "Top element: " << value << endl;
}
break;
case 4:
cout << "Enter new value for top element: ";
cin >> value;
stack.update(value);
break;
case 5:
stack.display();
break;
case 6:
cout << "Exiting..." << endl;
break;
default:
cout << "Invalid choice! Please try again." << endl;
}
} while (choice != 6);
return 0;
}

13. Write Program to convert Infix to Postfix Expression using class and
object.
#include <iostream>
#include <stack>
#include <string>
#include <cctype>

using namespace std;

class InfixToPostfix {
private:
stack<char> operatorStack; // Stack to hold operators

// Function to determine precedence of operators


int precedence(char op) {
if (op == '+' || op == '-') {
return 1;
}
if (op == '*' || op == '/') {
return 2;
}
if (op == '^') {
return 3;
}
return 0;
}

public:
// Function to convert infix expression to postfix expression
string convertToPostfix(const string& infix) {
string postfix = "";
for (char token : infix) {
// If the token is an operand, add it to the postfix expression
if (isalnum(token)) {
postfix += token;
}
// If the token is '(', push it to the stack
else if (token == '(') {
operatorStack.push(token);
}
// If the token is ')', pop from the stack to the postfix expression
until '(' is encountered
else if (token == ')') {
while (!operatorStack.empty() && operatorStack.top() != '(') {
postfix += operatorStack.top();
operatorStack.pop();
}
operatorStack.pop(); // Remove '(' from stack
}
// If the token is an operator
else {
while (!operatorStack.empty() &&
precedence(operatorStack.top()) >= precedence(token)) {
postfix += operatorStack.top();
operatorStack.pop();
}
operatorStack.push(token); // Push current operator onto the
stack
}
}

// Pop all remaining operators from the stack


while (!operatorStack.empty()) {
postfix += operatorStack.top();
operatorStack.pop();
}

return postfix; // Return the final postfix expression


}
};

int main() {
InfixToPostfix converter; // Create an object of InfixToPostfix class
string infix;

cout << "Enter infix expression: ";


getline(cin, infix); // Read the infix expression

string postfix = converter.convertToPostfix(infix); // Convert to postfix


cout << "Postfix expression: " << postfix << endl; // Display postfix
expression

return 0;
}

14. Write Program to convert Infix to Prefix Expression using class and
object.
#include <iostream>
#include <stack>
#include <string>
#include <algorithm>
#include <cctype>

using namespace std;

class InfixToPrefix {
private:
stack<char> operatorStack; // Stack to hold operators
// Function to determine precedence of operators
int precedence(char op) {
if (op == '+' || op == '-') {
return 1;
}
if (op == '*' || op == '/') {
return 2;
}
if (op == '^') {
return 3;
}
return 0;
}

// Function to reverse the input expression


string reverse(const string& exp) {
string reversedExp = exp;
reverse(reversedExp.begin(), reversedExp.end());
return reversedExp;
}

public:
// Function to convert infix expression to prefix expression
string convertToPrefix(const string& infix) {
string prefix = "";
string reversedInfix = reverse(infix);

// Iterate through the reversed infix expression


for (char token : reversedInfix) {
// If the token is an operand, add it to the prefix expression
if (isalnum(token)) {
prefix += token;
}
// If the token is ')', push it to the stack
else if (token == ')') {
operatorStack.push(token);
}
// If the token is '(', pop from the stack to the prefix expression
until ')' is encountered
else if (token == '(') {
while (!operatorStack.empty() && operatorStack.top() != ')') {
prefix += operatorStack.top();
operatorStack.pop();
}
operatorStack.pop(); // Remove ')' from stack
}
// If the token is an operator
else {
while (!operatorStack.empty() &&
precedence(operatorStack.top()) > precedence(token)) {
prefix += operatorStack.top();
operatorStack.pop();
}
operatorStack.push(token); // Push current operator onto the
stack
}
}

// Pop all remaining operators from the stack


while (!operatorStack.empty()) {
prefix += operatorStack.top();
operatorStack.pop();
}

// Reverse the prefix expression to get the final result


reverse(prefix.begin(), prefix.end());
return prefix; // Return the final prefix expression
}
};

int main() {
InfixToPrefix converter; // Create an object of InfixToPrefix class
string infix;

cout << "Enter infix expression: ";


getline(cin, infix); // Read the infix expression

string prefix = converter.convertToPrefix(infix); // Convert to prefix


cout << "Prefix expression: " << prefix << endl; // Display prefix
expression

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