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

CppAssignmentPDF

Uploaded by

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

CppAssignmentPDF

Uploaded by

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

1 Addition of Two Numbers Using Float Data Type

PROGRAM.CPP
#include <iostream>
using namespace std;

int main() {
float num1, num2, sum;

cout << "Enter first number: ";


cin >> num1;

cout << "Enter second number: ";


cin >> num2;

sum = num1 + num2;

cout << "Sum of " << num1 << " and " << num2 << " is: " << sum << endl;

return 0;
}

>_ Output
Enter first number: 3.5
Enter second number: 7.8
Sum of 3.5 and 7.8 is: 11.3

1
2 Finding the Biggest Number Between Two Numbers

PROGRAM.CPP
#include <iostream>
using namespace std;

int main() {
float num1, num2;

cout << "Enter first number: ";


cin >> num1;

cout << "Enter second number: ";


cin >> num2;

if(num1 > num2) {


cout << num1 << " is greater than " << num2 << endl;
}
else if(num2 > num1) {
cout << num2 << " is greater than " << num1 << endl;
}
else {
cout << "Both numbers are equal" << endl;
}

return 0;
}

>_ Output
Enter first number: 45.6
Enter second number: 23.1
45.6 is greater than 23.1

2
3 Finding Factorial Using do-while Loop

PROGRAM.CPP
#include <iostream>
using namespace std;

int main() {
int number;
long long factorial = 1;
int i = 1;

cout << "Enter a positive integer: ";


cin >> number;

// Handle negative numbers


if(number < 0) {
cout << "Error! Factorial of a negative number doesn't exist.";
}
else {
do {
factorial *= i;
i++;
} while(i <= number);

cout << "Factorial of " << number << " = " << factorial << endl;
}

return 0;
}

>_ Output

Enter a positive integer: 5


Factorial of 5 = 120

3
4 Program for Arithmetic Operations Using Switch Case

PROGRAM.CPP
#include <iostream>
using namespace std;

int main() {
float num1, num2, result;
char operation;

cout << "Enter first number: ";


cin >> num1;
cout << "Enter second number: ";
cin >> num2;

cout << "Choose an operation (+, -, *, /): ";


cin >> operation;

switch(operation) {
case '+':
result = num1 + num2;
cout << "Result: " << num1 << " + " << num2 << " = " << result;
break;
case '-':
result = num1 - num2;
cout << "Result: " << num1 << " - " << num2 << " = " << result;
break;
case '*':
result = num1 * num2;
cout << "Result: " << num1 << " * " << num2 << " = " << result;
break;
case '/':
if(num2 != 0) {
result = num1 / num2;
cout << "Result: " << num1 << " / " << num2 << " = ";
cout << result;

} else {
cout << "Error: Division by zero!";
}
break;
default:
cout << "Invalid operation!";
}

return 0;
}

>_ Output
Enter first number: 10
Enter second number: 5
Choose an operation (+, -, *, /): +
Result: 10 + 5 = 15

4
5 Program for Multiplication of Two 3x3 Matrices

PROGRAM.CPP
#include <iostream>
using namespace std;

int main() {
int A[3][3], B[3][3], C[3][3];

cout << "Enter elements of first 3x3 matrix:\n";


for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
cout << "Enter element A[" << i << "][" << j << "]: ";
cin >> A[i][j];
}
}

cout << "\nEnter elements of second 3x3 matrix:\n";


for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
cout << "Enter element B[" << i << "][" << j << "]: ";
cin >> B[i][j];
}
}

// Initializing result matrix C with zeros


for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
C[i][j] = 0;
}
}

// Matrix multiplication
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
for(int k = 0; k < 3; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}

cout << "\nResultant matrix after multiplication:\n";


for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
cout << C[i][j] << "\t";
}
cout << endl;
}

return 0;
}

5
>_ Output
Enter elements of first 3x3 matrix:
Enter element A[0][0]: 1
Enter element A[0][1]: 2
Enter element A[0][2]: 3
Enter element A[1][0]: 4
Enter element A[1][1]: 5
Enter element A[1][2]: 6
Enter element A[2][0]: 7
Enter element A[2][1]: 8
Enter element A[2][2]: 9

Enter elements of second 3x3 matrix:


Enter element B[0][0]: 9
Enter element B[0][1]: 8
Enter element B[0][2]: 7
Enter element B[1][0]: 6
Enter element B[1][1]: 5
Enter element B[1][2]: 4
Enter element B[2][0]: 3
Enter element B[2][1]: 2
Enter element B[2][2]: 1

Resultant matrix after multiplication:


30 24 18
84 69 54
138 114 90

6
6 Program to Store Five Books of Information Using Struct.

PROGRAM.CPP
#include <iostream>
#include <string>
using namespace std;

struct Book {
string title;
string author;
int year;
float price;
string publisher;
};

int main() {

const int NUM_BOOKS = 5;


Book books[NUM_BOOKS];

// Input information for each book


for(int i = 0; i < NUM_BOOKS; i++) {
cout << "\nEnter details for Book " << (i+1) << ":" << endl;

cout << "Title: ";


cin.ignore(i == 0 ? 0 : 1); // Clear input buffer
getline(cin, books[i].title);

cout << "Author: ";


getline(cin, books[i].author);

cout << "Publication Year: ";


cin >> books[i].year;

cout << "Price: $";


cin >> books[i].price;

cout << "Publisher: ";


cin.ignore();
getline(cin, books[i].publisher);
}

// Display all book information


cout << "\n\n===== BOOK INFORMATION =====\n";
for(int i = 0; i < NUM_BOOKS; i++) {
cout << "\nBook " << (i+1) << ":" << endl;
cout << "Title: " << books[i].title << endl;
cout << "Author: " << books[i].author << endl;
cout << "Publication Year: " << books[i].year << endl;
cout << "Price: $" << books[i].price << endl;
cout << "Publisher: " << books[i].publisher << endl;
cout << "----------------------------" << endl;
}
return 0;
}

