INDRAPRASTHA COLLEGE FOR WOMEN
PROGRAMMING USING C++
(SEMESTER 2)
SUBMITTED BY: SUBMITTED TO:
BHAVIKA JAIN MRS.ARCHANA SINGHAL
BSC. (HONS) COMPUTER SCIENCE
24/CS/09
24IPCWBSCS000009
QUESTION 1
CODE:-
#include <iostream>
using namespace std;
double power(int base, int exp) {
double result = 1.0;
for (int i = 0; i < exp; ++i) {
result *= base;
}
return result;
}
int main() {
int n;
cout << "Enter the number of terms (n): ";
cin >> n;
double sum = 0.0;
for (int i = 1; i <= n; ++i) {
double term = 1.0 / power(i, i);
if (i % 2 == 0)
sum -= term;
else
sum += term;
}
cout << "Sum of the series up to " << n << " terms is: " << sum << endl;
return 0;
}
OUTPUT:
QUESTION 2
CODE:-
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter the number of elements in the array: ";
cin >> n;
int arr[100];
cout << "Enter " << n << " elements:\n";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int uniqueArr[100];
int uniqueCount = 0;
for (int i = 0; i < n; i++) {
bool isDuplicate = false;
for (int j = 0; j < uniqueCount; j++) {
if (arr[i] == uniqueArr[j]) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
uniqueArr[uniqueCount] = arr[i];
uniqueCount++;
}
}
cout << "Array after removing duplicates:\n";
for (int i = 0; i < uniqueCount; i++) {
cout << uniqueArr[i] << " ";
}
return 0;
}
OUTPUT:
QUESTION 3
CODE:-
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
int main() {
int freq[26] = {0};
string input;
cout << "Enter a string: ";
getline(cin, input);
for (char ch : input) {
ch = tolower(ch);
if (isalpha(ch)) {
freq[ch - 'a']++;}}
cout << "Alphabet\tCount\n";
for (int i = 0; i < 26; ++i) {
if (freq[i] > 0) {
cout << char('a' + i) << "\t\t" << freq[i] << endl;
}}
return 0;}
OUTPUT:
QUESTION 4
CODE:
#include <iostream>
using namespace std;
int stringLength(char* str) {
int len = 0;
while (*(str + len) != '\0') len++;
return len;
}
void showAddresses(char* str) {
for (int i = 0; str[i] != '\0'; i++)
cout << "Address of '" << str[i] << "' = " << (void*)&str[i] << endl;
}
void concatenate(char* s1, char* s2, char* result) {
int i = 0, j = 0;
while (s1[i] != '\0') {
result[i] = s1[i];
i++;
}
while (s2[j] != '\0') {
result[i++] = s2[j++];
}
result[i] = '\0';
}
bool compare(char* s1, char* s2) {
int i = 0;
while (s1[i] != '\0' && s2[i] != '\0') {
if (s1[i] != s2[i]) return false;
i++;
}
return s1[i] == '\0' && s2[i] == '\0';
}
void toUpperCase(char* str) {
for (int i = 0; str[i] != '\0'; i++)
if (str[i] >= 'a' && str[i] <= 'z') str[i] -= 32;
}
void reverseString(char* str) {
int len = stringLength(str);
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}
void insertString(char* str1, char* str2, char* result, int pos) {
int i = 0, j = 0;
// Copy first part
for (i = 0; i < pos; i++) result[i] = str1[i];
// Insert str2
for (j = 0; str2[j] != '\0'; j++) result[i++] = str2[j];
for (int k = pos; str1[k] != '\0'; k++) result[i++] = str1[k];
result[i] = '\0';
}
int main() {
char str1[100], str2[100], result[200];
int choice, pos;
while (true) {
cout << "\nMenu:\n"
<< "1. Show address of each character\n"
<< "2. Concatenate two strings\n"
<< "3. Compare two strings\n"
<< "4. Calculate length\n"
<< "5. Convert lowercase to uppercase\n"
<< "6. Reverse string\n"
<< "7. Insert one string into another\n"
<< "8. Exit\n"
<< "Enter choice: ";
cin >> choice;
cin.ignore();
switch (choice) {
case 1:
cout << "Enter string: ";
cin.getline(str1, 100);
showAddresses(str1);
break;
case 2:
cout << "Enter first string: ";
cin.getline(str1, 100);
cout << "Enter second string: ";
cin.getline(str2, 100);
concatenate(str1, str2, result);
cout << "Concatenated: " << result << endl;
break;
case 3:
cout << "Enter first string: ";
cin.getline(str1, 100);
cout << "Enter second string: ";
cin.getline(str2, 100);
if (compare(str1, str2))
cout << "Strings are equal\n";
else
cout << "Strings are not equal\n";
break;
case 4:
cout << "Enter string: ";
cin.getline(str1, 100);
cout << "Length = " << stringLength(str1) << endl;
break;
case 5:
cout << "Enter string: ";
cin.getline(str1, 100);
toUpperCase(str1);
cout << "Uppercase: " << str1 << endl;
break;
case 6:
cout << "Enter string: ";
cin.getline(str1, 100);
reverseString(str1);
cout << "Reversed: " << str1 << endl;
break;
case 7:
cout << "Enter main string: ";
cin.getline(str1, 100);
cout << "Enter string to insert: ";
cin.getline(str2, 100);
cout << "Enter position: ";
cin >> pos;
cin.ignore();
insertString(str1, str2, result, pos);
cout << "Result: " << result << endl;
break;
case 8:
return 0;
default:
cout << "Invalid choice.\n";
}}
}
OUTPUT:
QUESTION 5
CODE:-
#include <iostream>
using namespace std;
void mergeArrays(int a[], int n, int b[], int m, int result[]) {
int i = 0, j = 0, k = 0;
while (i < n && j < m) {
if (a[i] < b[j])
result[k++] = a[i++];
else
result[k++] = b[j++];
}
while (i < n)
result[k++] = a[i++];
while (j < m)
result[k++] = b[j++];
}
int main() {
int n, m;
cout << "Enter number of elements in first sorted array: ";
cin >> n;
int a[n];
cout << "Enter elements of first sorted array:\n";
for (int i = 0; i < n; i++)
cin >> a[i];
cout << "Enter number of elements in second sorted array: ";
cin >> m;
int b[m];
cout << "Enter elements of second sorted array:\n";
for (int i = 0; i < m; i++)
cin >> b[i];
int result[n + m];
mergeArrays(a, n, b, m, result);
cout << "Merged sorted array: ";
for (int i = 0; i < n + m; i++)
cout << result[i] << " ";
return 0;
}
OUTPUT:
QUESTION 6
CODE:
#include <iostream>
using namespace std;
int binarySearchRecursive(int arr[], int low, int high, int key) {
if (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == key)
return mid;
else if (arr[mid] > key)
return binarySearchRecursive(arr, low, mid - 1, key);
else
return binarySearchRecursive(arr, mid + 1, high, key);
}
return -1;
}
int binarySearchIterative(int arr[], int n, int key) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main() {
int n, key, choice;
cout << "Enter number of elements: ";
cin >> n;
int arr[n];
cout << "Enter " << n << " sorted elements:\n";
for (int i = 0; i < n; i++)
cin >> arr[i];
cout << "Enter key to search: ";
cin >> key;
cout << "\nChoose Search Method:\n";
cout << "1. Binary Search using Recursion\n";
cout << "2. Binary Search without Recursion\n";
cout << "Enter choice: ";
cin >> choice;
int result = -1;
if (choice == 1)
result = binarySearchRecursive(arr, 0, n - 1, key);
else if (choice == 2)
result = binarySearchIterative(arr, n, key);
else
cout << "Invalid choice!\n";
if (result != -1)
cout << "Element found at index " << result << endl;
else
cout << "Element not found\n";
return 0;
}
OUTPUT:
QUESTION 7
CODE:
#include <iostream>
using namespace std;
int gcdRecursive(int a, int b) {
if (b == 0)
return a;
return gcdRecursive(b, a % b);
}
int gcdIterative(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
int a, b, choice;
cout << "Enter two numbers: ";
cin >> a >> b;
cout << "Choose method:\n1. Recursive\n2. Iterative\nEnter choice: ";
cin >> choice;
int result;
if (choice == 1)
result = gcdRecursive(a, b);
else
result = gcdIterative(a, b);
cout << "GCD = " << result << endl;
return 0;
}
OUTPUT:
QUESTION 8
CODE:
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
class Matrix {
private:
vector<vector<int>> mat;
int rows, cols;
public:
Matrix(int r, int c) : rows(r), cols(c), mat(r, vector<int>(c)) {}
void input() {
cout << "Enter matrix elements:\n";
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
cin >> mat[i][j];
}
void display() const {
for (const auto& row : mat) {
for (int val : row)
cout << val << " ";
cout << endl;
}
}
Matrix add(const Matrix& other) const {
if (rows != other.rows || cols != other.cols)
throw invalid_argument("Matrices must be of 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] + other.mat[i][j];
return result;
}
Matrix multiply(const Matrix& other) const {
if (cols != other.rows)
throw invalid_argument("Columns of first must match rows of second for multiplication.");
Matrix result(rows, other.cols);
for (int i = 0; i < rows; i++)
for (int j = 0; j < other.cols; j++)
for (int k = 0; k < cols; k++)
result.mat[i][j] += mat[i][k] * other.mat[k][j];
return result;
}
Matrix transpose() const {
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;
}
};
int main() {
try {
int r1, c1, r2, c2;
cout << "Enter rows and cols for Matrix A: ";
cin >> r1 >> c1;
Matrix A(r1, c1);
A.input();
cout << "Enter rows and cols for Matrix B: ";
cin >> r2 >> c2;
Matrix B(r2, c2);
B.input();
int choice;
cout << "\nMenu:\n1. Sum\n2. Product\n3. Transpose A\nEnter choice: ";
cin >> choice;
switch (choice) {
case 1: {
Matrix C = A.add(B);
cout << "Sum:\n";
C.display();
break;
}
case 2: {
Matrix C = A.multiply(B);
cout << "Product:\n";
C.display();
break;
}
case 3: {
Matrix C = A.transpose();
cout << "Transpose of A:\n";
C.display();
break;
}
default:
cout << "Invalid choice.\n";
}
} catch (const exception& e) {
cerr << "Error: " << e.what() << endl;
}
return 0;
}
OUTPUT:
QUESTION 9
CODE:
#include <iostream>
using namespace std;
class Person {
protected:
string name;
public:
Person(string n) : name(n) {}
virtual void display() {
cout << "Name: " << name << endl;
}
};
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 << "Student Name: " << name << endl;
cout << "Course: " << course << ", Marks: " << marks << ", Year: " << year << endl;
}
};
class Employee : public Person {
private:
string department;
float salary;
public:
Employee(string n, string d, float s) : Person(n), department(d), salary(s) {}
void display() override {
cout << "Employee Name: " << name << endl;
cout << "Department: " << department << ", Salary: " << salary << endl;
}
};
int main() {
Person* p;
Student s("Alice", "CS", 90, 2);
Employee e("Bob", "HR", 50000);
p = &s;
p->display(); // Calls Student's display()
p = &e;
p->display(); // Calls Employee's display()
return 0;
}
OUTPUT:
QUESTION 10
CODE:-
#include <iostream>
#include <cmath>
#include <stdexcept>
using namespace std;
class Triangle {
private:
double a, b, c;
public:
Triangle(double x, double y, double z) : a(x), b(y), c(z) {
if (a <= 0 || b <= 0 || c <= 0)
throw invalid_argument("Sides must be greater than 0.");
if (a + b <= c || a + c <= b || b + c <= a)
throw invalid_argument("Invalid triangle: sum of any two sides must be greater than the third side.");
}
double area() {
double s = (a + b + c) / 2;
return sqrt(s * (s - a) * (s - b) * (s - c));
}
static double area(double base, double height) {
return 0.5 * base * height;
}
void displaySides() {
cout << "Sides: " << a << ", " << b << ", " << c << endl;
}
};
int main() {
try {
double x, y, z;
cout << "Enter 3 sides of the triangle: ";
cin >> x >> y >> z;
Triangle t(x, y, z);
t.displaySides();
cout << "Area using Heron's formula: " << t.area() << endl;
char choice;
cout << "\nDo you want to calculate area of a right-angled triangle (y/n)? ";
cin >> choice;
if (choice == 'y' || choice == 'Y') {
double base, height;
cout << "Enter base and height: ";
cin >> base >> height;
if (base <= 0 || height <= 0)
throw invalid_argument("Base and height must be greater than 0.");
cout << "Area of right-angled triangle: " << Triangle::area(base, height) << endl;}
} catch (const exception& e) {
cerr << "Error: " << e.what() << endl;
}
return 0;}
OUTPUT:
QUESTION 11
CODE:
#include <iostream>
#include <fstream>
using namespace std;
class Student {
public:
int rollNo;
string name;
string studentClass;
int year;
float totalMarks;
void input() {
cout << "\nEnter Roll No: ";
cin >> rollNo;
cin.ignore();
cout << "Enter Name: ";
getline(cin, name);
cout << "Enter Class: ";
getline(cin, studentClass);
cout << "Enter Year: ";
cin >> year;
cout << "Enter Total Marks: ";
cin >> totalMarks;
}
void displayLine(const string& line) {
cout << line << endl;
}
string toLine() {
return to_string(rollNo) + " " + name + " " + studentClass + " " +
to_string(year) + " " + to_string(totalMarks);
}
};
int main() {
Student s[5];
ofstream outFile("students.txt");
if (!outFile) {
cerr << "Error opening file for writing.\n";
return 1;
}
cout << "Enter details for 5 students:\n";
for (int i = 0; i < 5; ++i) {
s[i].input();
outFile << s[i].toLine() << endl;
}
outFile.close();
ifstream inFile("students.txt");
if (!inFile) {
cerr << "Error opening file for reading.\n";
return 1;
}
cout << "\n--- Student Records (One Line Each) ---\n";
string line;
while (getline(inFile, line)) {
s[0].displayLine(line);
}
inFile.close();
return 0;
}
OUTPUT:
QUESTION 12
CODE:-
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream inFile("input.txt");
ofstream outFile("output.txt");
if (!inFile || !outFile) {
cerr << "Error opening files!" << endl;
return 1;
}
char ch;
while (inFile.get(ch)) {
if (!isspace(ch)) { // remove spaces, tabs, newlines
outFile.put(ch);
}
}
cout << "Contents copied to output.txt without whitespaces." << endl;
inFile.close();
outFile.close();
return 0;
}
OUTPUT: