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

PROGRAMMING WITH C++ Program File Yash

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

PROGRAMMING WITH C++ Program File Yash

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

PROGRAMMING WITH C++

ASSIGNMENT

BY
YASH MAHESHWARI
240443
1. Program to Check if a Given Character is Vowel or Consonant:

#include <iostream>

using namespace std;

int main() {

char ch;

cout << "Enter a character: ";

cin >> ch;

// Check if the character is a vowel or consonant

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||

ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {

cout << ch << " is a vowel." << endl;

} else {

cout << ch << " is a consonant." << endl;

return 0;

}
2. Program to Check Whether a Number is Positive, Negative, or Zero:

#include <iostream>

using namespace std;

int main() {

int num;

cout << "Enter a number: ";

cin >> num;

if (num > 0) {

cout << "The number is positive." << endl;

} else if (num < 0) {

cout << "The number is negative." << endl;

} else {

cout << "The number is zero." << endl;

return 0;

}
3. Program to Check if the Input Character is an Alphabet, Digit, or Special Character:

#include <iostream>

using namespace std;

int main() {

char ch;

cout << "Enter a character: ";

cin >> ch;

// Check if the character is alphabet, digit, or special character

if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {

cout << "The character is an alphabet." << endl;

} else if (ch >= '0' && ch <= '9') {

cout << "The character is a digit." << endl;

} else {

cout << "The character is a special character." << endl;

return 0;

}
4. Create a Calculator Using the Switch Statement:

#include <iostream>

using namespace std;

int main() {

int num1, num2;

char operation;

cout << "Enter first number: ";

cin >> num1;

cout << "Enter second number: ";

cin >> num2;

cout << "Enter operator (+, -, *, /): ";

cin >> operation;

switch (operation) {

case '+':

cout << "Result: " << num1 + num2 << endl;

break;

case '-':

cout << "Result: " << num1 - num2 << endl;

break;

case '*':

cout << "Result: " << num1 * num2 << endl;

break;

case '/'

if (num2 != 0) {
cout << "Result: " << num1 / num2 << endl;

} else {

cout << "Division by zero is not allowed." << endl;

break;

default:

cout << "Invalid operator." << endl;

return 0;

}
5. Program to Print a Half-Pyramid Using Numbers:

#include <iostream>

using namespace std;

int main() {

int n = 5;

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= i; j++) {

cout << j << " ";

cout << endl;

return 0;

}
6. Program to Print a Half-Pyramid Using *:

#include <iostream>

using namespace std;

int main() {

int n = 5;

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= i; j++) {

cout << "* ";

cout << endl;

return 0;

}
7. Print the Following Patterns:

(a) Alphabet Pyramid Pattern:

#include <iostream>

using namespace std;

int main() {

char ch = 'A';

for (int i = 1; i <= 5; i++) {

for (int j = 1; j <= i; j++) {

cout << ch << " ";

ch++;

cout << endl;

return 0;

(b) Inverted Star Pyramid:

#include <iostream>

using namespace std;

int main() {

int n = 5;

for (int i = n; i >= 1; i--) {

for (int j = 1; j <= i; j++) {


cout << "* ";

cout << endl;

return 0;

(c) Decreasing Star Pyramid:

#include <iostream>

using namespace std;

int main() {

int n = 8;

for (int i = 0; i < n; i += 2) {

for (int j = 0; j < i; j++) {

cout << " ";

for (int j = i; j < n; j++) {

cout << "* ";

cout << endl;

return 0;

(d) Number Pyramid:


#include <iostream>

using namespace std;

int main() {

int num = 1;

for (int i = 1; i <= 4; i++) {

for (int j = 1; j <= i; j++) {

cout << num << " ";

num++;

cout << endl;

return 0;

(e) Number Triangle:

#include <iostream>

using namespace std;

int main() {

for (int i = 1; i <= 5; i++) {

for (int j = 1; j <= i; j++) {

cout << i;

cout << endl;

return 0;
}

Let me know if you need further explanation or modifications!


1. Program to Find HCF/GCD:

#include <iostream>

using namespace std;

int main() {

int a, b, gcd;

cout << "Enter two numbers: ";

cin >> a >> b;

// Using Euclidean algorithm to find HCF/GCD

while (b != 0) {

gcd = b;

b = a % b;

a = gcd;

cout << "The HCF/GCD is: " << gcd << endl;

return 0;

}
2. Program to Find LCM:

#include <iostream>

using namespace std;

int main() {

int a, b, lcm;

cout << "Enter two numbers: ";

cin >> a >> b;

// Formula to find LCM: LCM = (a * b) / GCD

lcm = (a * b) / __gcd(a, b); // using the built-in gcd function

cout << "The LCM is: " << lcm << endl;

return 0;

}
3. Program to Check Whether a Number is Palindrome or Not:

#include <iostream>

using namespace std;

int main() {

int num, reversed = 0, remainder, original;

cout << "Enter a number: ";

cin >> num;

original = num;

// Reverse the number

while (num != 0) {

remainder = num % 10;

reversed = reversed * 10 + remainder;

num /= 10;

// Check if the number is a palindrome

if (original == reversed) {

cout << original << " is a palindrome." << endl;

} else {

cout << original << " is not a palindrome." << endl;

return 0;
}

4. Program to Check Whether a Number is Armstrong or Not:

#include <iostream>

#include <cmath>

using namespace std;

int main() {

int num, original, remainder, result = 0, n = 0;

cout << "Enter a number: ";

cin >> num;

original = num;

// Calculate the number of digits in the number

while (original != 0) {

original /= 10;

++n;

original = num;

// Calculate the Armstrong number

while (original != 0) {

remainder = original % 10;

result += pow(remainder, n);

original /= 10;
}

if (result == num) {

cout << num << " is an Armstrong number." << endl;

} else {

cout << num << " is not an Armstrong number." << endl;

return 0;

5. Program to Calculate the Sum of Natural Numbers:

#include <iostream>

using namespace std;

int main() {

int n, sum = 0;

cout << "Enter a number: ";

cin >> n;

// Calculate sum of natural numbers using formula n(n+1)/2

sum = n * (n + 1) / 2;

cout << "The sum of natural numbers up to " << n << " is: " << sum << endl;

return 0;

6. Program to Calculate the Sum of Series 1 - 2 + 3 - 4 + ... + n:

#include <iostream>
using namespace std;

int main() {

int n, sum = 0;

cout << "Enter a number: ";

cin >> n;

// Calculate sum of series 1 - 2 + 3 - 4 + ... + n

for (int i = 1; i <= n; i++) {

if (i % 2 == 0) {

sum -= i; // subtract for even numbers

} else {

sum += i; // add for odd numbers

cout << "The sum of the series is: " << sum << endl;

return 0;

}
List Programs
1. Compute the sum of the first n terms of the following series:

S = 1 - 1/2! + 1/3! - 1/4! + ... + 1/n!

#include <iostream>

using namespace std;

double factorial(int num) {

double fact = 1;

for (int i = 1; i <= num; ++i) {

fact *= i;

return fact;

int main(int argc, char *argv[]) {

int n;

// Check if command-line argument exists

if (argc > 1) {

n = atoi(argv[1]);

} else {

cout << "Enter the value of n: ";

cin >> n;

double sum = 0.0;

bool sign = true; // To alternate the sign of terms


for (int i = 1; i <= n; ++i) {

if (sign) {

sum += 1 / factorial(i);

} else {

sum -= 1 / factorial(i);

sign = !sign; // Flip sign for next term

cout << "The sum of the series for " << n << " terms is: " << sum << endl;

return 0;

}
2. Write a program to remove duplicates from an array.

#include <iostream>

#include <unordered_set>

#include <vector>

using namespace std;

void removeDuplicates(vector<int>& arr) {

unordered_set<int> uniqueElements;

int index = 0;

for (int i = 0; i < arr.size(); ++i) {

if (uniqueElements.find(arr[i]) == uniqueElements.end()) {

arr[index++] = arr[i];

uniqueElements.insert(arr[i]);

arr.resize(index); // Resize the array to remove extra elements

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];

removeDuplicates(arr);

cout << "Array after removing duplicates: ";

for (int i = 0; i < arr.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>

#include <cstring>

#include <cctype>

using namespace std;

void countAlphabets(const string& text) {

int freq[26] = {0}; // Array to store the frequency of each letter

// Count the frequency of each alphabet

for (char ch : text) {

if (isalpha(ch)) {

ch = tolower(ch); // Convert character to lowercase

freq[ch - 'a']++;

// Print the frequency table

cout << "Character | Frequency\n";

cout << "----------------------\n";

for (int i = 0; i < 26; ++i) {

if (freq[i] > 0) {

cout << char(i + 'a') << " | " << freq[i] << endl;

int main(int argc, char *argv[]) {


string text = "";

// Combine all command-line arguments into one string

for (int i = 1; i < argc; ++i) {

text += argv[i];

if (text.empty()) {

cout << "Please provide text as command line arguments." << endl;

} else {

countAlphabets(text);

return 0;

}
4. Write a menu-driven program to perform string manipulation (without using inbuilt string
functions):

#include <iostream>

#include <cstring>

using namespace std;

// Function to show the address of each character in the string

void showAddresses(const char* str) {

while (*str) {

cout << "Address of character " << *str << ": " << (void*)str << endl;

str++;

// Function to concatenate two strings

void concatenateStrings(char* str1, const char* str2) {

while (*str1) {

str1++;

while (*str2) {

*str1 = *str2;

str1++;

str2++;

*str1 = '\0'; // Null terminate the concatenated string

// Function to compare two strings

int compareStrings(const char* str1, const char* str2) {


while (*str1 && (*str1 == *str2)) {

str1++;

str2++;

return *str1 - *str2;

// Function to calculate length of the string using pointers

int stringLength(const char* str) {

int length = 0;

while (*str++) {

length++;

return length;

// Function to convert all lowercase characters to uppercase

void toUppercase(char* str) {

while (*str) {

if (*str >= 'a' && *str <= 'z') {

*str = *str - 32; // Convert lowercase to uppercase

str++;

// Function to reverse the string

void reverseString(char* str) {


int length = stringLength(str);

for (int i = 0; i < length / 2; ++i) {

char temp = str[i];

str[i] = str[length - 1 - i];

str[length - 1 - i] = temp;

// Function to insert a string at a user-specified position

void insertString(char* str1, const char* str2, int position) {

int len1 = stringLength(str1);

int len2 = stringLength(str2);

for (int i = len1 - 1; i >= position; --i) {

str1[i + len2] = str1[i];

for (int i = 0; i < len2; ++i) {

str1[position + i] = str2[i];

str1[len1 + len2] = '\0'; // Null terminate the string

int main() {

char str1[100], str2[100];

int choice, position;

while (true) {
cout << "\nMenu:\n";

cout << "1. Show 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 lowercase to uppercase\n";

cout << "6. Reverse the string\n";

cout << "7. Insert string into another string at a specified position\n";

cout << "8. Exit\n";

cout << "Enter your choice: ";

cin >> choice;

cin.ignore(); // To ignore newline character after choice input

switch (choice) {

case 1:

cout << "Enter a 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);

concatenateStrings(str1, str2);

cout << "Concatenated string: " << str1 << endl;

break;
case 3:

cout << "Enter first string: ";

cin.getline(str1, 100);

cout << "Enter second string: ";

cin.getline(str2, 100);

int result = compareStrings(str1, str2);

if (result == 0) {

cout << "The strings are equal." << endl;

} else if (result < 0) {

cout << "The first string is less than the second string." << endl;

} else {

cout << "The first string is greater than the second string." << endl;

break;

case 4:

cout << "Enter a string: ";

cin.getline(str1, 100);

cout << "Length of the string: " << stringLength(str1) << endl;

break;

case 5:

cout << "Enter a string: ";

cin.getline(str1, 100);

toUppercase(str1);

cout << "String after conversion to uppercase: " << str1 << endl;

break;

case 6:

cout << "Enter a string: ";


cin.getline(str1, 100);

reverseString(str1);

cout << "Reversed string: " << str1 << endl;

break;

case 7:

cout << "Enter the first string: ";

cin.getline(str1, 100);

cout << "Enter the second string: ";

cin.getline(str2, 100);

cout << "Enter the position to insert: ";

cin >> position;

insertString(str1, str2, position);

cout << "String after insertion: " << str1 << endl;

break;

case 8:

cout << "Exiting program." << endl;

return 0;

default:

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

5. Write a program to merge two ordered arrays to get a single ordered array.

#include <iostream>

#include <vector>

using namespace std;


vector<int> mergeArrays(const vector<int>& arr1, const vector<int>& arr2) {

vector<int> mergedArray;

int i = 0, j = 0;

// Merging the two sorted arrays

while (i < arr1.size() && j < arr2.size()) {

if (arr1[i] < arr2[j]) {

mergedArray.push_back(arr1[i]);

i++;

} else {

mergedArray.push_back(arr2[j]);

j++;

// Adding remaining elements of arr1, if any

while (i < arr1.size()) {

mergedArray.push_back(arr1[i]);

i++;

// Adding remaining elements of arr2, if any

while (j < arr2.size()) {

mergedArray.push_back(arr2[j]);

j++;

}
return mergedArray;

int main() {

int n1, n2;

// Input for the first array

cout << "Enter the number of elements in the first array: ";

cin >> n1;

vector<int> arr1(n1);

cout << "Enter the elements of the first array (sorted): ";

for (int i = 0; i < n1; i++) {

cin >> arr1[i];

// Input for the second array

cout << "Enter the number of elements in the second array: ";

cin >> n2;

vector<int> arr2(n2);

cout << "Enter the elements of the second array (sorted): ";

for (int i = 0; i < n2; i++) {

cin >> arr2[i];

// Merging the arrays

vector<int> mergedArray = mergeArrays(arr1, arr2);


// Output the merged array

cout << "Merged and sorted array: ";

for (int i = 0; i < mergedArray.size(); i++) {

cout << mergedArray[i] << " ";

cout << endl;

return 0;

6. Write a program to search a given element in a set of N numbers using Binary Search:

a. With Recursion

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

// Recursive binary search function

int binarySearchRecursive(const vector<int>& arr, int low, int high, int key) {

if (low > high) {

return -1; // Element not found

int mid = low + (high - low) / 2;

if (arr[mid] == key) {

return mid; // Element found

}
if (arr[mid] > key) {

return binarySearchRecursive(arr, low, mid - 1, key); // Search left half

} else {

return binarySearchRecursive(arr, mid + 1, high, key); // Search right half

int main() {

int n, key;

cout << "Enter the number of elements: ";

cin >> n;

vector<int> arr(n);

cout << "Enter the elements (sorted): ";

for (int i = 0; i < n; ++i) {

cin >> arr[i];

cout << "Enter the element to search: ";

cin >> key;

// Perform binary search using recursion

int result = binarySearchRecursive(arr, 0, n - 1, key);

if (result != -1) {
cout << "Element found at index: " << result << endl;

} else {

cout << "Element not found!" << endl;

return 0;

b. Without Recursion

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

// Iterative binary search function

int binarySearchIterative(const vector<int>& arr, int key) {

int low = 0, high = arr.size() - 1;

while (low <= high) {

int mid = low + (high - low) / 2;

if (arr[mid] == key) {

return mid; // Element found

if (arr[mid] > key) {

high = mid - 1; // Search left half

} else {
low = mid + 1; // Search right half

return -1; // Element not found

int main() {

int n, key;

cout << "Enter the number of elements: ";

cin >> n;

vector<int> arr(n);

cout << "Enter the elements (sorted): ";

for (int i = 0; i < n; ++i) {

cin >> arr[i];

cout << "Enter the element to search: ";

cin >> key;

// Perform binary search using iteration

int result = binarySearchIterative(arr, key);

if (result != -1) {

cout << "Element found at index: " << result << endl;

} else {
cout << "Element not found!" << endl;

return 0;

7. Write a program to calculate the GCD (Greatest Common Divisor) of two numbers:

a. With Recursion

#include <iostream>

using namespace std;

// Recursive function to calculate GCD

int gcdRecursive(int a, int b) {

if (b == 0) {

return a; // Base case: GCD is a when b is 0

return gcdRecursive(b, a % b); // Recursively calculate GCD

int main() {

int a, b;

cout << "Enter two numbers: ";

cin >> a >> b;

int result = gcdRecursive(a, b);

cout << "GCD of " << a << " and " << b << " is: " << result << endl;
return 0;

b. Without Recursion

#include <iostream>

using namespace std;

// Iterative function to calculate GCD

int gcdIterative(int a, int b) {

while (b != 0) {

int temp = b;

b = a % b;

a = temp;

return a; // When b is 0, a contains the GCD

int main() {

int a, b;

cout << "Enter two numbers: ";

cin >> a >> b;

int result = gcdIterative(a, b);

cout << "GCD of " << a << " and " << b << " is: " << result << endl;
return 0;

8. Create a Matrix class. Write a menu-driven program to perform the 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 <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.resize(r, vector<int>(c, 0));

void input() {

cout << "Enter elements for a " << rows << "x" << cols << " matrix:\n";

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {


cin >> mat[i][j];

void display() const {

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

cout << mat[i][j] << " ";

cout << endl;

Matrix add(const Matrix& other) {

if (rows != other.rows || cols != other.cols) {

throw invalid_argument("Matrix dimensions do not match 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) {

if (cols != other.rows) {

throw invalid_argument("Matrix dimensions do not match 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() {

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() {
int choice, rows1, cols1, rows2, cols2;

cout << "Enter the number of rows and columns for the first matrix: ";

cin >> rows1 >> cols1;

Matrix mat1(rows1, cols1);

mat1.input();

cout << "Enter the number of rows and columns for the second matrix: ";

cin >> rows2 >> cols2;

Matrix mat2(rows2, cols2);

mat2.input();

do {

cout << "\nMatrix Operations Menu\n";

cout << "1. Add Matrices\n";

cout << "2. Multiply Matrices\n";

cout << "3. Transpose of First Matrix\n";

cout << "4. Transpose of Second Matrix\n";

cout << "5. Exit\n";

cout << "Enter your choice: ";

cin >> choice;

try {

switch (choice) {

case 1:

// Addition

cout << "Matrix 1 + Matrix 2:\n";


mat1.add(mat2).display();

break;

case 2:

// Multiplication

cout << "Matrix 1 * Matrix 2:\n";

mat1.multiply(mat2).display();

break;

case 3:

// Transpose of matrix 1

cout << "Transpose of Matrix 1:\n";

mat1.transpose().display();

break;

case 4:

// Transpose of matrix 2

cout << "Transpose of Matrix 2:\n";

mat2.transpose().display();

break;

case 5:

cout << "Exiting...\n";

break;

default:

cout << "Invalid choice! Please try again.\n";

} catch (const invalid_argument& e) {

cout << "Error: " << e.what() << endl;

} while (choice != 5);


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, while Employee has
department and salary. Write the display() method in all three classes to display the corresponding
attributes. Provide the necessary methods to show runtime polymorphism.

#include <iostream>

#include <string>

using namespace std;

// Base class Person

class Person {

protected:

string name;

public:

Person(string n) : name(n) {}

virtual void display() const {

cout << "Name: " << name << endl;

};

// Derived class Student

class Student : public Person {

private:

string course;

float marks;
int year;

public:

Student(string n, string c, float m, int y) : Person(n), course(c), marks(m), year(y) {}

void display() const override {

Person::display();

cout << "Course: " << course << endl;

cout << "Marks: " << marks << endl;

cout << "Year: " << year << endl;

};

// Derived class Employee

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() const override {

Person::display();

cout << "Department: " << department << endl;

cout << "Salary: " << salary << endl;

};
int main() {

// Creating objects of Student and Employee

Person* person1 = new Student("John Doe", "Computer Science", 85.5, 2);

Person* person2 = new Employee("Alice Smith", "Marketing", 50000);

// Display information using runtime polymorphism

cout << "Student Information:" << endl;

person1->display();

cout << "\nEmployee Information:" << endl;

person2->display();

// Cleaning up memory

delete person1;

delete person2;

return 0;

10. Create a Triangle class. Add exception handling statements to ensure the following conditions:

 All sides are greater than 0.

 The 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 side1, side2, side3;

public:

// Constructor to initialize sides

Triangle(double s1, double s2, double s3) {

if (s1 <= 0 || s2 <= 0 || s3 <= 0) {

throw invalid_argument("Sides must be greater than 0");

if (s1 + s2 <= s3 || s1 + s3 <= s2 || s2 + s3 <= s1) {

throw invalid_argument("The sum of any two sides must be greater than the third side");

side1 = s1;

side2 = s2;

side3 = s3;

// Function to calculate area of a right-angled triangle

double areaRightAngled() {

return 0.5 * side1 * side2;

// Function to calculate area using Heron's formula


double areaHeron() {

double s = (side1 + side2 + side3) / 2; // Semi-perimeter

return sqrt(s * (s - side1) * (s - side2) * (s - side3));

void display() {

cout << "Sides of the Triangle: " << side1 << ", " << side2 << ", " << side3 << endl;

};

int main() {

double s1, s2, s3;

// Taking input from the user

cout << "Enter three sides of the triangle: ";

cin >> s1 >> s2 >> s3;

try {

// Creating an object of the Triangle class

Triangle t(s1, s2, s3);

t.display();

// Check if the triangle is right-angled

if (s1 * s1 + s2 * s2 == s3 * s3 || s1 * s1 + s3 * s3 == s2 * s2 || s2 * s2 + s3 * s3 == s1 * s1) {

cout << "Area of the Right-Angled Triangle: " << t.areaRightAngled() << endl;

} else {

cout << "Area using Heron's formula: " << t.areaHeron() << endl;
}

} catch (const invalid_argument& e) {

cout << "Error: " << e.what() << endl;

return 0;

11. Create a Student class containing fields for Roll No., Name, Class, Year, and Total Marks. Write a
program to store 5 objects of the Student class in a file. Retrieve these records from the file and
display them.

#include <iostream>

#include <fstream>

#include <string>

using namespace std;

class Student {

private:

int rollNo;

string name;

string studentClass;

int year;

float totalMarks;

public:

// Constructor

Student(int r, string n, string c, int y, float m) :

rollNo(r), name(n), studentClass(c), year(y), totalMarks(m) {}

// Function to display student information


void display() const {

cout << "Roll No: " << rollNo << "\n"

<< "Name: " << name << "\n"

<< "Class: " << studentClass << "\n"

<< "Year: " << year << "\n"

<< "Total Marks: " << totalMarks << "\n\n";

// Function to write student data to a file

void writeToFile(ofstream& outFile) const {

outFile << rollNo << "\n" << name << "\n" << studentClass << "\n" << year << "\n" << totalMarks
<< "\n";

// Function to read student data from a file

void readFromFile(ifstream& inFile) {

inFile >> rollNo;

inFile.ignore(); // To ignore newline after the integer

getline(inFile, name);

getline(inFile, studentClass);

inFile >> year;

inFile >> totalMarks;

};

int main() {

// Creating 5 student objects

Student students[] = {

Student(1, "Alice", "A", 1, 85.5),

Student(2, "Bob", "B", 2, 90.0),

Student(3, "Charlie", "C", 3, 78.0),


Student(4, "David", "D", 1, 88.5),

Student(5, "Eva", "E", 2, 92.0)

};

// Writing student data to a file

ofstream outFile("students.txt");

if (!outFile) {

cout << "Error opening file for writing.\n";

return 1;

for (int i = 0; i < 5; i++) {

students[i].writeToFile(outFile);

outFile.close();

// Reading student data from the file

ifstream inFile("students.txt");

if (!inFile) {

cout << "Error opening file for reading.\n";

return 1;

cout << "Student Information from File:\n";

Student temp(0, "", "", 0, 0.0);

while (inFile) {

temp.readFromFile(inFile);

if (inFile) {

temp.display();

}
}

inFile.close();

return 0;

}
12. Copy the contents of one text file to another file, after removing all whitespaces.

#include <iostream>

#include <fstream>

#include <cctype>

using namespace std;

void removeWhitespaceAndCopy(const string& inputFile, const string& outputFile) {

ifstream inFile(inputFile);

if (!inFile) {

cout << "Error opening input file.\n";

return;

ofstream outFile(outputFile);

if (!outFile) {

cout << "Error opening output file.\n";

return;

char ch;

while (inFile.get(ch)) {

if (!isspace(ch)) { // Check if the character is not a whitespace

outFile.put(ch);

inFile.close();
outFile.close();

int main() {

string inputFile = "input.txt"; // Input file

string outputFile = "output.txt"; // Output file

// Copy contents of input file to output file while removing whitespaces

removeWhitespaceAndCopy(inputFile, outputFile);

cout << "Whitespace removed and content copied successfully.\n";

return 0;

You might also like