C++ Lab Assignment – Consolidated Questions (Q.1)–(Q.14)
This document combines all C++ lab questions (Q.1)–(Q.14) into a single assignment file. I have written the answers in simple student language.
Q.1) Class, Constructors & Destructor in C++
Question Q.1)
Write a program to demonstrate a class, use of constructor, constructor overloading and destructor.
Answer (written by Ansari Intesab, MCA 1st year)
For this question I took a simple example of a Student class. I used my own details (name, roll no, college etc.) so that the program looks more real and not just a generic example.
In the class I have shown:
- default constructor
- parameterized constructor
- constructor overloading
- destructor
Program: construct_destruct_demo.cpp
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int age;
int rollNo;
string course;
string college;
public:
// Default constructor
Student() {
name = "Unknown";
age = 0;
rollNo = 0;
course = "Not decided";
college = "Not decided";
cout << "Default constructor called" << endl;
}
// Parameterized constructor (full details)
Student(string n, int a, int r, string c, string clg) {
name = n;
age = a;
rollNo = r;
course = c;
college = clg;
cout << "Parameterized constructor called" << endl;
}
// Constructor overloading (only name and roll no)
Student(string n, int r) {
name = n;
rollNo = r;
age = 20; // my current age
course = "MCA 1st year"; // default for this constructor
college = "KBCNMU, Jalgaon";
cout << "Overloaded constructor (name, roll) called" << endl;
}
void display() {
cout << "Name : " << name << endl;
cout << "Age : " << age << endl;
cout << "Roll No : " << rollNo << endl;
cout << "Course : " << course << endl;
cout << "College : " << college << endl;
cout << "------------------------------" << endl;
}
// Destructor
~Student() {
cout << "Destructor called for: " << name << endl;
}
};
int main() {
// Object with default constructor
Student s1;
s1.display();
// Object with full details (using my real data)
Student s2("Ansari Intesab", 20, 1,
"MCA 1st year, 1st sem (2025-2026)",
"KBCNMU, Jalgaon");
s2.display();
// Object with overloaded constructor (only name and roll)
Student s3("Sumaira", 2);
s3.display();
return 0; // here all three destructors will be called
}Sample Output (approximate)
Default constructor called
Name : Unknown
Age : 0
Roll No : 0
Course : Not decided
College : Not decided
------------------------------
Parameterized constructor called
Name : Ansari Intesab
Age : 20
Roll No : 1
Course : MCA 1st year, 1st sem (2025-2026)
College : KBCNMU, Jalgaon
------------------------------
Overloaded constructor (name, roll) called
Name : Sumaira
Age : 20
Roll No : 2
Course : MCA 1st year
College : KBCNMU, Jalgaon
------------------------------
Destructor called for: Sumaira
Destructor called for: Ansari Intesab
Destructor called for: UnknownIn this way I have covered class, constructor, constructor overloading and destructor in one small program using my own information.
Q.2) Arrays, Strings, Pointers, Constants & References in C++
Question Q.2)
Write a program to demonstrate the use of arrays, strings, pointers, constants, and references in C++.
Concept Overview
In C++ we use arrays, strings, pointers, constants and references in almost every program. Here I took again a small student marks example, because it is easy to imagine for us as MCA students.
Program: array_pointer_demo.cpp
#include <iostream>
#include <string>
using namespace std;
// Function to calculate total using reference
void calculateTotal(const int marks[], int size, int &total) {
total = 0;
for (int i = 0; i < size; i++) {
total += marks[i];
}
}
int main() {
const int SUBJECTS = 5; // Constant value (fixed subjects)
string name;
cout << "Enter student name: ";
getline(cin, name); // Using string input
int marks[SUBJECTS]; // Array for marks
cout << "Enter marks for " << SUBJECTS << " subjects: " << endl;
for (int i = 0; i < SUBJECTS; i++) {
cout << "Subject " << (i + 1) << ": ";
cin >> marks[i];
}
// Using pointer to display marks
int *ptr = marks;
cout << "\nMarks entered (via pointer): ";
for (int i = 0; i < SUBJECTS; i++) {
cout << *(ptr + i) << " ";
}
cout << endl;
// Using reference to get total
int totalMarks;
calculateTotal(marks, SUBJECTS, totalMarks);
cout << "\nStudent Name: " << name << endl;
cout << "Total Marks: " << totalMarks << endl;
cout << "Percentage: " << (totalMarks / (float)SUBJECTS) << "%" << endl;
return 0;
}Sample Input (example)
Enter student name: Intesab Ansari
Enter marks for 5 subjects:
Subject 1: 80
Subject 2: 75
Subject 3: 90
Subject 4: 85
Subject 5: 88Sample Output (example)
Marks entered (via pointer): 80 75 90 85 88
Student Name: Intesab Ansari
Total Marks: 418
Percentage: 83.6%Explanation
- Array –
marksarray stores marks of 5 subjects. - String –
namevariable stores student name. - Pointer –
ptris a pointer which is used to print marks. - Constant –
SUBJECTSis constant, so subjects count is fixed. - Reference –
totalis passed by reference incalculateTotal, so the function can directly change it.
Q03. Operator Overloading in C++
Question 03:
Write a program to demonstrate the use of operator overloading.
Concept Overview
Operator overloading in C++ allows us to redefine existing operators (such as +, -, ==) for user-defined types like classes. This improves code readability and lets us use natural syntax with objects.
In this example, we create a Complex class and overload:
- the
+operator to add two complex numbers - the
==operator to compare two complex numbers
Program: operator_overloading.cpp
#include <iostream>
using namespace std;
class Complex {
private:
float real, imag;
public:
// Constructor
Complex(float r = 0, float i = 0) {
real = r;
imag = i;
}
// Overload + operator for addition
Complex operator+(const Complex &c) {
return Complex(real + c.real, imag + c.imag);
}
// Overload == operator for comparison
bool operator==(const Complex &c) {
return (real == c.real && imag == c.imag);
}
// Display function
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3, 2), c2(1, 7), c3;
cout << "Complex Number 1: ";
c1.display();
cout << "Complex Number 2: ";
c2.display();
// Using overloaded + operator
c3 = c1 + c2;
cout << "Result of Addition: ";
c3.display();
// Using overloaded == operator
if (c1 == c2) {
cout << "Both complex numbers are equal." << endl;
} else {
cout << "Complex numbers are not equal." << endl;
}
return 0;
}Sample Output
Complex Number 1: 3 + 2i
Complex Number 2: 1 + 7i
Result of Addition: 4 + 9i
Complex numbers are not equal.Explanation
- The
operator+function adds real parts and imaginary parts separately and returns the result as a newComplexobject. - The
operator==function checks whether both real and imaginary parts of two complex numbers are equal. - This makes the syntax
c1 + c2andc1 == c2work naturally withComplexobjects.
Q04. Use of Inheritance in C++
Question 04:
Write program(s) to demonstrate the use of inheritance.
Concept Overview
Inheritance allows a derived class to reuse and extend the properties and behavior of a base class. It supports code reusability and models real-life hierarchies.
In this example we use a small student result system with:
Person(base class): common properties such asnameandage.Student(derived fromPerson): addsrollNumber.Result(derived fromStudent): adds marks and percentage calculation.
Program: inheritance_demo.cpp
#include <iostream>
using namespace std;
// Base Class
class Person {
protected:
string name;
int age;
public:
Person(string n, int a) {
name = n;
age = a;
}
void displayPerson() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
// Derived Class 1
class Student : public Person {
protected:
int rollNumber;
public:
Student(string n, int a, int r) : Person(n, a) {
rollNumber = r;
}
void displayStudent() {
displayPerson();
cout << "Roll Number: " << rollNumber << endl;
}
};
// Derived Class 2
class Result : public Student {
private:
float marks1, marks2, marks3;
public:
Result(string n, int a, int r, float m1, float m2, float m3)
: Student(n, a, r) {
marks1 = m1;
marks2 = m2;
marks3 = m3;
}
void displayResult() {
displayStudent();
float total = marks1 + marks2 + marks3;
float percentage = total / 3;
cout << "Marks: " << marks1 << ", " << marks2 << ", " << marks3 << endl;
cout << "Total: " << total << endl;
cout << "Percentage: " << percentage << "%" << endl;
}
};
int main() {
Result r("Intesab Ansari", 23, 101, 78.5, 82.0, 90.0);
cout << "=== Student Result Information ===" << endl;
r.displayResult();
return 0;
}Sample Output
=== Student Result Information ===
Name: Intesab Ansari
Age: 23
Roll Number: 101
Marks: 78.5, 82, 90
Total: 250.5
Percentage: 83.5%Explanation
Resultindirectly inherits all members fromPersonviaStudent, demonstrating multi-level inheritance.- The program shows how common data (name, age) can be kept in a base class and reused by multiple derived classes.
Q05. Compile-time and Run-time Polymorphism in C++
Question 05:
Write a program to demonstrate the use of compile-time and run-time polymorphism.
Concept Overview
Polymorphism means “one name, many forms”. In C++ there are two main types:
- Compile-time polymorphism (early binding) – achieved using function overloading or operator overloading. The function to call is decided at compile time.
- Run-time polymorphism (late binding) – achieved using virtual functions and function overriding. The function to execute is decided at run time based on the actual object type.
Program: polymorphism_demo.cpp
#include <iostream>
using namespace std;
// ================= Compile-time Polymorphism =================
class Calculator {
public:
// Function Overloading
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
};
// ================= Run-time Polymorphism =================
class Shape {
public:
// Virtual Function
virtual void draw() {
cout << "Drawing a Shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a Circle" << endl;
}
};
class Rectangle : public Shape {
public:
void draw() override {
cout << "Drawing a Rectangle" << endl;
}
};
// ================= Main Function =================
int main() {
cout << "=== Compile-time Polymorphism Demo ===" << endl;
Calculator calc;
cout << "Add (int, int): " << calc.add(5, 10) << endl;
cout << "Add (double, double): " << calc.add(4.5, 3.2) << endl;
cout << "Add (int, int, int): " << calc.add(1, 2, 3) << endl;
cout << "\n=== Run-time Polymorphism Demo ===" << endl;
Shape* shape; // Base class pointer
Circle c;
Rectangle r;
shape = &c;
shape->draw(); // Calls Circle's draw()
shape = &r;
shape->draw(); // Calls Rectangle's draw()
return 0;
}Sample Output
=== Compile-time Polymorphism Demo ===
Add (int, int): 15
Add (double, double): 7.7
Add (int, int, int): 6
=== Run-time Polymorphism Demo ===
Drawing a Circle
Drawing a RectangleExplanation
- Compile-time polymorphism: the
Calculatorclass overloads theaddfunction with different parameter lists. The compiler selects the correct version based on the arguments. - Run-time polymorphism: the base class
Shapedeclares avirtualfunctiondraw. The derived classesCircleandRectangleoverride it. A base-class pointer calls the correctdrawmethod depending on the object it points to at run time.
Q06. Friend Function and Friend Class in C++
Question 06:
Write a program to demonstrate the use of friend function and friend class.
Concept Overview
In C++, friend functions and friend classes are allowed to access the private and protected members of a class. This is useful when closely related functions or classes need direct access without exposing data through many getters and setters.
- Friend function – a non-member function which is given access to private data of a class.
- Friend class – a class that is allowed to access private data of another class.
Program: friend_demo.cpp
#include <iostream>
using namespace std;
// ================= Friend Function Demo =================
class Box {
private:
int length;
public:
Box(int l) : length(l) {}
// Friend Function declaration
friend void printLength(Box b);
};
// Friend Function Definition
void printLength(Box b) {
cout << "Length of the box: " << b.length << endl;
}
// ================= Friend Class Demo =================
class Engine {
private:
int horsepower;
public:
Engine(int hp) : horsepower(hp) {}
// Declaring Car as a friend class
friend class Car;
};
class Car {
public:
void showEnginePower(Engine e) {
cout << "Car engine horsepower: " << e.horsepower << " HP" << endl;
}
};
// ================= Main Function =================
int main() {
cout << "=== Friend Function Demo ===" << endl;
Box b1(15);
printLength(b1); // Friend function accessing private member
cout << "\n=== Friend Class Demo ===" << endl;
Engine e1(120);
Car c1;
c1.showEnginePower(e1); // Friend class accessing private member
return 0;
}Sample Output
=== Friend Function Demo ===
Length of the box: 15
=== Friend Class Demo ===
Car engine horsepower: 120 HPExplanation
printLengthis a friend function of classBox. It can access the private memberlengthdirectly.Caris declared as a friend class ofEngine, allowing it to access the private memberhorsepower.
Q07. Virtual Class (Virtual Base Class) in C++
Question 07:
Write a program to demonstrate the use of virtual class (virtual base class).
Concept Overview
When using multiple inheritance, the same base class can be inherited through multiple paths, which can lead to duplicate copies of base class members in the final derived class. This is known as the diamond problem.
To solve this, C++ provides virtual base classes. When a class is inherited virtually, only one shared base-class subobject is created.
Program: virtual_class_demo.cpp
#include <iostream>
using namespace std;
// Base class
class Person {
public:
string name;
int age;
Person(string n, int a) : name(n), age(a) {}
void displayPerson() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
// Derived virtually
class Student : virtual public Person {
public:
int rollNo;
Student(string n, int a, int r) : Person(n, a), rollNo(r) {}
void displayStudent() {
cout << "Roll No: " << rollNo << endl;
}
};
// Derived virtually
class Employee : virtual public Person {
public:
string company;
Employee(string n, int a, string c) : Person(n, a), company(c) {}
void displayEmployee() {
cout << "Company: " << company << endl;
}
};
// Derived from both Student and Employee
class WorkingStudent : public Student, public Employee {
public:
WorkingStudent(string n, int a, int r, string c)
: Person(n, a), Student(n, a, r), Employee(n, a, c) {}
void display() {
displayPerson();
displayStudent();
displayEmployee();
}
};
// ================= Main Function =================
int main() {
WorkingStudent ws("Intesab Ansari", 24, 101, "Taqdis Computers");
cout << "=== Virtual Class Demo ===" << endl;
ws.display();
return 0;
}Sample Output
=== Virtual Class Demo ===
Name: Intesab Ansari, Age: 24
Roll No: 101
Company: Taqdis ComputersExplanation
Personis inherited virtually by bothStudentandEmployee.WorkingStudentinherits from bothStudentandEmployeebut holds only onePersonsubobject.- This avoids duplication of
nameandageand resolves ambiguity.
Q08. Static Data Member and Static Member Function in C++
Question 08:
Write a program to demonstrate the use of static data member and static member function.
Concept Overview
- A static data member is shared among all objects of a class. There is only one copy of it for the entire class.
- A static member function can be called using the class name and can only access static members directly.
This is helpful for keeping track of information that is common to all objects, such as a count of created objects.
Program: static_member_demo.cpp
#include <iostream>
using namespace std;
class Student {
private:
string name;
int rollNo;
// Static data member
static int studentCount;
public:
// Constructor
Student(string n, int r) : name(n), rollNo(r) {
studentCount++; // increment count whenever a new object is created
}
void display() {
cout << "Name: " << name << ", Roll No: " << rollNo << endl;
}
// Static member function
static void showCount() {
cout << "Total Students: " << studentCount << endl;
}
};
// Static data member must be defined outside the class
int Student::studentCount = 0;
int main() {
Student s1("Intesab Ansari", 101);
Student s2("Sumaira Khan", 102);
Student s3("Rahul Sharma", 103);
cout << "=== Student Records ===" << endl;
s1.display();
s2.display();
s3.display();
cout << "\n=== Using Static Function ===" << endl;
Student::showCount(); // call static function without any object
return 0;
}Sample Output
=== Student Records ===
Name: Intesab Ansari, Roll No: 101
Name: Sumaira Khan, Roll No: 102
Name: Rahul Sharma, Roll No: 103
=== Using Static Function ===
Total Students: 3Explanation
studentCountis a static variable that counts how manyStudentobjects have been created.Student::showCount()is called using the class name, not any particular object.
Q09. File Handling in C++
Question 09:
Write a program to demonstrate file handling.
Concept Overview
File handling allows a program to store data in files and read it back later. In C++, file handling is supported by the <fstream> header which provides three key classes:
ofstream– to write data to a file.ifstream– to read data from a file.fstream– to both read and write.
Program: file_handling_demo.cpp
#include <iostream>
#include <fstream>
using namespace std;
int main() {
string name;
int rollNo;
float marks;
// Writing data to a file
ofstream outFile("student.txt"); // create/open file
if (!outFile) {
cout << "File could not be opened for writing!" << endl;
return 1;
}
cout << "Enter Student Name: ";
getline(cin, name);
cout << "Enter Roll No: ";
cin >> rollNo;
cout << "Enter Marks: ";
cin >> marks;
outFile << "Name: " << name << endl;
outFile << "Roll No: " << rollNo << endl;
outFile << "Marks: " << marks << endl;
outFile.close(); // always close the file
cout << "\nData successfully written to student.txt\n" << endl;
// Reading data from the file
ifstream inFile("student.txt");
if (!inFile) {
cout << "File could not be opened for reading!" << endl;
return 1;
}
cout << "=== Reading Data from File ===" << endl;
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
return 0;
}Sample Output
Enter Student Name: Intesab Ansari
Enter Roll No: 101
Enter Marks: 89.5
Data successfully written to student.txt
=== Reading Data from File ===
Name: Intesab Ansari
Roll No: 101
Marks: 89.5Explanation
- The program writes student details to a file
student.txtand then reads the same file back. ofstreamis used for writing andifstreamfor reading.
Q10. Function Templates in C++
Question 10:
Write a program to demonstrate the use of function templates.
Concept Overview
Function templates allow writing generic functions that work with different data types without duplicating code. The compiler generates the appropriate function definition based on the type used.
Program: function_template_demo.cpp
#include <iostream>
using namespace std;
// Template function
template <typename T>
T getMax(T a, T b) {
return (a > b) ? a : b;
}
int main() {
// Integers
int x = 10, y = 20;
cout << "Max of " << x << " and " << y << " is: " << getMax(x, y) << endl;
// Floats
float p = 12.5f, q = 9.8f;
cout << "Max of " << p << " and " << q << " is: " << getMax(p, q) << endl;
// Characters
char c1 = 'A', c2 = 'Z';
cout << "Max of '" << c1 << "' and '" << c2 << "' is: " << getMax(c1, c2) << endl;
// Strings (lexicographical comparison)
string s1 = "Apple", s2 = "Banana";
cout << "Max of \"" << s1 << "\" and \"" << s2 << "\" is: " << getMax(s1, s2) << endl;
return 0;
}Sample Output
Max of 10 and 20 is: 20
Max of 12.5 and 9.8 is: 12.5
Max of 'A' and 'Z' is: Z
Max of "Apple" and "Banana" is: BananaExplanation
template <typename T>declares a generic typeT.- The same function
getMaxis used forint,float,char, andstring.
Q11. Class Templates in C++
Question 11:
Write a program to demonstrate the use of class templates.
Concept Overview
Class templates are used to create generic classes that can work with different data types. Instead of writing separate classes for int, float, etc., we write one template class and instantiate it with different types.
Program: class_template_demo.cpp
#include <iostream>
using namespace std;
// Template Class
template <typename T>
class Calculator {
private:
T num1, num2;
public:
// Constructor
Calculator(T a, T b) : num1(a), num2(b) {}
T add() { return num1 + num2; }
T subtract() { return num1 - num2; }
T multiply() { return num1 * num2; }
T divide() {
if (num2 != 0) {
return num1 / num2;
} else {
cout << "Error: Division by zero!" << endl;
return 0;
}
}
};
int main() {
// Integer calculator
Calculator<int> intCalc(20, 10);
cout << "Integer Addition: " << intCalc.add() << endl;
cout << "Integer Subtraction: " << intCalc.subtract() << endl;
cout << "Integer Multiplication: " << intCalc.multiply() << endl;
cout << "Integer Division: " << intCalc.divide() << endl;
// Float calculator
Calculator<float> floatCalc(5.5f, 2.2f);
cout << "\nFloat Addition: " << floatCalc.add() << endl;
cout << "Float Subtraction: " << floatCalc.subtract() << endl;
cout << "Float Multiplication: " << floatCalc.multiply() << endl;
cout << "Float Division: " << floatCalc.divide() << endl;
return 0;
}Sample Output
Integer Addition: 30
Integer Subtraction: 10
Integer Multiplication: 200
Integer Division: 2
Float Addition: 7.7
Float Subtraction: 3.3
Float Multiplication: 12.1
Float Division: 2.5Explanation
Calculator<T>is a generic class that supports any numeric typeT.- The same class is used for integer and floating-point arithmetic.
Q12. Exception Handling in C++
Question 12:
Write a program to demonstrate the use of exception handling.
Concept Overview
Exception handling allows a program to handle runtime errors gracefully without crashing. C++ provides try, throw, and catch keywords for this purpose.
Program: exception_handling_demo.cpp
#include <iostream>
#include <stdexcept> // for runtime_error
using namespace std;
class Student {
private:
string name;
int marks;
public:
Student(string n, int m) {
if (m < 0 || m > 100) {
throw runtime_error("Invalid marks! Marks must be between 0 and 100.");
}
name = n;
marks = m;
}
void display() {
cout << "Student: " << name << ", Marks: " << marks << endl;
}
};
int main() {
try {
cout << "Creating student objects..." << endl;
Student s1("Rahul", 85);
s1.display();
// Invalid marks, will throw exception
Student s2("Intesab", 120);
s2.display();
}
catch (runtime_error &e) {
cout << "Exception Caught: " << e.what() << endl;
}
catch (...) {
cout << "Unknown exception occurred!" << endl;
}
cout << "Program continues after exception handling..." << endl;
return 0;
}Sample Output
Creating student objects...
Student: Rahul, Marks: 85
Exception Caught: Invalid marks! Marks must be between 0 and 100.
Program continues after exception handling...Explanation
- The constructor of
Studentthrows aruntime_errorif marks are outside the range 0–100. - The
tryblock contains code that may throw exceptions. - The
catchblocks handle the exception and display a meaningful message. - Program execution continues normally after the exception is handled.
Q13. Command Line Arguments in C++
Question 13:
Write a program to demonstrate command line arguments.
Concept Overview
Command line arguments allow us to pass input values from the terminal directly to the program when it starts, instead of using cin. They are accessed using:
int main(int argc, char* argv[])argc– the total number of arguments (including the program name).argv– an array of C-style strings holding each argument.
Program: command_line_args.cpp
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
cout << "Total Arguments: " << argc << endl;
cout << "Program Name: " << argv[0] << endl;
if (argc > 1) {
cout << "Arguments Passed:" << endl;
for (int i = 1; i < argc; i++) {
cout << "Arg " << i << ": " << argv[i] << endl;
}
} else {
cout << "No extra arguments provided!" << endl;
}
return 0;
}How to Compile and Run
g++ command_line_args.cpp -o args_demo
./args_demo
./args_demo Intesab MCA-418 NMUExample Output
Total Arguments: 1
Program Name: ./args_demo
No extra arguments provided!Total Arguments: 4
Program Name: ./args_demo
Arguments Passed:
Arg 1: Intesab
Arg 2: MCA-418
Arg 3: NMUExplanation
- The user can run the same program with or without additional arguments.
- This technique is widely used in Linux utilities and scripting.
Q14. Use of STL in C++
Question 14:
Write program(s) to demonstrate the use of Standard Template Library (STL).
Concept Overview
The Standard Template Library (STL) provides ready-made containers, iterators, and algorithms that make C++ programming more efficient.
In this example we will use:
vector<int>as a dynamic array containersortandbinary_searchalgorithmsmap<int, string>as an associative container for key–value pairs
Program: stl_demo.cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
int main() {
// 1. Vector example
vector<int> numbers = {5, 2, 8, 1, 9};
cout << "Original Numbers: ";
for (int n : numbers) cout << n << " ";
cout << endl;
// Sort the vector
sort(numbers.begin(), numbers.end());
cout << "Sorted Numbers: ";
for (int n : numbers) cout << n << " ";
cout << endl;
// 2. Map example
map<int, string> students;
students[101] = "Intesab";
students[102] = "Rahul";
students[103] = "Sumaira";
cout << "\nStudent Records:" << endl;
for (auto &pair : students) {
cout << "Roll No: " << pair.first << " -> Name: " << pair.second << endl;
}
// 3. Algorithm example
int key = 8;
if (binary_search(numbers.begin(), numbers.end(), key)) {
cout << "\nElement " << key << " found in vector!" << endl;
} else {
cout << "\nElement " << key << " not found!" << endl;
}
return 0;
}Sample Output
Original Numbers: 5 2 8 1 9
Sorted Numbers: 1 2 5 8 9
Student Records:
Roll No: 101 -> Name: Intesab
Roll No: 102 -> Name: Rahul
Roll No: 103 -> Name: Sumaira
Element 8 found in vector!Explanation
vectorautomatically manages its size as elements are added or removed.mapstores data in key–value form, useful for things like roll-number-to-name mappings.sortandbinary_searchare efficient algorithms provided by STL.
End of consolidated C++ lab assignment.