0% found this document useful (0 votes)
14 views83 pages

Mayank C

The document contains multiple C++ programming tasks completed by Ninad Gangodkar, including calculating the area of a circle, finding factorials using recursion, creating a bank account class, checking for prime numbers, and more. Each task includes code snippets demonstrating the implementation of the required functionalities. The document showcases a variety of programming concepts such as classes, recursion, and array manipulation.

Uploaded by

tvesag11
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)
14 views83 pages

Mayank C

The document contains multiple C++ programming tasks completed by Ninad Gangodkar, including calculating the area of a circle, finding factorials using recursion, creating a bank account class, checking for prime numbers, and more. Each task includes code snippets demonstrating the implementation of the required functionalities. The document showcases a variety of programming concepts such as classes, recursion, and array manipulation.

Uploaded by

tvesag11
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/ 83

/*

Name : Ninad Gangodkar


Class Roll no. : 46
University Roll no. : 2021334
Q1. Implement a C++ program to calculate the area of a circle given its radius.
*/

#include <iostream>
using namespace std;
const double PI = 3.14159; // Define PI
double calculateArea(double radius)
{
return PI * radius * radius; // Calculate area using formula: PI * r^2
}
int main()
{
double radius;
cout << "Enter the radius of the circle: ";
cin >> radius;
// Check if the radius is non-negative
if (radius >= 0)
{
double area = calculateArea(radius);
cout << "The area of the circle with radius " << radius << " is: " << area << endl;
}
else
{
cout << "Radius should be a non-negative number." << endl;
}
return 0;
}
*****OUTPUT******
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q2. Write a C++ program to find the factorial of a given number using recursion.*/
#include <iostream>
using namespace std;
// Function to calculate factorial using recursion
unsigned long long factorial(int n)
{
if (n == 0 || n == 1)
{
return 1;
}
else
{
return n * factorial(n - 1);
}
}

int main()
{
int number;
cout << "Enter a positive integer to find its factorial: ";
cin >> number;
if (number < 0)
{
cout << "Factorial is not defined for negative numbers." << endl;
}
else
{
unsigned long long fact = factorial(number);
cout << "Factorial of " << number << " = " << fact << endl;
}
return 0;
}
******OUTPUT******
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q3. Create a class in C++ to represent a bank account with methods for deposit and
withdrawal. */
#include <iostream>
using namespace std;
class BankAccount
{
private:
string accountNumber;
string accountHolderName;
double balance;
public:
// Constructor to initialize the account
BankAccount(string accNumber, string accHolderName, double initialBalance)
{
accountNumber = accNumber;
accountHolderName = accHolderName;
balance = initialBalance;
}
// Method to deposit money into the account
void deposit(double amount)
{
if (amount > 0)
{
balance += amount;
cout << "Deposit of $" << amount << " successful." << endl;
}
else
{
cout << "Invalid amount for deposit." << endl;
}
}
// Method to withdraw money from the account
void withdraw(double amount)
{
if (amount > 0 && amount <= balance)
{
balance -= amount;
cout << "Withdrawal of $" << amount << " successful." << endl;
}
else
{
cout << "Invalid amount for withdrawal or insufficient funds." << endl;
}
}
// Method to display account information
void displayAccountInfo()
{
cout << "Account Number: " << accountNumber << endl;
cout << "Account Holder: " << accountHolderName << endl;
cout << "Balance: $" << balance << endl;
}
};

