1.
/* C++ Program for Rational Operations using Operator Overloading */
#include<stdio.h>
#include<iostream>
using namespace std;
class rational
int numer;
int denom;
public:
void getdata()
cout<<"\n enter the numerator part of the rational no. :: ";
cin>>numer;
cout<<"\n enter the denominator part of the rational no. :: ";
cin>>denom;
void operator+(rational);
void operator-(rational);
void operator *(rational);
void operator /(rational);
};
void rational ::operator+(rational c1)
rational temp;
[Link]=(numer*[Link])+([Link]*denom);
[Link]=denom*[Link];
cout<<"\nrational no. after addition :: ";
cout<<"\n numerator = "<<[Link]<<"\n denominator = "<<[Link];
void rational ::operator -(rational c1)
{
rational temp;
[Link]=(numer*[Link])-([Link]*denom);
[Link]=denom*[Link];
cout<<"\n rational no. after subtraction :: ";
cout<<"\n numerator = " <<[Link]<<"\n denominator = "<<[Link];
void rational ::operator *(rational c1)
rational temp;
[Link]=numer*[Link];
[Link]=denom*[Link];
cout<<"\n rational no. after multiplication :: ";
cout <<"\n numerator = "<<[Link]<<"\n denominator = "<< [Link];
void rational :: operator /(rational c1)
rational temp;
[Link]= numer*[Link];
[Link]=[Link]*denom;
cout<<"\n rational no. after dividation :: ";
cout <<"\n numerator = "<<[Link]<<"\n denominator = "<<[Link];
int main()
rational c1, c2;
int n;
do
cout<<"\n\n [Link] data for rational no. ";
cout<<"\n 2. Addition of rational no. ";
cout<<"\n 3. Subtraction of rational no. ";
cout<<"\n 4. Multiplication of rational no.";
cout<<"\n 5. Division of rational no. ";
cout<<"\n 6. Quit";
cout<<"\n\n Enter your choice :: ";
cin>>n;
switch(n)
case 1:
cout<<endl<<"\n enter the data for first rational no.:: ";
[Link]();
cout<<endl<<"\n enter the data for second rational no. :: ";
[Link] ();
break;
case 2:
c1+c2;
break;
case 3:
c1-c2;
break;
case 4:
c1*c2;
break;
case 5:
c1/c2;
break;
case 6:
exit(1);
break;
} while (n!=6);
return 0;
Output:
[Link] data for rational no.
2. Addition of rational no.
3. Subtraction of rational no.
4. Multiplication of rational no.
5. Division of rational no.
6. Quit
Enter your choice :: 1
enter the data for first rational no.::
enter the numerator part of the rational no. :: 4
enter the denominator part of the rational no. :: 5
enter the data for second rational no. ::
enter the numerator part of the rational no. :: 2
enter the denominator part of the rational no. :: 3
[Link] data for rational no.
2. Addition of rational no.
3. Subtraction of rational no.
4. Multiplication of rational no.
5. Division of rational no.
6. Quit
Enter your choice :: 2
rational no. after addition ::
numerator = 22
denominator = 15
[Link] data for rational no.
2. Addition of rational no.
3. Subtraction of rational no.
4. Multiplication of rational no.
5. Division of rational no.
6. Quit
Enter your choice :: 3
rational no. after subtraction ::
numerator = 2
denominator = 15
[Link] data for rational no.
2. Addition of rational no.
3. Subtraction of rational no.
4. Multiplication of rational no.
5. Division of rational no.
6. Quit
Enter your choice :: 4
rational no. after multiplication ::
numerator = 8
denominator = 15
[Link] data for rational no.
2. Addition of rational no.
3. Subtraction of rational no.
4. Multiplication of rational no.
5. Division of rational no.
6. Quit
Enter your choice :: 5
rational no. after dividation ::
numerator = 12
denominator = 10
[Link] data for rational no.
2. Addition of rational no.
3. Subtraction of rational no.
4. Multiplication of rational no.
5. Division of rational no.
6. Quit
Enter your choice :: 6
[Link] credit card transactions (use inheritance).
#include <iostream>
#include <string>
// Base class representing a credit card
class CreditCard {
protected:
std::string cardNumber;
std::string cardHolderName;
double balance;
public:
CreditCard(const std::string& number, const std::string& name)
: cardNumber(number), cardHolderName(name), balance(0.0) {}
virtual void makePurchase(double amount) {
balance += amount;
std::cout << "Purchase of $" << amount << " made with card ending in " <<
[Link]([Link]() - 4) << std::endl;
void displayBalance() {
std::cout << "Card ending in " << [Link]([Link]() - 4) << " has a balance
of $" << balance << std::endl;
};
// Derived class for a premium credit card with additional rewards
class PremiumCreditCard : public CreditCard {
public:
PremiumCreditCard(const std::string& number, const std::string& name)
: CreditCard(number, name) {}
void makePurchase(double amount) override {
double rewardsPoints = amount * 0.02; // Earn 2% of purchase amount as rewards
balance += amount;
std::cout << "Purchase of $" << amount << " made with premium card ending in " <<
[Link]([Link]() - 4) << std::endl;
std::cout << "Earned " << rewardsPoints << " rewards points!" << std::endl;
};
int main() {
// Create an instance of the base CreditCard class
CreditCard card1("1234 5678 9012 3456", "John Doe");
[Link](100.0);
[Link]();
// Create an instance of the derived PremiumCreditCard class
PremiumCreditCard card2("9876 5432 1098 7654", "Jane Smith");
[Link](200.0);
[Link]();
return 0;
/*Ouput
Purchase of $100 made with card ending in 3456
Card ending in 3456 has a balance of $100
Purchase of $200 made with premium card ending in 7654
Earned 4 rewards points!
Card ending in 7654 has a balance of $200 */
[Link] polymorphism using shape objects in c++
#include <iostream>
// Base class representing a shape
class Shape {
public:
virtual double getArea() const = 0; // Pure virtual function
virtual void printInfo() const {
std::cout << "This is a generic shape." << std::endl;
};
// Derived class representing a rectangle
class Rectangle : public Shape {
private:
double length;
double width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
double getArea() const override {
return length * width;
void printInfo() const override {
std::cout << "This is a rectangle with length " << length << " and width " << width << "." <<
std::endl;
};
// Derived class representing a circle
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double getArea() const override {
return 3.14159 * radius * radius;
void printInfo() const override {
std::cout << "This is a circle with radius " << radius << "." << std::endl;
};
int main() {
Rectangle rectangle(5.0, 3.0);
Circle circle(2.5);
Shape* shapePtr = nullptr; // Base class pointer
shapePtr = &rectangle; // Pointing to a rectangle object
shapePtr->printInfo();
std::cout << "Area: " << shapePtr->getArea() << std::endl;
shapePtr = &circle; // Pointing to a circle object
shapePtr->printInfo();
std::cout << "Area: " << shapePtr->getArea() << std::endl;
return 0;
/*
Ouput:
This is a rectangle with length 5 and width 3.
Area: 15
This is a circle with radius 2.5.
Area: 19.6349 */
Cycle-2
[Link] all prime numbers in an interval
lower = 2
upper = 100
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
output:
Prime numbers between 2 and 100 are:
3
5
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
[Link] for array rotation
# Python program using the List
# slicing approach to rotate the array
def rotateList(arr,d,n):
arr[:]=arr[d:n]+arr[0:d]
return arr
# Driver function to test above function
arr = [1, 2, 3, 4, 5, 6]
print(arr)
print("Rotated list is")
print(rotateList(arr,3,len(arr)))
output:
[1, 2, 3, 4, 5, 6]
Rotated list is
[4, 5, 6, 1, 2, 3]
[Link] to split the array and add the first part to the end.
def splitArr(a, n, k):
b = a[:k]
return (a[k::]+b[::])
# main
arr = [12, 10, 5, 6, 52, 36]
n = len(arr)
position = 3
arr = splitArr(arr, n, position)
for i in range(0, n):
print(arr[i], end=' ')
output:
6 52 36 12 10 5
[Link] to find second largest number in a list.
list_val = [20, 30, 40, 25, 10]
# sorting the list
list_val.sort()
#displaying the second last element of the list
print("The second largest element of the list is:", list_val[-2])
output:
The second largest element of the list is: 30
[Link] to multiply two matrices
def matrix_multiply(matrix1, matrix2):
rows1 = len(matrix1)
cols1 = len(matrix1[0])
rows2 = len(matrix2)
cols2 = len(matrix2[0])
if cols1 != rows2:
print("Error: Number of columns in the first matrix must be equal to the number of rows in the
second matrix.")
return None
result = [[0] * cols2 for _ in range(rows1)]
for i in range(rows1):
for j in range(cols2):
for k in range(cols1):
result[i][j] += matrix1[i][k] * matrix2[k][j]
return result
# Example matrices
matrix1 = [[1, 2, 3], [4, 5, 6]]
matrix2 = [[7, 8], [9, 10], [11, 12]]
# Multiply the matrices
result = matrix_multiply(matrix1, matrix2)
# Print the result
if result is not None:
print("Matrix multiplication result:")
for row in result:
print(row)
Output:
Matrix multiplication result:
[58, 64]
[139, 154]
Cycle-3:
[Link] if a substring is present in a given string
MyString1 = "Keerthi is studying MCA Second Sem in RVR"
if "MCA" in MyString1:
print("Yes! it is present in the string")
else:
print("No! it is not present")
output:
Yes! it is present in the string
[Link] duplicate occurrence in string.
def replace_duplicates(string):
char_count = {}
result = ""
for char in string:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
for char in string:
if char_count[char] > 1:
result += "*"
else:
result += char
return result
# Example usage
input_string = "Hello, World!"
result_string = replace_duplicates(input_string)
print(result_string)
output:
He***, W*r*d!
[Link] anagrams together in python using list and dictionary.
def print_anagrams_together(words):
anagram_dict = {}
for word in words:
sorted_word = "".join(sorted(word)) # Sort the characters of the word
if sorted_word in anagram_dict:
anagram_dict[sorted_word].append(word) # Add the word to the existing list of anagrams
else:
anagram_dict[sorted_word] = [word] # Create a new list of anagrams for the sorted word
for key in anagram_dict:
print(anagram_dict[key])
# Example usage
word_list = ['cat', 'dog', 'tac', 'god', 'act', 'good']
print_anagrams_together(word_list)
Output:
['cat', 'tac', 'act']
['dog', 'god']
['good']
[Link] the frequencies in a list using dictionary in python.
def count_frequencies(lst):
freq_dict = {}
for element in lst:
if element in freq_dict:
freq_dict[element] += 1
else:
freq_dict[element] = 1
return freq_dict
# Example usage
my_list = [1, 2, 3, 2, 1, 3, 3, 4, 5, 4, 4, 4]
frequency_dict = count_frequencies(my_list)
print(frequency_dict)
Output:
{1: 2, 2: 2, 3: 3, 4: 4, 5: 1}
[Link] Tuples if similar initial element.
def join_tuples(tuples):
result = []
tuples_dict = {}
for t in tuples:
key = t[0]
if key in tuples_dict:
tuples_dict[key] += t[1:]
else:
tuples_dict[key] = list(t[1:])
for key in tuples_dict:
[Link]((key, ) + tuple(tuples_dict[key]))
return result
# Example usage
tuples_list = [(1, 'apple'), (2, 'banana'), (1, 'orange'), (3, 'mango'), (2, 'grape')]
joined_tuples = join_tuples(tuples_list)
print(joined_tuples)
Output:
[(1, 'apple', 'orange'), (2, 'banana', 'grape'), (3, 'mango')]
[Link] digits from Tuple list.
def extract_digits(tuples):
digits = []
for t in tuples:
for element in t:
if isinstance(element, int):
[Link](element)
return digits
# Example usage
tuples_list = [('apple', 1, 'orange'), (2, 'banana', 3), (4, 5, 'grape')]
digit_list = extract_digits(tuples_list)
print(digit_list)
Output:
[1, 2, 3, 4, 5]
[Link] number of characters, words, spaces and lines in a file.
def count_file_statistics(filename):
num_chars = 0
num_words = 0
num_spaces = 0
num_lines = 0
with open(filename, 'r') as file:
for line in file:
num_chars += len(line)
num_words += len([Link]())
num_spaces += [Link](' ')
num_lines += 1
return num_chars, num_words, num_spaces, num_lines
# Example usage
filename = '[Link]' # Replace with the actual filename
char_count, word_count, space_count, line_count = count_file_statistics(filename)
print("Character count:", char_count)
print("Word count:", word_count)
print("Space count:", space_count)
print("Line count:", line_count)
[Link] for Sieve of Eratosthenes.
def sieve_of_eratosthenes(n):
# Create a boolean array "is_prime[0..n]" and initialize
# all entries it as true. A value in is_prime[i] will
# finally be false if i is Not a prime, else true.
is_prime = [True] * (n + 1)
primes = []
p=2
while p * p <= n:
# If is_prime[p] is not changed, then it is a prime
if is_prime[p] == True:
# Update all multiples of p
for i in range(p * p, n + 1, p):
is_prime[i] = False
p += 1
# Append all prime numbers to the 'primes' list
for p in range(2, n + 1):
if is_prime[p]:
[Link](p)
return primes
# Example usage
limit = 30
prime_numbers = sieve_of_eratosthenes(limit)
print("Prime numbers up to", limit, ":")
print(prime_numbers)
Output:
Prime numbers up to 30 :
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]