7
>_ Prompt >_ Output
Enter details for Book 1: ===== BOOK INFORMATION =====
Title: C++ Programming
Author: Bjarne Stroustrup Book 1:
Publication Year: 2000 Title: C++ Programming
Price: $45.99 Author: Bjarne Stroustrup
Publisher: Addison-Wesley Publication Year: 2000
Price: $45.99
Enter details for Book 2: Publisher: Addison-Wesley
Title: Data Structures ----------------------------
Author: Robert Lafore
Publication Year: 1998 Book 2:
Price: $39.50 Title: Data Structures
Publisher: Pearson Author: Robert Lafore
Publication Year: 1998
Enter details for Book 3: Price: $39.50
Title: Algorithms Publisher: Pearson
Author: Thomas Cormen ----------------------------
Publication Year: 2009
Price: $58.25 Book 3:
Publisher: MIT Press Title: Algorithms
Author: Thomas Cormen
Enter details for Book 4: Publication Year: 2009
Title: Clean Code Price: $58.25
Author: Robert Martin Publisher: MIT Press
Publication Year: 2008 ----------------------------
Price: $42.75
Publisher: Prentice Hall Book 4:
Title: Clean Code
Enter details for Book 5: Author: Robert Martin
Title: Design Patterns Publication Year: 2008
Author: Erich Gamma Price: $42.75
Publication Year: 1994 Publisher: Prentice Hall
Price: $49.99 ----------------------------
Publisher: Addison-Wesley
Book 5:
Title: Design Patterns
Author: Erich Gamma
Publication Year: 1994
Price: $49.99
Publisher: Addison-Wesley
----------------------------

8
7 Program to Store Six Employee Information Using Union

PROGRAM.CPP
#include <iostream>
#include <string>
using namespace std;

union EmployeeID {
int num_id;
char text_id[10];
};

struct Employee {
string name;
EmployeeID id;
bool is_num_id; // true for numeric ID, false for text ID
};

int main() {

Employee emp[6];

// Input information for each employee


for(int i = 0; i < 6; i++) {
cout << "\nEmployee " << (i+1) << ":" << endl;

cout << "Name: ";


cin.ignore(i == 0 ? 0 : 1);
getline(cin, emp[i].name);

cout << "ID type (1=numeric, 0=text): ";


cin >> emp[i].is_num_id;

if(emp[i].is_num_id) {
cout << "Numeric ID: ";
cin >> emp[i].id.num_id;
} else {
cout << "Text ID: ";
cin >> emp[i].id.text_id;
}
}

// Display all employee information


cout << "\n===== EMPLOYEES =====\n";
for(int i = 0; i < 6; i++) {
cout << "\nEmployee " << (i+1) << ":" << endl;
cout << "Name: " << emp[i].name << endl;

if(emp[i].is_num_id) {
cout << "ID: " << emp[i].id.num_id << endl;
} else {
cout << "ID: " << emp[i].id.text_id << endl;
}
}

return 0;
}

9
>_ Output
Employee 1:
Name: John
ID type (1=numeric, 0=text): 1
Numeric ID: 101

Employee 2:
Name: Sara
ID type (1=numeric, 0=text): 0
Text ID: ABC123

[Input continues for 4 more employees...]

===== EMPLOYEES =====

Employee 1:
Name: John
ID: 101

Employee 2:
Name: Sara
ID: ABC123

[Output continues for 4 more employees...]

10
8 Simple Interest Using Call by Value and Reference

PROGRAM.CPP

#include <iostream>
using namespace std;

// Function to calculate simple interest using call by value


float calculateInterestByValue(float principal, float rate, float time) {
return (principal * rate * time) / 100;
}

// Function to calculate simple interest using call by reference


void calculateInterestByReference(float principal, float rate, float time,
float &interest) {
interest = (principal * rate * time) / 100;
}

int main() {
float principal, rate, time, interestByValue, interestByReference;

cout << "Enter principal amount: Rs ";


cin >> principal;

cout << "Enter rate of interest (% per annum): ";


cin >> rate;

cout << "Enter time period (in years): ";


cin >> time;

// Calculate interest using call by value


interestByValue = calculateInterestByValue(principal, rate, time);

// Calculate interest using call by reference


calculateInterestByReference(principal, rate, time, interestByReference);

cout << "\nResults:" << endl;


cout << "Simple Interest (by value): Rs " << interestByValue << endl;
cout << "Simple Interest (by reference): Rs " << interestByReference;

return 0;
}

>_ Output

Enter principal amount: Rs 5000


Enter rate of interest (% per annum): 6.5
Enter time period (in years): 3

Results:
Simple Interest (by value): Rs 975
Simple Interest (by reference): Rs 975

11
9 Sum and Average of Five Numbers Using Class and Objects

PROGRAM.CPP
#include <iostream>
using namespace std;