int main()
{
string accNumber, accHolderName;
double initialBalance;
// Get account details from user input
cout << "Enter account number: ";
cin >> accNumber;
cout << "Enter account holder name: ";
cin.ignore(); // Ignore newline character from previous input
getline(cin, accHolderName);
cout << "Enter initial balance: $";
cin >> initialBalance;
// Creating an instance of BankAccount using user-provided details
BankAccount myAccount(accNumber, accHolderName, initialBalance);
// Display initial account information
myAccount.displayAccountInfo();
// Perform transactions based on user input
int choice;
double amount;
do
{
cout << "\nChoose an option:\n1. Deposit\n2. Withdraw\n0. Exit\n";
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter amount to deposit: $";
cin >> amount;
myAccount.deposit(amount);
break;
case 2:
cout << "Enter amount to withdraw: $";
cin >> amount;
myAccount.withdraw(amount);
break;
case 0:
break;
default:
cout << "Invalid choice. Please enter a valid option." << endl;
}
// Display updated account information after each transaction
myAccount.displayAccountInfo();
} while (choice != 0);
return 0;
}
*****OUTPUT****
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q4. Implement a C++ program to check if a given number is prime. */
#include <iostream>
using namespace std;
bool isPrime(int number)
{
if (number <= 1)
{
return false; // Numbers less than or equal to 1 are not prime
}
for (int i = 2; i * i <= number; ++i)
{
if (number % i == 0)
{
return false; // If the number is divisible by any number up to its square root, it's not
prime
}
}
return true; // If no divisors are found, the number is prime
}
int main()
{
int num;
cout << "Enter a number to check if it's prime: ";
cin >> num;
if (isPrime(num))
{
cout << num << " is a prime number." << endl;
}
else
{
cout << num << " is not a prime number." << endl;
}
return 0;
}
****OUTPUT****
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q5. Write a C++ program to find the largest element in an array. */
#include <iostream>
#include <climits> // Include the library for INT_MIN
using namespace std;
int findLargestElement(int arr[], int size)
{
if (size == 0)
{
cout << "Array is empty." << endl;
return INT_MIN;
}
int maxElement = arr[0];
for (int i = 1; i < size; ++i)
{
if (arr[i] > maxElement)
{
maxElement = arr[i];
}
}
return maxElement;
}
int main()
{
int size;
cout << "Enter the size of the array: ";
cin >> size;
int array[size];
cout << "Enter the elements of the array:" << endl;
for (int i = 0; i < size; ++i)
{
cin >> array[i];
}
int largest = findLargestElement(array, size);
if (largest != INT_MIN)
{
cout << "The largest element in the array is: " << largest << endl;
}
return 0;
}
*****OUTPUT*****
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q6. Implement a C++ program to merge two sorted arrays into a single sorted array.*/
#include <iostream>
using namespace std;

void mergeArrays(int arr1[], int size1, int arr2[], int size2, int result[])
{
int i = 0, j = 0, k = 0;

while (i < size1 && j < size2)


{
if (arr1[i] < arr2[j])
result[k++] = arr1[i++];
else
result[k++] = arr2[j++];
}

while (i < size1)


result[k++] = arr1[i++];

while (j < size2)


result[k++] = arr2[j++];
}

int main()
{
int size1, size2;

cout << "Enter the size of the first array: ";


cin >> size1;
int arr1[size1];
cout << "Enter elements of the first array (in sorted order): ";
for (int i = 0; i < size1; i++)
cin >> arr1[i];

cout << "Enter the size of the second array: ";


cin >> size2;
int arr2[size2];
cout << "Enter elements of the second array (in sorted order): ";
for (int i = 0; i < size2; i++)
cin >> arr2[i];

int result[size1 + size2];


mergeArrays(arr1, size1, arr2, size2, result);

cout << "Merged array in sorted order: ";


for (int i = 0; i < size1 + size2; i++)
cout << result[i] << " ";

return 0;
}
********OUTPUT*******
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q7.Implement a C++ program to find the GCD (Greatest Common Divisor) of two
numbers.*/
#include <iostream>
using namespace std;
int gcd(int a, int b)
{
if (b == 0)
{
return a; // GCD is 'a' when 'b' becomes 0
}
return gcd(b, a % b); // Recursively call gcd with 'b' and 'a % b'
}
int main()
{
int num1, num2;
cout << "Enter two numbers to find their GCD: ";
cin >> num1 >> num2;
int result = gcd(num1, num2);
cout << "GCD of " << num1 << " and " << num2 << " is: " << result << endl;
return 0;
}
********OUTPUT*******
/*Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q8.Develop a C++ program to find the second-largest element in an array.*/
#include <iostream>
#include <climits>
using namespace std;
int findSecondLargest(int arr[], int size)
{
int max1 = INT_MIN; // Initialize first maximum to the smallest possible value
int max2 = INT_MIN; // Initialize second maximum to the smallest possible value
for (int i = 0; i < size; ++i)
{
// If current element is greater than first maximum, update both maximums
if (arr[i] > max1)
{
max2 = max1;
max1 = arr[i];
}
// If current element is greater than second maximum but not equal to first maximum,
update second maximum
else if (arr[i] > max2 && arr[i] != max1)
{
max2 = arr[i];
}
}
return max2;
}
int main()
{
int size;
cout << "Enter the size of the array: ";
cin >> size;
int array[size];
cout << "Enter the elements of the array:" << endl;
for (int i = 0; i < size; ++i)
{
cin >> array[i];
}
int secondLargest = findSecondLargest(array, size);
if (secondLargest != INT_MIN)
{
cout << "The second-largest element in the array is: " << secondLargest << endl;
}
else
{
cout << "Unable to find the second-largest element." << endl;
}
return 0;
}
****OUTPUT*****
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q9.Implement a C++ program to find the LCM (Least Common Multiple) of two numbers.*/
#include <iostream>
using namespace std;
// Function to find the Greatest Common Divisor (GCD) using the Euclidean algorithm
int gcd(int a, int b)
{
if (b == 0)
{
return a;
}
return gcd(b, a % b);
}
// Function to find the LCM using the GCD
int lcm(int a, int b)
{
// LCM = (a * b) / GCD(a, b)
return (a * b) / gcd(a, b);
}

