PRACTICAL LIST
PROGRAMMING USING C++
Jatin Kumar, 25749 Chirag Gautam,25733
//1. Write a program to compute the sum of the first n terms
of the following series:
The number of terms n will be taken from the user through
the command line. If the command line argument is not
found then prompt the user to enter the value of n.
#include <iostream>
#include <cmath> // for pow()
using namespace std;
int main(int argc, char* argv[]) {
int n;
// Check if command-line argument is given
if (argc >= 2) {
n = 0;
// Manually convert string to int (basic way)
for (int i = 0; argv[1][i] != '\0'; i++) {
if (argv[1][i] >= '0' && argv[1][i] <= '9') {
n = n * 10 + (argv[1][i] - '0');
} else {
cout << "Invalid input. Please enter a valid
number.\n";
return 1;
}
}
} else {
cout << "Enter the number of terms (n): ";
cin >> n;
}
double sum = 0.0;
for (int i = 1; i <= n; i++) {
double term = 1.0 / pow(i, i);
// Alternate signs
if (i % 2 == 0)
sum -= term;
else
sum += term;
}
cout << "Sum of the series up to " << n << " terms is: " <<
sum << endl;
return 0;
}
//Q2.Write a program to remove the duplicates from an
array
#include <iostream>
using namespace std;
int removeDuplicates(int arr[], int size) {
int temp[100]; // Temporary array to store unique elements
int newSize = 0;
for (int i = 0; i < size; i++) {
bool isDuplicate = false;
// Check if arr[i] already exists in temp[]
for (int j = 0; j < newSize; j++) {
if (arr[i] == temp[j]) {
isDuplicate = true;
break;
}
}
// If not a duplicate, add to temp[]
if (!isDuplicate) {
temp[newSize] = arr[i];
newSize++;
}
}
// Copy unique elements back to original array
for (int i = 0; i < newSize; i++) {
arr[i] = temp[i];
}
return newSize;
}
int main() {
int arr[100], size;
cout << "Enter the number of elements: ";
cin >> size;
cout << "Enter the elements:\n";
for (int i = 0; i < size; i++) {
cin >> arr[i];
}
size = removeDuplicates(arr, size);
cout << "Array after removing duplicates:\n";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
//3. Write a program that prints a table indicating the
number of occurrences of each alphabet in the text entered
as command line arguments.
#include <iostream>
using namespace std;
int main() {
char text[1000];
int count[26] = {0};
cout << "Enter a line of text: ";
cin.getline(text, 1000);
for (int i = 0; text[i] != '\0'; i++) {
char ch = text[i];
// Convert uppercase to lowercase manually
if (ch >= 'A' && ch <= 'Z') {
ch = ch + 32;
}
// Count only lowercase letters
if (ch >= 'a' && ch <= 'z') {
count[ch - 'a']++;
}
}
cout << "\nLetter Count:\n";
for (int i = 0; i < 26; i++) {
if (count[i] > 0) {
cout << (char)(i + 'a') << " : " << count[i] << endl;
}
}
return 0;
}
//4. Write a menu-driven program to perform string
manipulation (without using built-in string functions):
a. Print the address of each character in the input string
b. Concatenate two strings.
c. Compare two strings.
d. Calculate the length of the input string (using pointers).
e. Convert all lowercase characters in a string to
uppercase.
f. Reverse the input string.
g. Insert a string in another string at the position specified
by a user.
#include <iostream>
using namespace std;
// Function to show index and address of each character in the
string
void showAddresses(char* str) {
for (int i = 0; str[i] != '\0'; ++i) {
cout << "Index: " << i << " | Character: " << str[i] << " |
Address: " << (void*)&str[i] << endl;
}
}
// Function to concatenate two strings
void concatenateStrings(char* str1, char* str2) {
int i = 0, j = 0;
// Move to the end of the first string
while (str1[i] != '\0') {
i++;
}
// Append the second string to the first string
while (str2[j] != '\0') {
str1[i] = str2[j];
i++;
j++;
}
str1[i] = '\0'; // Null-terminate the concatenated string
}
// Function to compare two strings
int compareStrings(char* str1, char* str2) {
int i = 0;
while (str1[i] != '\0' && str2[i] != '\0') {
if (str1[i] != str2[i]) {
return str1[i] - str2[i]; // Return the difference
}
i++;
}
return str1[i] - str2[i]; // Return the difference for unequal
length strings
}
// Function to calculate the length of the string using pointers
int calculateLength(char* str) {
int length = 0;
while (*str != '\0') {
length++;
str++;
}
return length;
}
// Function to convert all lowercase characters to uppercase
void toUpperCase(char* str) {
while (*str != '\0') {
if (*str >= 'a' && *str <= 'z') {
*str = *str - 32; // Convert to uppercase
}
str++;
}
}
// Function to reverse the string
void reverseString(char* str) {
int length = calculateLength(str);
char temp;
for (int i = 0; i < length / 2; i++) {
temp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = temp;
}
}
// Function to insert a string in another string at a specified
position
void insertString(char* str1, char* str2, int position) {
int i = calculateLength(str1);
int j = 0;
// Move all characters of str1 from position to the right
for (int k = i; k >= position; k--) {
str1[k + calculateLength(str2)] = str1[k];
}
// Insert str2 at the specified position
while (str2[j] != '\0') {
str1[position + j] = str2[j];
j++;
}
str1[i + calculateLength(str2)] = '\0'; // Null-terminate the
modified string
}
int main() {
int choice;
char str1[100], str2[100];
int position;
while (true) {
cout << "\nMenu:\n";
cout << "1. Show index and address of each character in
string\n";
cout << "2. Concatenate two strings\n";
cout << "3. Compare two strings\n";
cout << "4. Calculate length of the string\n";
cout << "5. Convert all lowercase characters to
uppercase\n";
cout << "6. Reverse the string\n";
cout << "7. Insert a string in another string at a specified
position\n";
cout << "8. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter a string: ";
cin >> str1;
showAddresses(str1);
break;
case 2:
cout << "Enter first string: ";
cin >> str1;
cout << "Enter second string: ";
cin >> str2;
concatenateStrings(str1, str2);
cout << "Concatenated string: " << str1 << endl;
break;
case 3:
cout << "Enter first string: ";
cin >> str1;
cout << "Enter second string: ";
cin >> str2;
int resultCompare;
resultCompare = compareStrings(str1, str2);
if (resultCompare == 0) {
cout << "Strings are equal.\n";
} else if (resultCompare < 0) {
cout << "First string is less than second string.\n";
} else {
cout << "First string is greater than second
string.\n";
}
break;
case 4:
cout << "Enter a string: ";
cin >> str1;
cout << "Length of the string: " <<
calculateLength(str1) << endl;
break;
case 5:
cout << "Enter a string: ";
cin >> str1;
toUpperCase(str1);
cout << "String in uppercase: " << str1 << endl;
break;
case 6:
cout << "Enter a string: ";
cin >> str1;
reverseString(str1);
cout << "Reversed string: " << str1 << endl;
break;
case 7:
cout << "Enter the first string: ";
cin >> str1;
cout << "Enter the second string: ";
cin >> str2;
cout << "Enter the position where you want to insert
the second string: ";
cin >> position;
insertString(str1, str2, position);
cout << "Modified string: " << str1 << endl;
break;
case 8:
cout << "Exiting program.\n";
return 0;
default:
cout << "Invalid choice. Please try again.\n";
}
}
return 0;
}
//5. Write a program to merge two ordered arrays to get a
single ordered array.
#include <iostream>
using namespace std;
int main() {
int a[100], b[100], merged[200];
int n1, n2, i, j, k;
// Input for first sorted array
cout << "Enter size of first sorted array: ";
cin >> n1;
cout << "Enter elements of first sorted array (in order):\n";
for (i = 0; i < n1; i++) {
cin >> a[i];
}
// Input for second sorted array
cout << "Enter size of second sorted array: ";
cin >> n2;
cout << "Enter elements of second sorted array (in order):\n";
for (i = 0; i < n2; i++) {
cin >> b[i];
}
// Merge the two arrays
i = 0; j = 0; k = 0;
while (i < n1 && j < n2) {
if (a[i] < b[j]) {
merged[k++] = a[i++];
} else {
merged[k++] = b[j++];
}
}
// Copy remaining elements
while (i < n1) {
merged[k++] = a[i++];
}
while (j < n2) {
merged[k++] = b[j++];
}
// Output the merged sorted array
cout << "Merged sorted array:\n";
for (i = 0; i < k; i++) {
cout << merged[i] << " ";
}
cout << endl;
return 0;
}
//6. Write a program to search a given element in a set of N
numbers.
#include <iostream>
using namespace std;
int main() {
int arr[100], n, key, i;
bool found = false;
cout << "Enter the number of elements: ";
cin >> n;
cout << "Enter " << n << " numbers:\n";
for (i = 0; i < n; i++) {
cin >> arr[i];
}
cout << "Enter the number to search: ";
cin >> key;
for (i = 0; i < n; i++) {
if (arr[i] == key) {
found = true;
break;
}
}
if (found) {
cout << "Element " << key << " found at position " << i + 1
<< "." << endl;
} else {
cout << "Element " << key << " not found in the set." <<
endl;
}
return 0;
}
//7. Write a program to calculate the GCD of two numbers.
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
int x = a, y = b;
// Euclidean algorithm
while (y != 0) {
int temp = y;
y = x % y;
x = temp;
}
cout << "GCD of " << a << " and " << b << " is: " << x <<
endl;
return 0;
}
//8. Create a Matrix class. Write a menu-driven program to
perform following Matrix operations (exceptions should be
thrown by the functions if matrices passed to them are
incompatible and handled by the main() function):
a. Sum
b. Product
c. Transpose
#include <iostream>
#include <stdexcept>
using namespace std;
class Matrix {
private:
int rows, cols;
int** mat;
public:
// Constructor to initialize the matrix
Matrix(int r, int c) {
rows = r;
cols = c;
mat = new int*[rows];
for (int i = 0; i < rows; i++) {
mat[i] = new int[cols];
}
}
// Destructor to release memory
~Matrix() {
for (int i = 0; i < rows; i++) {
delete[] mat[i];
}
delete[] mat;
}
// Input matrix values with a more clear format
void input() {
cout << "Enter matrix elements row by row, separated by
spaces:\n";
for (int i = 0; i < rows; i++) {
cout << "Row " << i + 1 << ": ";
for (int j = 0; j < cols; j++) {
cin >> mat[i][j];
}
}
}
// Display matrix
void display() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << mat[i][j] << " ";
}
cout << endl;
}
}
// Add matrices
Matrix add(const Matrix& m) {
if (rows != m.rows || cols != m.cols) {
throw invalid_argument("Matrices must have the same
size for addition.");
}
Matrix result(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result.mat[i][j] = mat[i][j] + m.mat[i][j];
}
}
return result;
}
// Multiply matrices
Matrix multiply(const Matrix& m) {
if (cols != m.rows) {
throw invalid_argument("Number of columns of first
matrix must equal number of rows of second matrix.");
}
Matrix result(rows, m.cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < m.cols; j++) {
result.mat[i][j] = 0;
for (int k = 0; k < cols; k++) {
result.mat[i][j] += mat[i][k] * m.mat[k][j];
}
}
}
return result;
}
// Transpose the matrix
Matrix transpose() {
Matrix result(cols, rows);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result.mat[j][i] = mat[i][j];
}
}
return result;
}
};
// Main function for menu-driven program
int main() {
int choice;
int r1, c1, r2, c2;
while (true) {
// Display menu
cout << "\nMatrix Operations Menu\n";
cout << "1. Add matrices\n";
cout << "2. Multiply matrices\n";
cout << "3. Transpose matrix\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
if (choice == 4) break;
try {
switch (choice) {
case 1: {
// Input first matrix
cout << "Enter number of rows and columns for
Matrix 1: ";
cin >> r1 >> c1;
Matrix m1(r1, c1);
m1.input();
// Input second matrix
cout << "Enter number of rows and columns for
Matrix 2: ";
cin >> r2 >> c2;
Matrix m2(r2, c2);
m2.input();
// Add matrices
Matrix result = m1.add(m2);
cout << "Sum of matrices:\n";
result.display();
break;
}
case 2: {
// Input first matrix
cout << "Enter number of rows and columns for
Matrix 1: ";
cin >> r1 >> c1;
Matrix m1(r1, c1);
m1.input();
// Input second matrix
cout << "Enter number of rows and columns for
Matrix 2: ";
cin >> r2 >> c2;
Matrix m2(r2, c2);
m2.input();
// Multiply matrices
Matrix result = m1.multiply(m2);
cout << "Product of matrices:\n";
result.display();
break;
}
case 3: {
// Input matrix for transpose
cout << "Enter number of rows and columns for
Matrix: ";
cin >> r1 >> c1;
Matrix m1(r1, c1);
m1.input();
// Transpose matrix
Matrix result = m1.transpose();
cout << "Transpose of matrix:\n";
result.display();
break;
}
default:
cout << "Invalid choice, please try again.\n";
break;
}
} catch (const exception& e) {
cout << "Error: " << e.what() << endl;
}
}
return 0;
}
//9. Define a class Person having name as a data member.
Inherit two classes Student and Employee from Person.
Student has additional attributes as course, marks and
year and Employee has department and salary. Write
display() method in all the three classes to display the
corresponding attributes. Provide the necessary methods
to show runtime polymorphism.
#include <iostream>
#include <string>
using namespace std;
// Base class
class Person {
protected:
string name;
public:
Person(string n) : name(n) {}
virtual void display() {
cout << "Name: " << name << endl;
}
virtual ~Person() {}
};
// Derived class: Student
class Student : public Person {
private:
string course;
int marks;
int year;
public:
Student(string n, string c, int m, int y)
: Person(n), course(c), marks(m), year(y) {}
void display() override {
cout << "Name: " << name << endl;
cout << "Course: " << course << endl;
cout << "Marks: " << marks << endl;
cout << "Year: " << year << endl;
}
};
// Derived class: Employee
class Employee : public Person {
private:
string department;
double salary;
public:
Employee(string n, string d, double s)
: Person(n), department(d), salary(s) {}
void display() override {
cout << "Name: " << name << endl;
cout << "Department: " << department << endl;
cout << "Salary: " << salary << endl;
}
};
// Function demonstrating runtime polymorphism
void showDetails(Person* p) {
p->display();
}
int main() {
Person* p1 = new Person("John Doe");
Person* p2 = new Student("Alice", "Computer Science", 90,
2024);
Person* p3 = new Employee("Bob", "HR", 50000.0);
cout << "Person:" << endl;
showDetails(p1);
cout << "\nStudent:" << endl;
showDetails(p2);
cout << "\nEmployee:" << endl;
showDetails(p3);
delete p1;
delete p2;
delete p3;
return 0;
}
//10. Create a Triangle class. Add exception handling
statements to ensure the following conditions: all sides are
greater than 0 and sum of any two sides is greater than the
third side. The class should also have overloaded
functions for calculating the area of a right angled triangle
as well as using Heron's formula to calculate the area of
any type of triangle.
#include <iostream>
#include <cmath>
#include <stdexcept>
using namespace std;
class Triangle {
private:
double a, b, c;
// Helper function to validate triangle
void validateTriangle(double x, double y, double z) {
if (x <= 0 || y <= 0 || z <= 0) {
throw invalid_argument("All sides must be greater than
zero.");
}
if ((x + y <= z) || (x + z <= y) || (y + z <= x)) {
throw invalid_argument("Sum of any two sides must be
greater than the third side.");
}
}
public:
// Constructor with validation
Triangle(double x, double y, double z) {
validateTriangle(x, y, z);
a = x;
b = y;
c = z;
}
// Area for right-angled triangle: assuming 'base' and 'height'
double area(double base, double height) {
if (base <= 0 || height <= 0) {
throw invalid_argument("Base and height must be
greater than zero.");
}
return 0.5 * base * height;
}
// Overloaded area() for any triangle using Heron's formula
double area() {
double s = (a + b + c) / 2.0;
return sqrt(s * (s - a) * (s - b) * (s - c));
}
void printSides() {
cout << "Sides of triangle: a = " << a << ", b = " << b << ",
c = " << c << endl;
}
};
// Driver function
int main() {
try {
Triangle t1(3, 4, 5); // Valid triangle
t1.printSides();
cout << "Area using Heron's formula: " << t1.area() <<
endl;
cout << "Area of right-angled triangle (base=3, height=4):
";
cout << t1.area(3, 4) << endl;
cout << endl;
// Invalid triangle (throws exception)
Triangle t2(1, 2, 3); // Not valid
cout << "This will not print because of the exception." <<
endl;
}
catch (exception& e) {
cout << "Exception: " << e.what() << endl;
}
return 0;
}
//11. Copy the contents of one text file to another, after
removing all whitespaces.
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string sourceFile = "Myfile.txt";
string destinationFile = "destination.txt";
ifstream inFile(sourceFile.c_str());
ofstream outFile(destinationFile.c_str());
if (!inFile) {
cout << "Could not open source file." << endl;
return 1;
}
if (!outFile) {
cout << "Could not open destination file." << endl;
return 1;
}
char ch;
while (inFile.get(ch)) {
if (!isspace(ch)) {
outFile.put(ch);
}
}
inFile.close();
outFile.close();
cout << "File copied successfully with all whitespaces
removed." << endl;
return 0;
}