class Numbers {
private:
float n1, n2, n3, n4, n5;
float sum;
float average;

public:
// Function to input numbers
void inputNumbers() {
cout << "Enter five numbers:" << endl;
cin >> n1 >> n2 >> n3 >> n4 >> n5;
}

// Function to calculate sum


void calculateSum() {
sum = n1 + n2 + n3 + n4 + n5;
}

// Function to calculate average


void calculateAverage() {
average = sum / 5;
}

// Function to display results


void displayResults() {
cout << "\nResults:" << endl;
cout << "Sum: " << sum << endl;
cout << "Average: " << average << endl;
}
};

int main() {
Numbers numObj;

numObj.inputNumbers();
numObj.calculateSum();
numObj.calculateAverage();
numObj.displayResults();

return 0;
}

>_ Output
Enter five numbers: 10 20 30 40 50
Results:
Numbers entered: 10, 20, 30, 40, 50
Sum: 150
Average: 30

12
10 Multiply Two Numbers Using Private and Public Memb. Func.

PROGRAM.CPP
#include <iostream>
using namespace std;

class Calculator {
private:
// Private member function
float multiplyNumbers(float a, float b) {
return a * b;
}

public:
// Public member function that uses the private function
void getProductAndDisplay() {
float num1, num2, product;

cout << "Enter first number: ";


cin >> num1;

cout << "Enter second number: ";


cin >> num2;

// Call private member function


product = multiplyNumbers(num1, num2);

cout << "\nResult: ";


cout << num1 << " × " << num2 << " = " << product << endl;
}
};

int main() {
Calculator calc;

// We can only call the public function


calc.getProductAndDisplay();

// The following line would cause a compilation error because


// multiplyNumbers is private
// calc.multiplyNumbers(5, 10);

return 0;
}

>_ Output
Enter first number: 12.5
Enter second number: 4.5
Result: 12.5 × 4.5 = 56.25

13
11 Print Triangle Structure Using Scope Resolution Operator

PROGRAM.CPP
#include <iostream>
using namespace std;

class Pattern {
private:
int rows;

public:
// Constructor declaration
Pattern(int r);

// Function declaration
void printPattern();
};

// Constructor definition using scope resolution operator


Pattern::Pattern(int r) {
rows = r;
}

// Function definition using scope resolution operator


void Pattern::printPattern() {
for(int i = 1; i <= rows; i++) {
for(int j = 1; j <= i; j++) {
cout << j << " ";
}
cout << endl;
}
}

int main() {
// Create object with 5 rows
Pattern triangle(5);

cout << "Pattern Output:" << endl;


triangle.printPattern();

return 0;
}

>_ Output
Pattern Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

14
12 Program for Constructor and Destructor

PROGRAM.CPP
#include <iostream>
#include <string>
using namespace std;

class Student {
private:
int id;
string name;

public:
// Parameterized constructor
Student(int studentId, string studentName) {
id = studentId;
name = studentName;
}

// Function to display student information


void displayInfo() {
cout << "Student ID: " << id << ", Name: " << name << endl;
}

// Destructor
~Student() {
cout << "Destructor called for " << name << " with ID " << id;
}
};

int main() {
cout << "Creating students..." << endl;

// Using parameterized constructor


Student student1(101, "John Smith");
student1.displayInfo();

cout << "\n";

cout << "\nExiting main function..." << endl;

// Destructors will be called automatically when objects go out of scope


return 0;
}

>_ Output
Creating students...
Student ID: 101, Name: John Smith
Exiting main function...
Destructor called for John Smith with ID 101.

15
13 Program for Multiple Inheritance

PROGRAM.CPP

#include <iostream>
using namespace std;

// Base class 1
class Animal {
public:
void eat() {
cout << "Animal is eating" << endl;
}
};

// Base class 2
class Pet {
public:
void play() {
cout << "Pet is playing" << endl;
}
};

// Derived class inheriting from both Animal and Pet


class Dog : public Animal, public Pet {
public:
void bark() {
cout << "Dog is barking" << endl;
}
};

int main() {
Dog dog;
cout << "Demonstrating Multiple Inheritance:" << endl;
dog.eat(); // From Animal class
dog.play(); // From Pet class
dog.bark(); // From Dog class
return 0;
}

>_ Output
Demonstrating Multiple Inheritance:
Animal is eating
Pet is playing
Dog is barking

16
14 Program for Operator Overloading

PROGRAM.CPP
#include <iostream>
using namespace std;

class Point {
public:
int x, y;

Point(int x, int y) {
this->x = x;
this->y = y;
}

// Overload the + operator


Point operator + (const Point& other) {
return Point(x + other.x, y + other.y);
}
};

int main() {
Point p1(2, 3);
Point p2(4, 5);

Point result = p1 + p2; // Calls the overloaded operator+


cout << "P1: (" << p1.x << ", " << p1.y << ")" << endl;
cout << "P2: (" << p2.x << ", " << p2.y << ")" << endl;
cout << "Result: (" << result.x << ", " << result.y << ")" << endl;
return 0;
}

>_ Output
P1: (2, 3)
P2: (4, 5)
Result: (6, 8)

17
15 Program for Friend Function (15.1)

PROGRAM.CPP

#include <iostream>
using namespace std;

class A {
private:
int x = 10;

// Declare friend function


friend void show(A);
};

void show(A obj) {


// Can access private member x
cout << "Value of x: " << obj.x << endl;
}

int main() {
A obj;
show(obj);
return 0;
}