int main()
{
int num1, num2;
cout << "Enter two numbers to find their LCM: ";
cin >> num1 >> num2;
int result = lcm(num1, num2);
cout << "LCM of " << num1 << " and " << num2 << " is: " << result << endl;
return 0;
}
*****OUPUT*****
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q10Implement a C++ program to calculate the power of a number using recursion.*/
#include <iostream>
using namespace std;
// Function to calculate power using recursion
double power(double base, int exponent)
{
if (exponent == 0)
{
return 1; // Anything raised to the power of 0 is 1
}
else if (exponent > 0)
{
return base * power(base, exponent - 1); // Recursive call to calculate power
}
else
{
return 1 / power(base, -exponent); // For negative exponents, compute the reciprocal
}
}
int main()
{
double base;
int exponent;
cout << "Enter base: ";
cin >> base;
cout << "Enter exponent: ";
cin >> exponent;
double result = power(base, exponent);
cout << "Result: " << result << endl;
return 0;
}
*****OUPUT*****
/*Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q11. Implement a C++ program to find the non-repeating characters in string.
#include<iostream>
#include<string>
using namespace std;
int main(){
string str;
cout<<"\t\t\tINPUT\n";
cout<<"Enter a string\n";
getline(cin,str);
int n=str.length();
cout<<"\t\t\OUTPUT\n";
for(int i=0;i<n;i++){
int flag=0;
for(int j=0;j<n;j++){
if(i!=j && str[i]==str[j]){
flag=1;
break;
}
}
if(flag==0){
cout<<str[i]<<" ";
}
}
return 0;
}
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q11. Define a class Hotel in C++ with the following specifications Private members • Rno
Data member to store room number • Name Data member to store customer name • Tariff
Data member to store per day charges • NOD Data member to store number of days of stay •
CALC() Function to calculate and return amount as NOD*Tariff ,and if the value of days*
Tariff >10000, then total amount is 1.05* days*Tariff. Public members • Checkin() Function
to enter the content Rno, Name, Tariff and NOD • Checkout() Function to display Rno,
Name, Tariff, NOD and Amount (amount to be displayed by calling function) CALC()*/
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Hotel
{
private:
int Rno, NOD;
string Name;
float Tariff;
float CALC()
{
if ((NOD * Tariff) > 10000)
{
return (1.05 * NOD * Tariff);
}
else
{
return (NOD * Tariff);
}
}

public:
void Checkin()
{
cout << "Enter the room number\n";
cin >> Rno;
cin.ignore();
cout << "Enter the name\n";
getline(cin, Name);
cout << "Enter tariff\n";
cin >> Tariff;
cout << "Enter the number of days\n";
cin >> NOD;
}
void Checkout()
{
cout << left << setw(15) << "Name" << setw(15) << "Room number" << setw(15) <<
"Tariff" << setw(20) << "Number of days"
<< "Amount" << endl;
cout << left << setw(15) << Name << setw(15) << Rno << setw(15) << Tariff <<
setw(20) << NOD << CALC() << endl;
}
};
int main()
{
Hotel h;
cout << "\t\t\tINPUT\n";
h.Checkin();
cout << "\t\t\tOUTPUT\n";
h.Checkout();
return 0;
}
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q13. Create a class called Time that has separate int member data for hours, minutes and
seconds. One constructor should initialize this data to 0, and another should initialize it to
fixed values. A member function should display it in 11:59:59 format. A member function
named add() should add two objects of type time passed as arguments. A main ( ) program
should create two initialized values together, leaving the result in the third time variable.
Finally it should display the value of this third variable.*/

#include <iostream>
using namespace std;

