0% found this document useful (0 votes)
20 views25 pages

CPP 5 Mark

The document contains a series of programming tasks and explanations related to C++ concepts, including object-oriented programming, data structures like linked lists, stacks, and queues, as well as dynamic memory allocation. It provides code examples for creating classes, implementing constructors, and performing operations such as searching in arrays and calculating the area of triangles. Additionally, it discusses key features of OOP and dynamic memory management in C++.

Uploaded by

Pratham Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views25 pages

CPP 5 Mark

The document contains a series of programming tasks and explanations related to C++ concepts, including object-oriented programming, data structures like linked lists, stacks, and queues, as well as dynamic memory allocation. It provides code examples for creating classes, implementing constructors, and performing operations such as searching in arrays and calculating the area of triangles. Additionally, it discusses key features of OOP and dynamic memory management in C++.

Uploaded by

Pratham Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

5 mark important question

1.Create a class Employee with data members empId, age, and salary. Write a
program to initialize the data members inside the main function and display them
using a member function definition outside the class.

#include <iostream>

using namespace std;

class Employee {

public:

int empId;

int age;

double salary;

// Function to display the employee details

void display() {

cout << "Employee ID: " << empId << endl;

cout << "Age: " << age << endl;

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

};

int main() {

Employee emp1;

// Initialize data members

emp1.empId = 101;

emp1.age = 30;

emp1.salary = 50000.50;

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
// Display employee details

emp1.display();

return 0;

2. Apply the concept of OOP to read three sides of a triangle. Calculate and display
the area of the triangle.

#include <iostream>

#include <cmath>

using namespace std;

class Triangle {

public:

double side1, side2, side3;

// Function to calculate the area using Heron's formula

double area() {

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

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

};

int main() {

Triangle t;

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

cin >> t.side1 >> t.side2 >> t.side3;

cout << "Area of the triangle: " << t.area() << endl;

return 0;

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
}

3. Write a C++ program to implement a linked list.

#include <iostream>

using namespace std;

class Node {

public:

int data;

Node* next;

Node(int val) {

data = val;

next = nullptr;

};

class LinkedList {

public:

Node* head;

LinkedList() {

head = nullptr;

// Function to insert a new node at the end

void insert(int val) {

Node* newNode = new Node(val);

if (head == nullptr) {

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
head = newNode;

} else {

Node* temp = head;

while (temp->next != nullptr) {

temp = temp->next;

temp->next = newNode;

// Function to display the linked list

void display() {

Node* temp = head;

while (temp != nullptr) {

cout << temp->data << " ";

temp = temp->next;

cout << endl;

};

int main() {

LinkedList list;

list.insert(10);

list.insert(20);

list.insert(30);

list.display();

return 0;

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
4.Explain the key features of object-oriented programming languages

Object-Oriented Programming (OOP) is a paradigm that revolves around the concept of


objects, which are instances of classes. It was developed to overcome the limitations of
procedural programming by providing a more organized and modular approach to software
design. OOP aims to make software more reusable, scalable, and maintainable. The key
features of object-oriented programming include:

1. Encapsulation: This is the process of bundling data (attributes) and methods


(functions) that operate on the data within a single unit called a class. Encapsulation
hides the internal state of an object and allows access only through specified methods
(getters and setters). This is critical in protecting data integrity and controlling how
data is accessed and modified.
2. Abstraction: Abstraction simplifies complex systems by focusing on the essential
characteristics while hiding unnecessary details. It allows the programmer to define
interfaces and interact with objects without needing to understand their internal
workings. This is achieved by using abstract classes and interfaces in many OOP
languages.
3. Inheritance: Inheritance allows a new class (child class) to inherit the properties and
behaviors (methods) of an existing class (parent class). This promotes code reuse and
establishes a hierarchy between classes. The child class can also override or extend
the functionality of the parent class.
4. Polymorphism: Polymorphism means "many shapes" and allows objects of different
classes to be treated as objects of a common superclass. It enables methods to take on
different forms, where the method's behavior depends on the object that invokes it.
Polymorphism can be achieved through method overriding and method overloading.
5. Classes and Objects: In OOP, a class serves as a blueprint for creating objects. An
object is an instance of a class, which contains real values for the attributes defined in
the class. Objects interact with each other through their methods and represent real-
world entities.
6. Message Passing: Objects in OOP communicate with each other by sending
messages. A message can be a request for an action or an instruction to invoke a
method on an object.

These features enable OOP to create more flexible, scalable, and easier-to-maintain systems.
They help in managing the complexity of large systems by providing a way to organize and
structure the code effectively.

5. Write a program to search for an element in an array using linear search.

#include <iostream>

using namespace std;

int linearSearch(int arr[], int size, int key) {

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

if (arr[i] == key) {

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
return i; // Element found

return -1; // Element not found

int main() {

int arr[] = {10, 20, 30, 40, 50};

int size = sizeof(arr) / sizeof(arr[0]);

int key = 30;

int index = linearSearch(arr, size, key);

if (index != -1) {

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

} else {

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

return 0;

6.Create a menu-driven program demonstrating the following operations on a


Queue: insert, delete, and display

#include <iostream>

using namespace std;

class Queue {

private:
Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU
Important question by MrDnobody
int arr[5];

int front, rear;

public:

Queue() {

front = -1;

rear = -1;

// Insert an element in the queue

void insert(int val) {

if (rear == 4) {

cout << "Queue Overflow!" << endl;

} else {

if (front == -1) front = 0;

arr[++rear] = val;

// Delete an element from the queue

void deleteElement() {

if (front == -1 || front > rear) {

cout << "Queue Underflow!" << endl;

} else {

cout << "Deleted element: " << arr[front++] << endl;

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
}

// Display the elements of the queue

void display() {

if (front == -1 || front > rear) {

cout << "Queue is empty!" << endl;

} else {

for (int i = front; i <= rear; i++) {

cout << arr[i] << " ";

cout << endl;

};

int main() {

Queue q;

int choice, value;

do {

cout << "\nMenu: \n1. Insert\n2. Delete\n3. Display\n4. Exit\nEnter your choice: ";

cin >> choice;

switch (choice) {

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
case 1:

cout << "Enter value to insert: ";

cin >> value;

q.insert(value);

break;

case 2:

q.deleteElement();

break;

case 3:

q.display();

break;

case 4:

break;

default:

cout << "Invalid choice!" << endl;

} while (choice != 4);

return 0;

7. Develop a menu-driven program demonstrating the following operations on


a Stack: push(), pop(), isEmpty(), isFull(), and display().

#include <iostream>

using namespace std;

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
class Stack {

private:

int arr[5];

int top;

public:

Stack() {

top = -1;

// Push operation

void push(int val) {

if (top == 4) {

cout << "Stack Overflow!" << endl;

} else {

arr[++top] = val;

cout << "Pushed " << val << endl;

// Pop operation

void pop() {

if (top == -1) {

cout << "Stack Underflow!" << endl;

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
} else {

cout << "Popped " << arr[top--] << endl;

// Check if the stack is empty

bool isEmpty() {

return top == -1;

// Check if the stack is full

bool isFull() {

return top == 4;

// Display the stack elements

void display() {

if (top == -1) {

cout << "Stack is empty!" << endl;

} else {

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

cout << arr[i] << " ";

cout << endl;

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
}

};

int main() {

Stack s;

int choice, value;

do {

cout << "\nMenu: \n1. Push\n2. Pop\n3. Display\n4. Check if Empty\n5. Check if
Full\n6. Exit\nEnter your choice: ";

cin >> choice;

switch (choice) {

case 1:

cout << "Enter value to push: ";

cin >> value;

s.push(value);

break;

case 2:

s.pop();

break;

case 3:

s.display();

break;

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
case 4:

cout << (s.isEmpty() ? "Stack is empty" : "Stack is not empty") << endl;

break;

case 5:

cout << (s.isFull() ? "Stack is full" : "Stack is not full") << endl;

break;

case 6:

break;

default:

cout << "Invalid choice!" << endl;

} while (choice != 6);

return 0;

8. Explain different types of constructors in C++ with examples.

In C++, constructors are special member functions that are invoked automatically when an
object of a class is created. The primary purpose of a constructor is to initialize the data
members of a new object. There are several types of constructors, each serving a specific
purpose in initializing objects in different ways:

1. Default Constructor:
A default constructor is a constructor that takes no arguments and provides default
values for the data members of the object. It is automatically called when an object is
created without any arguments

class Rectangle {

public:

int length, width;

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
// Default constructor

Rectangle() {

length = 5;

width = 10;

};

int main() {

Rectangle rect; // Default constructor called

cout << "Length: " << rect.length << ", Width: " << rect.width << endl;

return 0;

}
2. A parameterized constructor accepts arguments when an object is
created. This allows the user to initialize data members with specific
values at the time of object creation.

class Rectangle {

public:

int length, width;

// Parameterized constructor

Rectangle(int l, int w) {

length = l;

width = w;

};

int main() {

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
Rectangle rect(15, 20); // Parameterized constructor called

cout << "Length: " << rect.length << ", Width: " << rect.width << endl;

return 0;

3. A copy constructor is used to create a new object as a copy of an existing


object. It is invoked when an object is passed by value to a function,
returned by value from a function, or explicitly copied.

class Rectangle {

public:

int length, width;

// Parameterized constructor

Rectangle(int l, int w) {

length = l;

width = w;

// Copy constructor

Rectangle(const Rectangle& rect) {

length = rect.length;

width = rect.width;

};

int main() {

Rectangle rect1(10, 20); // Parameterized constructor

Rectangle rect2 = rect1; // Copy constructor called

cout << "Length: " << rect2.length << ", Width: " << rect2.width << endl;

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
return 0;

4. A dynamic constructor is used to allocate memory dynamically to


objects using new. It is typically used when the size of data members is
determined at runtime.

class Array {

public:

int* arr;

int size;

// Dynamic constructor

Array(int s) {

size = s;

arr = new int[size]; // Dynamic memory allocation

// Destructor to free memory

~Array() {

delete[] arr;

};

int main() {

Array arr1(5); // Dynamic constructor called

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

arr1.arr[i] = i + 1;

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
for (int i = 0; i < 5; i++) {

cout << arr1.arr[i] << " ";

return 0;

9. Define and explain dynamic memory allocation in C++.

Dynamic memory allocation is a process where memory is allocated during the program's
runtime, rather than at compile-time. In C++, this is done using
the new and delete operators. Dynamic memory allocation is useful when the size of the
memory required is not known in advance or changes during program execution.

The new operator is used to allocate memory for a single variable or an array on the heap.
The delete operator is used to free up the memory allocated using new to avoid memory
leaks.

#include <iostream>

using namespace std;

int main() {

int* ptr;

int n;

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

cin >> n;

// Dynamically allocating memory for an array of 'n' elements

ptr = new int[n];

// Initializing the array elements


Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU
Important question by MrDnobody
for (int i = 0; i < n; i++) {

ptr[i] = i + 1;

// Displaying the elements

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

cout << ptr[i] << " ";

cout << endl;

// Deleting the dynamically allocated memory

delete[] ptr;

return 0;

In the above example, memory for the integer array is allocated dynamically using
the new operator. After using the array, the delete[] operator frees the memory to avoid
memory leaks. Dynamic memory allocation allows you to create arrays of any size, even
when the size isn't known beforehand.

Dynamic memory management is crucial in C++ as it ensures optimal use of memory,


especially in large applications where the data size may change dynamically.

10. Explain the working of a stack and implement it using an array.

A stack is a linear data structure that follows the LIFO (Last In, First Out) principle. The last
element added to the stack is the first one to be removed. Operations performed on a stack
include:

1. Push: Adds an element to the stack.


2. Pop: Removes the element from the stack.
3. Peek: Views the top element without removing it.
4. IsEmpty: Checks if the stack is empty.
Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU
Important question by MrDnobody
5. IsFull: Checks if the stack is full (when the maximum capacity is reached).

#include <iostream>

using namespace std;

class Stack {

private:

int arr[5];

int top;

public:

Stack() {

top = -1;

// Push operation

void push(int value) {

if (top == 4) {

cout << "Stack Overflow!" << endl;

} else {

arr[++top] = value;

// Pop operation

void pop() {

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
if (top == -1) {

cout << "Stack Underflow!" << endl;

} else {

cout << "Popped: " << arr[top--] << endl;

// Display top element

void peek() {

if (top == -1) {

cout << "Stack is empty!" << endl;

} else {

cout << "Top element: " << arr[top] << endl;

// Check if the stack is empty

bool isEmpty() {

return top == -1;

// Check if the stack is full

bool isFull() {

return top == 4;

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
// Display stack contents

void display() {

if (top == -1) {

cout << "Stack is empty!" << endl;

} else {

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

cout << arr[i] << " ";

cout << endl;

};

int main() {

Stack s;

s.push(10);

s.push(20);

s.push(30);

s.display();

s.pop();

s.peek();

s.display();

return 0;

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
11. Explain polymorphism in object-oriented programming. Discuss its types

Polymorphism is one of the core concepts in Object-Oriented Programming (OOP). It allows


objects of different classes to be treated as objects of a common superclass, enabling the same
method or operation to behave differently depending on the type of object that invokes it.
Polymorphism enhances the flexibility and maintainability of code by allowing the same
interface to be used for different data types.

There are two types of polymorphism:

Compile-time Polymorphism (Static Polymorphism):

This type of polymorphism is resolved at compile-time. The most common


examples of compile-time polymorphism are function overloading and operator
overloading.

Function Overloading occurs when multiple functions with the same name exist
but differ in the number or type of parameters.

Operator Overloading allows existing operators to be used in new ways for user-
defined classes.

class Example {

public:

void display(int i) {

cout << "Integer: " << i << endl;

void display(double d) {

cout << "Double: " << d << endl;

};

2. Run-time Polymorphism (Dynamic Polymorphism):

• This type of polymorphism is resolved at runtime and is implemented


through function overriding and virtual functions.
• Function Overriding happens when a method in a derived class has the same
signature as a method in the base class but provides a different implementation.
• A function is marked as virtual in the base class, allowing the derived class's method
to be called at runtime, depending on the type of object that calls it.
• class Shape {
Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU
Important question by MrDnobody
• public:
• virtual void draw() {
• cout << "Drawing Shape" << endl;
• }
• };

• class Circle : public Shape {
• public:
• void draw() override {
• cout << "Drawing Circle" << endl;
• }
• };

• int main() {
• Shape* shape;
• Circle circle;
• shape = &circle;
• shape->draw(); // Calls Circle's draw method at runtime
• return 0;
• }

12.Create a class to calculate the area of a rectangle and square, using method
overloading.

#include <iostream>

using namespace std;

class Shape {

public:

// Method to calculate area of a rectangle

int area(int length, int width) {

return length * width;

// Method to calculate area of a square (overloaded method)

int area(int side) {

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
return side * side;

};

int main() {

Shape shape;

int rectangleArea = shape.area(5, 10); // Rectangle

int squareArea = shape.area(4); // Square

cout << "Area of Rectangle: " << rectangleArea << endl;

cout << "Area of Square: " << squareArea << endl;

return 0;

12. Define the concept of operator overloading in C++ with an example

Operator overloading allows you to define or modify the behavior of


operators in user-defined classes. It enables operators like +, -, *, [], and
others to work with objects of a class, as if they were built-in types.

#include <iostream>

using namespace std;

class Complex {

private:

int real, imag;

public:

// Constructor

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody
Complex(int r, int i) : real(r), imag(i) {}

// Overloading the '+' operator

Complex operator + (const Complex& other) {

return Complex(real + other.real, imag + other.imag);

// Function to display the complex number

void display() {

cout << real << " + " << imag << "i" << endl;

};

int main() {

Complex c1(3, 4), c2(1, 2);

Complex c3 = c1 + c2; // Calls the overloaded '+' operator

c3.display(); // Output: 4 + 6i

return 0;

Join my community : https://chat.whatsapp.com/K0fZdK8oYOTBJNulvKlbwU


Important question by MrDnobody

You might also like