>_ Output
Value of x: 10

18
15 Program for Friend Class (15.2)

PROGRAM.CPP
#include <iostream>
using namespace std;

class B; // Forward declaration

class A {
private:
int x = 5;

// Declare class B as friend


friend class B;
};

class B {
public:
void display(A obj) {
cout << "Accessing A's private x: " << obj.x << endl;
}
};

int main() {
A obj;
B b;
b.display(obj);
return 0;
}

>_ Output
Accessing A’s private x: 5

19
16 Program for Virtual Function (16.1)

PROGRAM.CPP
#include <iostream>
using namespace std;

class Base {
public:
virtual void show() {
cout << "Base\n";
}
};

class Derived : public Base {


public:
void show() override {
cout << "Base Overridden: Derived Function\n";
}
};

int main() {
Base* bptr = new Derived();
bptr->show();
delete bptr;
return 0;
}

>_ Output
Base Overridden: Derived Function

20
16 Program for Virtual Class (16.2)

PROGRAM.CPP

#include <iostream>
using namespace std;

class A {
public:
void greet() {
cout << "Hello from A\n";
}
};

class B : virtual public A {}; // virtual inheritance


class C : virtual public A {}; // virtual inheritance

class D : public B, public C {};

int main() {
D obj;
obj.greet(); // Only one copy of A is inherited
return 0;
}

>_ Output
Hello from A

21
17 Program for Exception Handling

PROGRAM.CPP
#include <iostream>
using namespace std;

int divide(int numerator, int denominator) {


if (denominator == 0) {
throw "Division by zero error!";
}
return numerator / denominator;
}

int main() {
try {
// Attempt to divide 10 by 0
int result = divide(10, 0);
cout << "Result: " << result << endl;
} catch (const char* errorMsg) {
// Exception is caught and processed here
cerr << "Caught Exception: " << errorMsg << endl;
}

return 0;
}

>_ Output
Caught Exception: Division by zero error!

22
18 Program for File Handling

PROGRAM.CPP
#include <iostream>
#include <fstream> // for file handling
using namespace std;

int main() {
// 1. Writing to a file
ofstream outFile("example.txt"); // creates & opens file
outFile << "Hello, this is a file!\n";
outFile << "Welcome to C++ file handling.";
outFile.close(); // close the file

// 2. Reading from the same file


ifstream inFile("example.txt"); // open for reading
string line;

while (getline(inFile, line)) {


cout << line << endl; // print line by line
}
inFile.close(); // close the file

return 0;
}

>_ Output
Hello, this is a file!
Welcome to C++ file handling.

23
19 Merging Two Sorted Arrays

PROGRAM.CPP
#include <iostream>
using namespace std;

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

// Compare and merge elements


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

// Copy remaining elements from arr1


while (i < size1) {
result[k++] = arr1[i++];
}

// Copy remaining elements from arr2


while (j < size2) {
result[k++] = arr2[j++];
}
}

void printArray(int arr[], int size) {


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

int main() {
int arr1[] = {1, 3, 5, 7, 9};
const int size1 = sizeof(arr1) / sizeof(arr1[0]);

int arr2[] = {2, 4, 6, 8, 10};


const int size2 = sizeof(arr2) / sizeof(arr2[0]);

int merged[size1 + size2];

cout << "First array: "; printArray(arr1, size1);


cout << "Second array: "; printArray(arr2, size2);

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

cout << "Merged array: ";


printArray(merged, size1 + size2);

return 0;
}

24
>_ Output
First array: 1 3 5 7 9
Second array: 2 4 6 8 10
Merged array: 1 2 3 4 5 6 7 8 9 10

25
20 Program for Fibonacci Series (using recursion – 20.1)

PROGRAM.CPP
#include <iostream>
using namespace std;

// Fibonacci using recursion


int fibRecursive(int n) {
if (n <= 1) // Base Case
return n;
return fibRecursive(n-1) + fibRecursive(n-2);
}

int main() {
int n = 10;

cout << "Demonstrating Fibonacci Series:" << endl;

// Using recursion
cout << "Fibonacci Series (Recursive):";
for (int i = 0; i < n; i++) {
cout << " " << fibRecursive(i);
}
cout << endl;

return 0;
}

>_ Output
Demonstrating Fibonacci Series:
Fibonacci Series (Recursive): 0 1 1 2 3 5 8 13 21 34

26
20 Program for Fibonacci Series (using iteration – 20.2)

PROGRAM.CPP
#include <iostream>
using namespace std;

// Fibonacci using iteration


void fibIterative(int n) {
int t1 = 0, t2 = 1, nextTerm;

cout << "Fibonacci Series (Iterative):";


if (n >= 1) cout << " " << t1;
if (n >= 2) cout << " " << t2;

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


nextTerm = t1 + t2;
cout << " " << nextTerm;
t1 = t2;
t2 = nextTerm;
}
cout << endl;
}

int main() {
int n = 10;

cout << "Demonstrating Fibonacci Series:" << endl;

// Using iteration
fibIterative(n);

return 0;
}

>_ Output
Demonstrating Fibonacci Series:
Fibonacci Series (Iterative): 0 1 1 2 3 5 8 13 21 34

27
21 Program for Factorial (using recursion – 21.1)

PROGRAM.CPP

#include <iostream>
using namespace std;

// Factorial using recursion


unsigned long long factorialRecursive(int n) {
if (n <= 1)
return 1;
return n * factorialRecursive(n - 1);
}