class Time
{
private:
int h;
int min;
int sec;

public:
Time()
{
h = 0;
min = 0;
sec = 0;
}
Time(int ho, int mi, int se)
{
h = ho;
min = mi;
sec = se;
}
void Display()
{
cout << h << ":" << min << ":" << sec << endl;
}
Time add(Time a, Time b)
{
Time ob;
ob.h = a.h + b.h;
ob.min = a.min + b.min;
ob.sec = a.sec + b.sec;
if (ob.min >= 60)
{
ob.h += ob.min / 60;
ob.min %= 60;
}
if (ob.sec >= 60)
{
ob.min += ob.sec / 60;
ob.sec %= 60;
}
return ob;
}
};
int main()
{
int h1, m1, s1, h2, m2, s2;
cout << "Enter hours, minutes, and seconds for Time 1 (separated by spaces): ";
cin >> h1 >> m1 >> s1;
cout << "Enter hours, minutes, and seconds for Time 2 (separated by spaces): ";
cin >> h2 >> m2 >> s2;
Time A(h1, m1, s1), B(h2, m2, s2), C;
cout << "Time of object 1 : ";
A.Display();
cout << "Time of object 2 : ";
B.Display();
C = C.add(A, B);
cout << "Time of object 3 (contains sum of both times) : ";
C.Display();
return 0;
}
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q14. Create a class called Student that contains the data members like age, name, enroll_no,
marks. Create another class called Faculty that contains data members like facultyName,
facultyCode, salary,deptt, age, experience, gender. Create the function display() in both the
classes to display the respective information. The derived Class Person demonstrates multiple
inheritance. The program should be able to call both the base classes and displays their
information. Remove the ambiguity (When we have exactly same variables or same methods
in both the base classes, which one will becalled?) by proper mechanism*/

#include <iostream>
#include <string>
using namespace std;
class Student
{
private:
int age, enroll_no;
float marks;
string name;

public:
void setdata()
{
cout << "Enter Name\n";
getline(cin, name);
cout << "Enter age\n";
cin >> age;
cout << "Enter enroll number\n";
cin >> enroll_no;
cout << "Enter marks\n";
cin >> marks;
cin.ignore();
}
void display()
{
cout << "Name : " << name << ", Age : " << age << ", Enroll Number : " << enroll_no
<< " & Marks : " << marks << endl;
}
};
class Faculty
{
private:
int facultyCode;
float salary;
int age, exp;
string facultyName, deptt;
char gender;

public:
void set_data()
{
cout << "Enter faculty name\n";
getline(cin, facultyName);
cout << "Enter faculty code\n";
cin >> facultyCode;
cout << "Enter department\n";
cin >> deptt;
cout << "Enter age\n";
cin >> age;
cout << "Enter gender(F for female and M for male)\n";
cin >> gender;
cout << "Enter experience(in years)\n";
cin >> exp;
cout << "Enter salary\n";
cin >> salary;
}
void display()
{
cout << "Name : " << facultyName << ", Faculty Code : " << facultyCode << ",
Department : " << deptt << ", Age : " << age << ", Experience(in years) : " << exp << ",
Gender : " << gender << " & Salary : " << salary << endl;
}
};
class Person : public Student, public Faculty
{
public:
void display()
{
Student::display();
Faculty::display();
}
};
int main()
{
Person p;
cout << "\t\t\tINPUT\n";
cout << "Enter data of student\n";
p.setdata();
cout << "Enter data of faculty\n";
p.set_data();
cout << "\t\t\tOUTPUT\n";
p.display();
return 0;
}
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q15 Create a base class called CAL_AREA(Abstract). Use this class to store float type
values that could be used to compute the volume of figures. Derive two specific classes called
cone, hemisphere and cylinder from the base CAL_AREA. Add to the base class, a member
function getdata ( ) to initialize base class data members and another member function
display volume( ) to compute and display the volume of figures. Make display volume ( ) as a
pure virtual function and redefine this function in the derived classes to suit their
requirements. Using these three classes, design a program that will accept dimensions of a
cone, cylinder and hemisphere interactively and display the volumes. Remember values given
as input will be and used as follows: Volume of cone = (1/3)πr2h Volume of hemisphere =
(2/3)πr3 Volume of cylinder = πr2h*/
#include <iostream>
using namespace std;
class CAL_AREA
{
protected:
float r;

public:
void get_data()
{
cout << "Enter the dimensions\n";
cout << "Enter radius\n";
cin >> r;
}
virtual void display_volume() = 0;
};
class Cone : public CAL_AREA
{
public:
float h;
void get_data()
{
CAL_AREA::get_data();
cout << "Enter height :";
cin >> h;
}
void display_volume()
{
float vol = (1.0 / 3) * 3.14 * r * r * h;
cout << "The volume of cone is : " << vol << endl;
}
};
class Cylinder : public CAL_AREA
{
public:
float h;
void get_data()
{
CAL_AREA::get_data();
cout << "Enter height :";
cin >> h;
}
void display_volume()
{
float vol = 3.14 * r * r * h;
cout << "The volume of cylinder is : " << vol << endl;
}
};
class Hemisphere : public CAL_AREA
{
public:
void get_data()
{
CAL_AREA::get_data();
}
void display_volume()
{
float vol = (2.0 / 3) * 3.14 * r * r * r;
cout << "The volume of hemisphere is : " << vol << endl;
}
};
int main()
{
Cone c;
Hemisphere h;
Cylinder cy;
cout << "\t\t\tINPUT\n";
cout << "For Cone :";
c.get_data();
cout << "\t\t\tOUTPUT\n";
c.display_volume();
cout << "\t\t\tINPUT\n";
cout << "For Hemisphere :";
h.get_data();
cout << "\t\t\tOUTPUT\n";
h.display_volume();
cout << "For Cylinder :";
cout << "\t\t\tINPUT\n";
cy.get_data();
cout << "\t\t\tOUTPUT\n";
cy.display_volume();
}
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q16. Using the concept of operator overloading. Implement a program to overload the
following: a. Unary – b. Unary ++ preincrement, postincrement c. Unary -- predecrement,
postdecrement.*/

#include <iostream>
using namespace std;
class Number
{
private:
int value;

public:
Number() : value(0) {}
Number(int val) : value(val) {}
// Unary operator overloading for prefix increment (++)
Number operator++()
{
value++;
return *this;
}
// Unary operator overloading for postfix increment (++)
Number operator++(int)
{
Number temp(value);
value++;
return temp;
}
// Unary operator overloading for prefix decrement (--)
Number operator--()
{
value--;
return *this;
}
// Unary operator overloading for postfix decrement (--)
Number operator--(int)
{
Number temp(value);
value--;
return temp;
}
// Unary operator overloading for negation (-)
Number operator-()
{
return Number(-value);
}
void display()
{
cout << "Value: " << value << endl;
}
};

int main()
{
int initialValue;
cout << "Enter initial value: ";
cin >> initialValue;
Number num(initialValue);
cout << "Original Value: ";
num.display();
++num;
cout << "After pre-increment (++): ";
num.display();
num++;
cout << "After post-increment (++): ";
num.display();
--num;
cout << "After pre-decrement (--): ";
num.display();
num--;
cout << "After post-decrement (--): ";
num.display();
Number negativeNum = -num;
cout << "After negation (-): ";
negativeNum.display();
return 0;
}
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q17. Create a class Complex having two int type variable named real & img denoting real
and imaginary part respectively of a complex number. Overload +, - , = = operator to add, to
subtract and to compare two complex numbers being denoted by the two complex type
objects*/

#include <iostream>
using namespace std;
class Complex
{
private:
int real;
int img;
public:
// Default constructor
Complex() : real(0), img(0) {}

// Parameterized constructor
Complex(int r, int i) : real(r), img(i) {}

// Overloading addition operator (+)


Complex operator+(const Complex &other)
{
Complex result;
result.real = real + other.real;
result.img = img + other.img;
return result;
}

// Overloading subtraction operator (-)


Complex operator-(const Complex &other)
{
Complex result;
result.real = real - other.real;
result.img = img - other.img;
return result;
}

// Overloading equality operator (==)


bool operator==(const Complex &other)
{
return (real == other.real) && (img == other.img);
}
// Display function for Complex numbers
void display()
{
cout << real << " + " << img << "i";
}
};

