CppAssignmentPDF
CppAssignmentPDF
PROGRAM.CPP
#include <iostream>
using namespace std;
int main() {
float num1, num2, sum;
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;
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 << "Factorial of " << number << " = " << factorial << endl;
}
return 0;
}
>_ Output
3
4 Program for Arithmetic Operations Using Switch Case
PROGRAM.CPP
#include <iostream>
using namespace std;
int main() {
float num1, num2, result;
char 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];
// 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];
}
}
}
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
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() {
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];
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;
}
}
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
Employee 1:
Name: John
ID: 101
Employee 2:
Name: Sara
ID: ABC123
10
8 Simple Interest Using Call by Value and Reference
PROGRAM.CPP
#include <iostream>
using namespace std;
int main() {
float principal, rate, time, interestByValue, interestByReference;
return 0;
}
>_ Output
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;
}
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;
int main() {
Calculator calc;
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();
};
int main() {
// Create object with 5 rows
Pattern triangle(5);
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;
}
// Destructor
~Student() {
cout << "Destructor called for " << name << " with ID " << id;
}
};
int main() {
cout << "Creating students..." << endl;
>_ 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;
}
};
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;
}
int main() {
Point p1(2, 3);
Point p2(4, 5);
>_ 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;
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 A {
private:
int x = 5;
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";
}
};
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";
}
};
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 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
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;
int main() {
int arr1[] = {1, 3, 5, 7, 9};
const int size1 = sizeof(arr1) / sizeof(arr1[0]);
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;
int main() {
int n = 10;
// 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;
int main() {
int n = 10;
// 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;
int main() {
int num = 5;
// 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;
int main() {
int num = 5;
// 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;
int main() {
int num1 = 48, num2 = 18;
// 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;
int main() {
int num1 = 48, num2 = 18;
// 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;
int main() {
int num1 = 48, num2 = 18;
// 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) {
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));
}
int main() {
cout << "Demonstrating Triangle Class with Operator Overloading:" <<
endl;
Triangle t3;
cout << "\nAssigning t2 to t3:" << endl;
t3 = t2;
t3.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
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 volume
double volume() const {
return length * breadth * height;
}
return *this;
}
36
// Overload decrement (--) operator (postfix)
Box operator--(int) {
Box temp = *this;
--length;
--breadth;
--height;
return temp;
}
int main() {
cout << "Demonstrating Box Class with Operator Overloading:" << endl;
Box b2 = b1;
37
cout << "\nBox b2 (copy of b1):" << endl;
b2.display();
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
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
38
26 Program for Student Struct
PROGRAM.CPP
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
39
int main() {
Student students[10];
ofstream outFile;
if (!outFile) {
cerr << "Error opening file for writing!" << endl;
return 1;
}
outFile.close();
cout << "\nStudent data has been successfully stored in 'students.dat'"
<< endl;
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
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;
int main() {
ifstream inFile;
Student student;
if (!inFile) {
cerr << "Error opening file for reading!" << endl;
return 1;
}
// 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;
ifstream readDestFile(destFileName);
44
string line;
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!
45
30 Insert Data into File and Display
PROGRAM.CPP
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
if (!file) {
cerr << "Error creating file: " << filename << endl;
return;
}
cout << "File '" << filename << "' created successfully!" << endl;
file.close();
}
if (!file) {
cerr << "Error opening file for insertion: " << filename << endl;
return;
}
Product product;
char choice;
do {
cout << "\nEnter Product Details:" << endl;
46
cin >> product.id;
cin.ignore();
cout << "Do you want to insert another record? (y/n): ";
cin >> choice;
cin.ignore();
file.close();
}
if (!file) {
cerr << "Error opening file for reading: " << filename << endl;
return;
}
Product product;
bool found = false;
if (!found) {
cout << "No records found in the file." << endl;
}
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;
if (!found) {
cout << "Product with ID " << searchId << " not found." << endl;
}
file.close();
}
int main() {
string filename;
int choice;
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;
}
return 0;
}
>_ Output
Enter filename to work with: products.dat
49
Name: Headphones
Price: 149.99
Quantity: 15
Record inserted successfully!
Do you want to insert another record? (y/n): n
50