int main() {
int num = 5;

cout << "Demonstrating Factorial Calculation:" << endl;

// Using recursion
cout << "Factorial of " << num << " using recursion: ";
cout << factorialRecursive(num) << endl;

return 0;
}

>_ Output
Demonstrating Factorial Calculation:
Factorial of 10 using recursion: 120

28
21 Program for Factorial (using iteration – 21.2)

PROGRAM.CPP
#include <iostream>
using namespace std;

// Factorial using iteration


unsigned long long factorialIterative(int n) {
unsigned long long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}

int main() {
int num = 5;

cout << "Demonstrating Factorial Calculation:" << endl;

// Using iteration
cout << "Factorial of " << num << " using iteration: ";
cout << factorialIterative(num) << endl;

return 0;
}

>_ Output
Demonstrating Factorial Calculation:
Factorial of 10 using iteration: 120

29
22 Program for GCD (using recursion – 22.1)

PROGRAM.CPP

#include <iostream>
using namespace std;

// GCD using recursion (Euclidean algorithm)


int gcdRecursive(int a, int b) {
if (b == 0)
return a;
return gcdRecursive(b, a % b);
}

int main() {
int num1 = 48, num2 = 18;

cout << "Demonstrating GCD Calculation:" << endl;


cout << "Numbers: " << num1 << " and " << num2 << endl;

// Using recursion
cout << "GCD using recursion: " << gcdRecursive(num1, num2) << endl;

return 0;
}

>_ Output
Demonstrating GCD Calculation:
Numbers: 48 and 18
GCD using recursion: 6

30
22 Program for GCD (without recursion – 22.2)

PROGRAM.CPP
#include <iostream>
using namespace std;

// GCD without recursion


int gcdIterative(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}

int main() {
int num1 = 48, num2 = 18;

cout << "Demonstrating GCD Calculation:" << endl;


cout << "Numbers: " << num1 << " and " << num2 << endl;

// Without recursion
cout << "GCD without recursion: " << gcdIterative(num1, num2) << endl;

return 0;
}

>_ Output
Demonstrating GCD Calculation:
Numbers: 48 and 18
GCD without recursion: 6

31
23 Coming Soon.....

PROGRAM.CPP
#include <iostream>
using namespace std;

// GCD without recursion


int gcdIterative(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}

int main() {
int num1 = 48, num2 = 18;

cout << "Demonstrating GCD Calculation:" << endl;


cout << "Numbers: " << num1 << " and " << num2 << endl;

// Without recursion
cout << "GCD without recursion: " << gcdIterative(num1, num2) << endl;

return 0;
}

>_ Output
Demonstrating GCD Calculation:
Numbers: 48 and 18
GCD without recursion: 6

32
24 Triangle Class with Operator Overloading

PROGRAM.CPP
#include <iostream>
#include <cmath>
using namespace std;

class Triangle {
private:
double side1, side2, side3;

public:
// Constructor
Triangle(double s1 = 0, double s2 = 0, double s3 = 0)
: side1(s1), side2(s2), side3(s3) {

// Validate triangle inequality theorem


if (!isValid()) {
cout << "Warning: These sides do not form a valid triangle.
Setting to default." << endl;
side1 = side2 = side3 = 0;
}
}

// Check if triangle is valid


bool isValid() const {
return (side1 + side2 > side3) &&
(side1 + side3 > side2) &&
(side2 + side3 > side1);
}

// Calculate area using Heron's formula


double area() const {
if (side1 == 0 || side2 == 0 || side3 == 0)
return 0;

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


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

// Overload assignment operator


Triangle& operator=(const Triangle& t) {
if (this != &t) {
side1 = t.side1;
side2 = t.side2;
side3 = t.side3;
}
return *this;
}

33
// Overload equality operator
bool operator==(const Triangle& t) const {
// Triangles are equal if they have the same set of sides (in any
order)
return ((side1 == t.side1 && side2 == t.side2 && side3 == t.side3) ||
(side1 == t.side1 && side2 == t.side3 && side3 == t.side2) ||
(side1 == t.side2 && side2 == t.side1 && side3 == t.side3) ||
(side1 == t.side2 && side2 == t.side3 && side3 == t.side1) ||
(side1 == t.side3 && side2 == t.side1 && side3 == t.side2) ||
(side1 == t.side3 && side2 == t.side2 && side3 == t.side1));
}

// Display triangle info


void display() const {
cout << "Triangle sides: " << side1 << ", " << side2 << ", " << side3
<< endl;
cout << "Area: " << area() << endl;
}
};

int main() {
cout << "Demonstrating Triangle Class with Operator Overloading:" <<
endl;

Triangle t1(3, 4, 5);


cout << "Triangle t1:" << endl;
t1.display();

Triangle t2(5, 12, 13);


cout << "\nTriangle t2:" << endl;
t2.display();

Triangle t3;
cout << "\nAssigning t2 to t3:" << endl;
t3 = t2;
t3.display();

cout << "\nChecking equality:" << endl;


cout << "t1 == t2: " << (t1 == t2 ? "true" : "false") << endl;
cout << "t2 == t3: " << (t2 == t3 ? "true" : "false") << endl;

// Try invalid triangle


cout << "\nTrying to create invalid triangle:" << endl;
Triangle invalid(1, 1, 10);
invalid.display();

return 0;
}

>_ Output
Demonstrating Triangle Class with Operator Overloading:
Triangle t1:
Triangle sides: 3, 4, 5
Area: 6