int main()
{
int real1, img1, real2, img2;
// Input for Complex Number 1
cout << "Enter real and imaginary parts of Complex Number 1: ";
cin >> real1 >> img1;
// Input for Complex Number 2
cout << "Enter real and imaginary parts of Complex Number 2: ";
cin >> real2 >> img2;
// Creating Complex objects
Complex c1(real1, img1);
Complex c2(real2, img2);
Complex c3;
// Displaying Complex Number 1
cout << "Complex Number 1: ";
c1.display();
cout << endl;
// Displaying Complex Number 2
cout << "Complex Number 2: ";
c2.display();
cout << endl;
// Addition operation and display result
c3 = c1 + c2;
cout << "Addition Result: ";
c3.display();
cout << endl;
// Subtraction operation and display result
c3 = c1 - c2;
cout << "Subtraction Result: ";
c3.display();
cout << endl;
// Equality comparison and display result
if (c1 == c2)
{
cout << "Complex Number 1 is equal to Complex Number 2." << endl;
}
else
{
cout << "Complex Number 1 is not equal to Complex Number 2." << endl;
}
return 0;
}
***** OUTPUT******
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q18. Imagine a tollbooth with a class called TollBooth. The two data items are of type
unsigned int and double to hold the total number of cars and total amount of money collected.
A constructor initializes both of these data members to 0. A member function called
payingCar( )increments the car total and adds 0.5 to the cash total. Another function called
nonPayCar( ) increments the car total but adds nothing to the cash total. Finally a member
function called display( )shows the two totals. Include a program to test this class. This
program should allow the user to push one key to count a paying car and another to count a
non paying car. Pushing the ESC key should cause the program to print out the total number
of cars and total cash and then exit.*/

#include <iostream>
#include <conio.h>
using namespace std;
class TollBooth
{
private:
unsigned int totalCars;
double totalCash;

public:
TollBooth() : totalCars(0), totalCash(0.0) {}
void payingCar()
{
totalCars++;
totalCash += 0.5;
}
void nonPayCar()
{
totalCars++;
}
void display()
{
cout << "Total Cars: " << totalCars << "\nTotal Cash: Rs " << totalCash << "\n";
}
};
int main()
{
TollBooth toll;
char key;
cout << "\t\t\tINPUT\n";
do
{
cout << "Press 'P' to count a paying car, 'N' to count a non-paying car, or 'ESC' to exit.\
n";
key = _getch();
switch (key)
{
case 'P':
case 'p':
toll.payingCar();
cout << "Paying car counted.\n";
break;
case 'N':
case 'n':
toll.nonPayCar();
cout << "Non-paying car counted.\n";
break;
case 27:
cout << "Exiting program.\n";
break;
default:
cout << "Invalid key. Try again.\n";
}
} while (key != 27);
cout << "\t\t\tOUTPUT\n";
toll.display();
return 0;
}
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q19. Write a C++ program to compare Father Name, Mother Name of both classes using
friend function. If Father name and Mother Name of both classes are equal then print the
message “Belongs to Same Family” and display message “We are Brothers” or “We are
Sisters” or “We are brother and sister”, otherwise print the message “Belongs to different
Family”.*/

#include <iostream>
#include <string>
using namespace std;
class UserTwo;
class UserOne
{
private:
string Name;
string FatherName;
string MotherName;
char Gender;

public:
void InputInfo()
{
cout << "Enter name\n";
getline(cin, Name);
cout << "Enter father name\n";
getline(cin, FatherName);
cout << "Enter mothername\n";
getline(cin, MotherName);
cout << "Enter Gender : 'M' for male and 'F' for female\n";
cin >> Gender;
cin.ignore();
}
friend void Userchecker(UserOne, UserTwo);
};
class UserTwo
{
private:
string Name;
string FatherName;
string MotherName;
char Gender;

public:
void InputInfo()
{
cout << "Enter name\n";
getline(cin, Name);
cout << "Enter father name\n";
getline(cin, FatherName);
cout << "Enter mothername\n";
getline(cin, MotherName);
cout << "Enter Gender : 'M' for male and 'F' for female\n";
cin >> Gender;
cin.ignore();
}
friend void Userchecker(UserOne, UserTwo);
};

void Userchecker(UserOne a, UserTwo b)


{
if (a.FatherName == b.FatherName && a.MotherName == b.MotherName)
{
cout << "Belongs to same family\n";
if (a.Gender == 'M' && b.Gender == 'M')
{
cout << "We are brothers\n";
}
else if (a.Gender == 'F' && b.Gender == 'F')
{
cout << "We are sisters\n";
}
else
{
cout << "We are brother and sister\n";
}
}
else
{
cout << "Belongs to different family\n";
}
}
int main()
{
cout << "\t\t\tINPUT\n";
UserOne A;
UserTwo B;
A.InputInfo();
B.InputInfo();
cout << "\t\t\tOUTPUT\n";
Userchecker(A, B);
return 0;
}
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q20. Create a class MyCalculator which consists of a single method power(int, int). This
method takes two integers, n and p, as parameters and finds n p . If either n or p is negative,
then the method must throw an exception which says "n and p should be nonnegative". Input
Format: Each line of the input contains two integers, n and p . Output Format: Each line of
the output contains the result ,if neither of n and p is negative. Otherwise the output contains
"n and p should be non-negative".*/

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