Triangle t2:
Triangle sides: 5, 12, 13

34
Area: 30

Assigning t2 to t3:
Triangle sides: 5, 12, 13
Area: 30

Checking equality:
t1 == t2: false
t2 == t3: true

Trying to create invalid triangle:


Warning: These sides do not form a valid triangle. Setting to default.
Triangle sides: 0, 0, 0
Area: 0

35
25 Box Class with Operator Overloading

PROGRAM.CPP
#include <iostream>
using namespace std;

class Box {
private:
double length, breadth, height;

public:
// Constructor
Box(double l = 0, double b = 0, double h = 0)
: length(l), breadth(b), height(h) {}

// Calculate surface area


double surfaceArea() const {
return 2 * (length * breadth + breadth * height + height * length);
}

// Calculate volume
double volume() const {
return length * breadth * height;
}

// Overload increment (++) operator (prefix)


Box& operator++() {
++length;
++breadth;
++height;
return *this;
}

// Overload increment (++) operator (postfix)


Box operator++(int) {
Box temp = *this;
++length;
++breadth;
++height;
return temp;
}

// Overload decrement (--) operator (prefix)


Box& operator--() {
--length;
--breadth;
--height;

// Ensure dimensions don't go negative


if (length < 0) length = 0;
if (breadth < 0) breadth = 0;
if (height < 0) height = 0;

return *this;
}

36
// Overload decrement (--) operator (postfix)
Box operator--(int) {
Box temp = *this;
--length;
--breadth;
--height;

// Ensure dimensions don't go negative


if (length < 0) length = 0;
if (breadth < 0) breadth = 0;
if (height < 0) height = 0;

return temp;
}

// Overload equality (==) operator


bool operator==(const Box& b) const {
return (length == b.length && breadth == b.breadth && height ==
b.height);
}

// Friend function to check if box is a cube


friend bool isCube(const Box& b);

// Overload assignment operator


Box& operator=(const Box& b) {
if (this != &b) {
length = b.length;
breadth = b.breadth;
height = b.height;
}
return *this;
}

// Display box info


void display() const {
cout << "Box dimensions: " << length << " x " << breadth << " x " <<
height << endl;
cout << "Surface Area: " << surfaceArea() << endl;
cout << "Volume: " << volume() << endl;
}
};

// Friend function to check if box is a cube


bool isCube(const Box& b) {
return (b.length == b.breadth && b.breadth == b.height);
}

int main() {
cout << "Demonstrating Box Class with Operator Overloading:" << endl;

Box b1(2, 3, 4);


cout << "Box b1:" << endl;
b1.display();

cout << "\nIncrementing b1 (prefix):" << endl;


++b1;
b1.display();

Box b2 = b1;

37
cout << "\nBox b2 (copy of b1):" << endl;
b2.display();

cout << "\nDecrementing b2 (postfix):" << endl;


Box b3 = b2--;
cout << "b3 (result of postfix decrement):" << endl;
b3.display();
cout << "b2 (after postfix decrement):" << endl;
b2.display();

cout << "\nChecking equality:" << endl;


cout << "b1 == b2: " << (b1 == b2 ? "true" : "false") << endl;
cout << "b2 == b3: " << (b2 == b3 ? "true" : "false") << endl;

Box cube(5, 5, 5);


cout << "\nIs cube a cube? " << (isCube(cube) ? "Yes" : "No") << endl;
cout << "Is b1 a cube? " << (isCube(b1) ? "Yes" : "No") << endl;

return 0;
}

>_ Output
Demonstrating Box Class with Operator Overloading:
Box b1:
Box dimensions: 2 x 3 x 4
Surface Area: 52
Volume: 24

Incrementing b1 (prefix):
Box dimensions: 3 x 4 x 5
Surface Area: 94
Volume: 60

Box b2 (copy of b1):


Box dimensions: 3 x 4 x 5
Surface Area: 94
Volume: 60

Decrementing b2 (postfix):
b3 (result of postfix decrement):
Box dimensions: 3 x 4 x 5
Surface Area: 94
Volume: 60
b2 (after postfix decrement):
Box dimensions: 2 x 3 x 4
Surface Area: 52
Volume: 24

Checking equality:
b1 == b2: false
b2 == b3: false

Is cube a cube? Yes


Is b1 a cube? No

38
26 Program for Student Struct

PROGRAM.CPP
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

// Structure definition for Student


struct Student {
int rollNo;
char name[50];
char className[20];
int year;
float totalMarks;
};

// Function to input student details


void inputStudent(Student &s) {
cout << "Enter Roll No.: ";
cin >> s.rollNo;
cin.ignore(); // Clear the input buffer

cout << "Enter Name: ";


cin.getline(s.name, 50);

cout << "Enter Class: ";


cin.getline(s.className, 20);

cout << "Enter Year: ";


cin >> s.year;

cout << "Enter Total Marks: ";


cin >> s.totalMarks;
}

// Function to display student details


void displayStudent(const Student &s) {
cout << "Roll No.: " << s.rollNo << endl;
cout << "Name: " << s.name << endl;
cout << "Class: " << s.className << endl;
cout << "Year: " << s.year << endl;
cout << "Total Marks: " << s.totalMarks << endl;
cout << "------------------------" << endl;
}