class MyCalculator
{
public:
int power(int n, int p)
{
if (n < 0 || p < 0)
{
throw invalid_argument("n and p should be non-negative");
}
else if (n == 0 && p == 0)
{
throw invalid_argument("n and p should not be zero");
}
else
{
int result = 1;
for (int i = 0; i < p; ++i)
{
result *= n;
}
return result;
}
}
};

int main()
{
MyCalculator myCalc;
int n, p;
cout << "Read the input till EOF" << endl;
// Input
while (cin >> n >> p)
{
try
{
int result = myCalc.power(n, p);
cout << result << endl;
}
catch (const invalid_argument &e)
{
cout << "C++Exception: " << e.what() << endl;
}
}

return 0;
}
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q21.Create class SavingsAccount. Use a static variable annualInterestRate to store the annual
interest rate for all account holders. Each object of the class contains a private instance
variable savingsBalance indicating the amount the saver currently has on deposit. Provide
method calculateMonthlyInterest() to calculate the monthly interest by multiplying the
savingsBalance by annualInterestRate divided by 12.This interest should be added
tosavingsBalance. Provide a static method modifyInterestRate() that sets the
annualInterestRate to a new value. Write a program to test class SavingsAccount. Instantiate
two savingsAccount objects, saver1 and saver2, with balances of Rs2000.00 and Rs3000.00,
respectively. Set annualInterestRate to 4%, then calculate the monthly interest and print the
new balances for both savers. Then set the annualInterestRate to 5%, calculate the next
month’s interest and print the new balances for both savers.*/

#include <iostream>
using namespace std;

class SavingsAccount
{
private:
static double annualInterestRate;
double savingsBalance;

public:
SavingsAccount(double balance) : savingsBalance(balance) {}

void calculateMonthlyInterest()
{
double monthlyInterest = (savingsBalance * annualInterestRate) / 12;
savingsBalance += monthlyInterest;
}

static void modifyInterestRate(double newRate)


{
annualInterestRate = newRate;
}

double getBalance() const


{
return savingsBalance;
}
};

double SavingsAccount::annualInterestRate = 0.0;

int main()
{
double balance1, balance2;
cout << "Enter the initial balance for saver 1: Rs";
cin >> balance1;
cout << "Enter the initial balance for saver 2: Rs";
cin >> balance2;

SavingsAccount saver1(balance1);
SavingsAccount saver2(balance2);

double interestRate;
cout << "Enter the annual interest rate in decimal (for example, 0.04 for 4%): ";
cin >> interestRate;

SavingsAccount::modifyInterestRate(interestRate);

saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
cout << "\nNext month's balances with " << (interestRate * 100) << "% annual interest
rate:" << endl;
cout << "Saver 1: Rs" << saver1.getBalance() << endl;
cout << "Saver 2: Rs" << saver2.getBalance() << endl;

return 0;
}
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q22. An electricity board charges the following rates to domestic users to discourage large
consumption of energy. For the first 100 units: - 60 P per unit For the next 200 units: -80 P
per unit Beyond 300 units: -90 P per unit All users are charged a minimum of Rs 50 if the
total amount is more than Rs 300 then an additional surcharge of 15% is added. Implement a
C++ program to read the names of users and number of units consumed and display the
charges with names. */
#include <iostream>
#include <string>
using namespace std;
int main()
{
float first_100 = 0.60;
float next_200 = 0.80;
float beyond_300 = 0.90;
float min_charge = 50;
float surcharge_rate = 0.15;
int n;
cout << "\t\t\t\t\tINPUT\n";
cout << "Enter the number of users\n";
cin >> n;
float unit[n], charge[n];
string name[n];
for (int i = 0; i < n; i++)
{
cout << "Enter name of user " << i + 1 << "\n";
cin >> name[i];
cout << "Enter the number of units user by user " << i + 1 << "\n";
cin >> unit[i];
if (unit[i] <= 100)
{
charge[i] = (unit[i] * first_100);
}
else if (unit[i] <= 300)
{
charge[i] = (100 * first_100 + (unit[i] - 100) * next_200);
}
else
{
charge[i] = (100 * first_100 + 200 * next_200 + (unit[i] - 300) * beyond_300);
}
if (charge[i] < min_charge)
{
charge[i] = min_charge;
}
if (charge[i] > 300)
{
charge[i] += charge[i] * surcharge_rate;
}
}
cout << "\t\t\t\t\tOUTPUT\n";
for (int i = 0; i < n; i++)
{
cout << "Name : " << name[i] << ", Units consumed : " << unit[i] << ", Charge : Rs" <<
charge[i] << endl;
}
return 0;
}
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q23. Printing an array into Zigzag fashion. Suppose you were given an array of integers, and
you are told to sort the integers in a zigzag pattern. In general, in a zigzag pattern, the first
integer is less than the second integer, which is greater than the third integer, which is less
than the fourth integer, and so on. Hence, the converted array should be in the form of e1 < e2
> e3 < e4 > e5 < e6. Test cases: Input 1: 7 4 3 7 8 6 2 1 Output 1: 3 7 4 8 2 6 1 Input 2: 4 1 4
3 2 Output 2: 1 4 2 3 */

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void zigzagSort(vector<int> &arr)


{
int n = arr.size();
bool less = true; // Flag to indicate the current pattern

for (int i = 0; i < n - 1; ++i)


{
if (less)
{
// If current pattern is 'less than'
if (arr[i] > arr[i + 1])
{
swap(arr[i], arr[i + 1]);
}
}
else
{
// If current pattern is 'greater than'
if (arr[i] < arr[i + 1])
{
swap(arr[i], arr[i + 1]);
}
}
less = !less; // Change pattern for the next pair
}
}

int main()
{
int n;
cout << "Enter the number of elements: ";
cin >> n;

vector<int> arr(n);
cout << "Enter the elements: ";
for (int i = 0; i < n; ++i)
{
cin >> arr[i];
}

zigzagSort(arr);

cout << "Array in Zigzag pattern: ";


for (int i = 0; i < n; ++i)
{
cout << arr[i] << " ";
}
cout << endl;

return 0;}
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q24. Create a base class called shape. Use this class to store two double type values that
could be used to compute the area of figures. Derive two specific classes called triangle and
rectangle from base shape. Add to the base class, a member function get_data() to initialize
base class data members and another member function display_area() to compute and display
the area of figures. Make display_area() as a virtual function and redefine this function in the
derived class to suit their requirements. Using these three classes, design a program that will
accept dimensions of a triangle or a rectangle interactively and display the area. Remember
the two values given as input will be treated as lengths of two sides in the case of rectangles
and as base and height in the case of triangle and used as follows: Area of rectangle = x * y
Area of triangle = ½ *x*y*/
#include <iostream>
using namespace std;
class shape
{
protected:
double a, b;

public:
void get_data()
{
cout << "Enter dimensions\n";
cout << "Enter a\n";
cin >> a;
cout << "Enter b\n";
cin >> b;
}
virtual void display_area() {}
};
class triangle : public shape
{
public:
void display_area()
{
double area = 0.5 * a * b;
cout << "The area of the traingle is " << area << endl;
}
};
class rectangle : public shape
{
public:
void display_area()
{
double area = a * b;
cout << "The area of the rectangle is " << area << endl;
}
};
int main()
{
shape *s;
triangle t;
rectangle r;
cout << "\t\t\tINPUT\n";
cout << "For Triangle :";
s = &t;
s->get_data();
s->display_area();
s = &r;
cout << "For Rectangle :";
s->get_data();
cout << "\t\t\tOUTPUT\n";

s->display_area();
return 0;
}
/*
Name : Ninad Gangodkar
Class Roll no. : 46
University Roll no. : 2021334
Q25*/

#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Animal is eating"<<endl;
}
};
class Mammal:public virtual Animal{
public:
void giveBirth(){
cout<<"Mammal is giving birth"<<endl;
}
};
class Bird:public virtual Animal{
public:
void layEggs(){
cout<<"Bird is laying eggs"<<endl;
}
};
class Platypus:public Mammal,public Bird{
public:
void swim(){
cout<<"Platypus is swimming"<<endl;
}
};
int main(){
Platypus p;
p.eat();
p.giveBirth();
p.layEggs();
p.swim();
return 0;
}

You might also like