39
int main() {
Student students[10];
ofstream outFile;

// Open file for writing in binary mode


outFile.open("students.dat", ios::binary | ios::out);

if (!outFile) {
cerr << "Error opening file for writing!" << endl;
return 1;
}

cout << "Enter details for 10 students:" << endl;

// Input details for 10 students and write to file


for (int i = 0; i < 10; i++) {
cout << "\nStudent " << (i + 1) << ":" << endl;
inputStudent(students[i]);

// Write the student record to the file


outFile.write(reinterpret_cast<char*>(&students[i]),
sizeof(Student));
}

outFile.close();
cout << "\nStudent data has been successfully stored in 'students.dat'"
<< endl;

// Display all students to verify


cout << "\nStudent Details:" << endl;
cout << "------------------------" << endl;

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


cout << "Student " << (i + 1) << ":" << endl;
displayStudent(students[i]);
}

return 0;
}

>_ Output
Enter details for 10 students:

Student 1:
Enter Roll No.: 101
Enter Name: John Smith
Enter Class: 10A
Enter Year: 2023
Enter Total Marks: 450.5

Student 2:
Enter Roll No.: 102
Enter Name: Mary Johnson
Enter Class: 10A
Enter Year: 2023
Enter Total Marks: 487.75

40
Student 3:
Enter Roll No.: 103
Enter Name: Robert Williams
Enter Class: 10B
Enter Year: 2023
Enter Total Marks: 423.25

... (7 more students) ...

Student data has been successfully stored in 'students.dat'

Student Details:
------------------------
Student 1:
Roll No.: 101
Name: John Smith
Class: 10A
Year: 2023
Total Marks: 450.5
------------------------
Student 2:
Roll No.: 102
Name: Mary Johnson
Class: 10A
Year: 2023
Total Marks: 487.75
------------------------
... (8 more students) ...

41
27 Program for retrieve Student details

PROGRAM.CPP
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;

// Structure definition for Student (must match the structure in previous


program)
struct Student {
int rollNo;
char name[50];
char className[20];
int year;
float totalMarks;
};

int main() {
ifstream inFile;
Student student;

// Open file for reading in binary mode


inFile.open("students.dat", ios::binary | ios::in);

if (!inFile) {
cerr << "Error opening file for reading!" << endl;
return 1;
}

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


cout << "===============================================" << endl;
cout << left << setw(10) << "Roll No." << setw(25) << "Name" << setw(10)
<< "Marks" << endl;
cout << "-----------------------------------------------" << endl;

// Read student records from file and display in the specified format
while (inFile.read(reinterpret_cast<char*>(&student), sizeof(Student))) {
cout << left << setw(10) << student.rollNo
<< setw(25) << student.name
<< setw(10) << fixed << setprecision(2) << student.totalMarks <<
endl;
}

inFile.close();
cout << "===============================================" << endl;

return 0;
}

42
>_ Output
Student Information:
===============================================
Roll No. Name Marks
-----------------------------------------------
101 John Smith 450.50
102 Mary Johnson 487.75
103 Robert Williams 423.25
104 Sarah Davis 478.00
105 Michael Brown 431.75
106 Jennifer Garcia 492.25
107 David Martinez 445.50
108 Lisa Robinson 468.75
109 James Wilson 416.00
110 Patricia Taylor 463.25
===============================================

43
28 Copying File Content Without Whitespaces

PROGRAM.CPP
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
string sourceFileName, destFileName;
ifstream sourceFile;
ofstream destFile;
char ch;

// Get file names from user


cout << "Enter source file name: ";
getline(cin, sourceFileName);

cout << "Enter destination file name: ";


getline(cin, destFileName);

// Open source file for reading


sourceFile.open(sourceFileName);
if (!sourceFile) {
cerr << "Error opening source file: " << sourceFileName << endl;
return 1;
}

// Open destination file for writing


destFile.open(destFileName);
if (!destFile) {
cerr << "Error opening destination file: " << destFileName << endl;
sourceFile.close();
return 1;
}

cout << "Copying file and removing whitespaces..." << endl;

// Read each character from source file


while (sourceFile.get(ch)) {
// Write to destination file only if not a whitespace
if (!isspace(ch)) {
destFile.put(ch);
}
}

// Close both files


sourceFile.close();
destFile.close();

cout << "File copied successfully without whitespaces!" << endl;

// Display the contents of the destination file


cout << "\nContents of destination file:" << endl;
cout << "------------------------------" << endl;

ifstream readDestFile(destFileName);

44
string line;

while (getline(readDestFile, line)) {


cout << line << endl;
}

readDestFile.close();

return 0;
}

>_ Output
Enter source file name: source.txt
Enter destination file name: destination.txt
Copying file and removing whitespaces...
File copied successfully without whitespaces!

Contents of destination file:


------------------------------
Thisisasamplefilewithlinesoftext.
Allthewhitespaces,includingtabs,spaces,andnewlines,havebeenremoved.
Thisisusefulforsavingspaceandprocessingtext.

**Note: Assuming source.txt contains:


This is a sample file with lines of text.
All the whitespaces, including tabs, spaces, and newlines, have been
removed.
This is useful for saving space and processing text

45
30 Insert Data into File and Display

PROGRAM.CPP
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;

// Product structure for demonstration


struct Product {
int id;
char name[50];
double price;
int quantity;
};

// Function to display file menu


void displayMenu() {
cout << "\n==== File Operations Menu ====" << endl;
cout << "1. Create new file" << endl;
cout << "2. Insert data into file" << endl;
cout << "3. Display file contents" << endl;
cout << "4. Search for record" << endl;
cout << "5. Exit" << endl;
cout << "Enter your choice: ";
}

// Function to create a new file


void createFile(const string& filename) {
ofstream file(filename, ios::binary | ios::out);

if (!file) {
cerr << "Error creating file: " << filename << endl;
return;
}

cout << "File '" << filename << "' created successfully!" << endl;
file.close();
}

// Function to insert data into file


void insertData(const string& filename) {
ofstream file(filename, ios::binary | ios::app);

if (!file) {
cerr << "Error opening file for insertion: " << filename << endl;
return;
}

Product product;
char choice;

do {
cout << "\nEnter Product Details:" << endl;

cout << "ID: ";

46
cin >> product.id;
cin.ignore();

cout << "Name: ";


cin.getline(product.name, 50);

cout << "Price: ";


cin >> product.price;

cout << "Quantity: ";


cin >> product.quantity;

// Write the product to the file


file.write(reinterpret_cast<char*>(&product), sizeof(Product));

cout << "Record inserted successfully!" << endl;

cout << "Do you want to insert another record? (y/n): ";
cin >> choice;
cin.ignore();

} while (choice == 'y' || choice == 'Y');

file.close();
}

// Function to display file contents


void displayData(const string& filename) {
ifstream file(filename, ios::binary | ios::in);

if (!file) {
cerr << "Error opening file for reading: " << filename << endl;
return;
}

Product product;
bool found = false;

cout << "\n========== File Contents ==========" << endl;


cout << left << setw(5) << "ID" << setw(20) << "Name"
<< setw(10) << "Price" << setw(10) << "Quantity" << endl;
cout << "-----------------------------------" << endl;

// Read and display each product


while (file.read(reinterpret_cast<char*>(&product), sizeof(Product))) {
cout << left << setw(5) << product.id
<< setw(20) << product.name
<< fixed << setprecision(2) << setw(10) << product.price
<< setw(10) << product.quantity << endl;
found = true;
}

if (!found) {
cout << "No records found in the file." << endl;
}

cout << "====================================" << endl;


file.close();
}

47
// Function to search for a record
void searchRecord(const string& filename) {
ifstream file(filename, ios::binary | ios::in);

if (!file) {
cerr << "Error opening file for reading: " << filename << endl;
return;
}

int searchId;
cout << "Enter Product ID to search: ";
cin >> searchId;

Product product;
bool found = false;

// Search for the product with the given ID


while (file.read(reinterpret_cast<char*>(&product), sizeof(Product))) {
if (product.id == searchId) {
cout << "\n===== Product Found =====" << endl;
cout << "ID: " << product.id << endl;
cout << "Name: " << product.name << endl;
cout << "Price: $" << fixed << setprecision(2) << product.price
<< endl;
cout << "Quantity: " << product.quantity << endl;
cout << "========================" << endl;
found = true;
break;
}
}

if (!found) {
cout << "Product with ID " << searchId << " not found." << endl;
}

file.close();
}

int main() {
string filename;
int choice;

cout << "Enter filename to work with: ";


getline(cin, filename);

do {
displayMenu();
cin >> choice;
cin.ignore();

switch (choice) {
case 1:
createFile(filename);
break;

case 2:
insertData(filename);
break;

case 3:

48
displayData(filename);
break;

case 4:
searchRecord(filename);
break;

case 5:
cout << "Exiting program. Goodbye!" << endl;
break;

default:
cout << "Invalid choice. Please try again." << endl;
}

} while (choice != 5);

return 0;
}

>_ Output
Enter filename to work with: products.dat

==== File Operations Menu ====


1. Create new file
2. Insert data into file
3. Display file contents
4. Search for record
5. Exit
Enter your choice: 1
File 'products.dat' created successfully!

==== File Operations Menu ====


1. Create new file
2. Insert data into file
3. Display file contents
4. Search for record
5. Exit
Enter your choice: 2

Enter Product Details:


ID: 101
Name: Laptop
Price: 1299.99
Quantity: 5
Record inserted successfully!
Do you want to insert another record? (y/n): y

Enter Product Details:


ID: 102
Name: Smartphone
Price: 799.50
Quantity: 10
Record inserted successfully!
Do you want to insert another record? (y/n): y

Enter Product Details:


ID: 103

49
Name: Headphones
Price: 149.99
Quantity: 15
Record inserted successfully!
Do you want to insert another record? (y/n): n

==== File Operations Menu ====


1. Create new file
2. Insert data into file
3. Display file contents
4. Search for record
5. Exit
Enter your choice: 3

========== File Contents ==========


ID Name Price Quantity
-----------------------------------
101 Laptop 1299.99 5
102 Smartphone 799.50 10
103 Headphones 149.99 15
====================================

==== File Operations Menu ====


1. Create new file
2. Insert data into file
3. Display file contents
4. Search for record
5. Exit
Enter your choice: 4
Enter Product ID to search: 102

===== Product Found =====


ID: 102
Name: Smartphone
Price: $799.50
Quantity: 10
========================

==== File Operations Menu ====


1. Create new file
2. Insert data into file
3. Display file contents
4. Search for record
5. Exit
Enter your choice: 4
Enter Product ID to search: 105
Product with ID 105 not found.

==== File Operations Menu ====


1. Create new file
2. Insert data into file
3. Display file contents
4. Search for record
5. Exit
Enter your choice: 5
Exiting program. Goodbye!

50

You might also like