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

dsaAssignment[1]

The document contains multiple C++ programs demonstrating various data structures and algorithms, including dynamic memory allocation, array manipulation, matrix operations, searching algorithms, and sorting techniques. Key functionalities include memory allocation with malloc, calloc, realloc, and free; array insertion, deletion, and traversal; matrix addition, subtraction, and multiplication; as well as linear search and sorting algorithms like selection, insertion, and quick sort. Each program includes user input for elements and displays the results of operations performed.

Uploaded by

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

dsaAssignment[1]

The document contains multiple C++ programs demonstrating various data structures and algorithms, including dynamic memory allocation, array manipulation, matrix operations, searching algorithms, and sorting techniques. Key functionalities include memory allocation with malloc, calloc, realloc, and free; array insertion, deletion, and traversal; matrix addition, subtraction, and multiplication; as well as linear search and sorting algorithms like selection, insertion, and quick sort. Each program includes user input for elements and displays the results of operations performed.

Uploaded by

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

GGNIMT

1.Program for using Dynamic Functions (malloc(),


calloc(), realloc() and free()) functions.
#include <iostream>

#include <cstdlib>

using namespace std;

int main() {

int n, new_n;

// Step 1: Allocate memory using malloc

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

cin >> n;

int* arr = (int*)malloc(n * sizeof(int));

if (arr == nullptr) {

cout << "Memory allocation failed using malloc.\n";

return 1;

cout << "Enter " << n << " elements: ";

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

cin >> arr[i];

cout << "Array elements (malloc): ";

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

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

cout << endl;

// Step 2: Allocate memory using calloc

int* c_arr = (int*)calloc(n, sizeof(int));

if (c_arr == nullptr) {

cout << "Memory allocation failed using calloc.\n";

1 | Page
GGNIMT

free(arr);

return 1;

cout << "Array elements (calloc, initialized to 0): ";

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

cout << c_arr[i] << " ";

cout << endl;

// Step 3: Reallocate memory using realloc

cout << "Enter the new size of the array: ";

cin >> new_n;

arr = (int*)realloc(arr, new_n * sizeof(int));

if (arr == nullptr) {

cout << "Memory reallocation failed.\n";

free(c_arr);

return 1;

if (new_n > n) {

cout << "Enter " << new_n - n << " additional elements: ";

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

cin >> arr[i];

cout << "Array elements after reallocation: ";

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

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

cout << endl;

2 | Page
GGNIMT

// Step 4: Free allocated memory

free(arr);

free(c_arr);

cout << "Memory successfully freed.\n";

return 0;

Output:

2. Program to insert, delete and traverse an element


from an array.
#include <iostream>

using namespace std;

void traverse(int arr[], int n) {

cout << "Array elements: ";

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

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

cout << endl;

void insertElement(int arr[], int& n, int pos, int value) {

3 | Page
GGNIMT

if (pos < 0 || pos > n) {

cout << "Invalid position!" << endl;

return;

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

arr[i] = arr[i - 1];

arr[pos] = value;

n++;

cout << "Element inserted." << endl;

void deleteElement(int arr[], int& n, int pos) {

if (pos < 0 || pos >= n) {

cout << "Invalid position!" << endl;

return;

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

arr[i] = arr[i + 1];

n--;

cout << "Element deleted." << endl;

int main() {

int arr[100], n;

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

cin >> n;

cout << "Enter the elements of the array:" << endl;

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

4 | Page
GGNIMT

cin >> arr[i];

// Traverse the array

traverse(arr, n);

int value, pos;

cout << "Enter the position to insert an element (0-indexed): ";

cin >> pos;

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

cin >> value;

insertElement(arr, n, pos, value);

// Traverse after insertion

traverse(arr, n);

cout << "Enter the position to delete an element (0-indexed): ";

cin >> pos;

deleteElement(arr, n, pos);

// Traverse after deletion

traverse(arr, n);

return 0;

Output:

5 | Page
GGNIMT

3. Program to merge one dimensional arrays.


#include <iostream>

using namespace std;

int main() {

int n1, n2;

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

cin >> n1;

int arr1[n1];

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

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

cin >> arr1[i];

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

cin >> n2;

int arr2[n2];

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

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

cin >> arr2[i];

// Create merged array

int merged[n1 + n2];

int k = 0;

// Copy elements from the first array

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

merged[k++] = arr1[i];

// Copy elements from the second array

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

6 | Page
GGNIMT

merged[k++] = arr2[i];

cout << "Merged array: ";

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

cout << merged[i] << " ";

cout << endl;

return 0;

Output:

4. Program for addition and subtraction of two matrices.


/* Addition and Subtraction of two matrices */

#include <iostream>

using namespace std;

void addMatrices(int rows, int cols, int mat1[][10], int mat2[][10], int
result[][10]) {

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

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

result[i][j] = mat1[i][j] + mat2[i][j];

}
7 | Page
GGNIMT

void subtractMatrices(int rows, int cols, int mat1[][10], int mat2[][10], int
result[][10]) {

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

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

result[i][j] = mat1[i][j] - mat2[i][j];

int main() {

int rows, cols;

cout << "Enter the number of rows and columns of the matrices: ";

cin >> rows >> cols;

int mat1[10][10], mat2[10][10], result[10][10];

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

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

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

cin >> mat1[i][j];

cout << "Enter elements of the second matrix:\n";

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

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

cin >> mat2[i][j];

addMatrices(rows, cols, mat1, mat2, result);

cout << "Result of matrix addition:\n";

8 | Page
GGNIMT

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

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

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

cout << endl;

subtractMatrices(rows, cols, mat1, mat2, result);

cout << "Result of matrix subtraction:\n";

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

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

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

cout << endl;

return 0;

Output:

9 | Page
GGNIMT

5. Program for implementing multiplication of two


matrices.
/* Multiplication of two matrices*/

#include <iostream>

using namespace std;

void multiplyMatrices(int mat1[][10], int mat2[][10], int result[][10], int


rows1, int cols1,int cols2) {

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

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

result[i][j] = 0;

for(int k = 0; k < cols1; k++) {

result[i][j] += mat1[i][k] * mat2[k][j];

}}}}

int main() {

int rows1, cols1, rows2, cols2;

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

cin >> rows1 >> cols1;

int mat1[10][10];

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

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

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

cin >> mat1[i][j];

}}

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

cin >> rows2 >> cols2;

if(cols1 != rows2) {

cout << "Matrix multiplication not possible. Number of columns in the


first matrix must be equal to the number of rows in the second matrix."
<< endl;

return 0;

10 | P a g e
GGNIMT

int mat2[10][10];

cout << "Enter elements of the second matrix:\n";

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

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

cin >> mat2[i][j];

}}

int result[10][10];

multiplyMatrices(mat1, mat2, result, rows1, cols1, cols2);

cout << "1st matrix:\n";

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

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

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

cout << endl;

cout << "2nd matrix:\n";

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

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

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

cout << endl;

cout << "Result of matrix multiplication:\n";

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

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

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

cout << endl;

11 | P a g e
GGNIMT

return 0;

Output:

6. Implement linear search using one and two


dimensional array.
#include <iostream>

using namespace std;

// Linear Search for One-Dimensional Array

int linearSearch1D(int arr[], int size, int target) {

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

if (arr[i] == target) {

return i; // Return the index if found

12 | P a g e
GGNIMT

return -1; // Return -1 if not found

// Linear Search for Two-Dimensional Array

int linearSearch2D(int arr[][3], int rows, int cols, int target) {

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

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

if (arr[i][j] == target) {

return i * cols + j; // Flatten the index

return -1; // Return -1 if not found

int main() {

int n, target;

// One-dimensional array input and search

cout << "Enter size of 1D array: ";

cin >> n;

int arr1[n];

cout << "Enter elements of 1D array: ";

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

cin >> arr1[i];

cout << "Enter target element to search in 1D: ";

cin >> target;

13 | P a g e
GGNIMT

int result1D = linearSearch1D(arr1, n, target);

if (result1D != -1) {

cout << "Element found at index " << result1D << " in 1D array.\n";

} else {

cout << "Element not found in 1D array.\n";

// Two-dimensional array input and search

int rows = 2, cols = 3;

int arr2[2][3]; // Fixed 2D array with 2 rows and 3 columns

cout << "Enter elements of 2D array (2x3):\n";

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

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

cin >> arr2[i][j];

cout << "Enter target element to search in 2D: ";

cin >> target;

int result2D = linearSearch2D(arr2, rows, cols, target);

if (result2D != -1) {

int row = result2D / cols; // Calculate row index

int col = result2D % cols; // Calculate column index

cout << "Element found at position (" << row << ", " << col << ")
in 2D array.\n";

} else {

cout << "Element not found in 2D array.\n";

14 | P a g e
GGNIMT

return 0;

Output:

7. Program for implementing selection sort.


#include <iostream>

using namespace std;

void selectionSort(int arr[], int n) {

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

int minIndex = i;

// Find the index of the minimum element

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

if (arr[j] < arr[minIndex]) {

minIndex = j;

// Swap the minimum element with the current element

15 | P a g e
GGNIMT

if (minIndex != i) {

swap(arr[i], arr[minIndex]);

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

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

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

cout << endl;

int main() {

int n;

cout << "Enter number of elements: ";

cin >> n;

int arr[n];

cout << "Enter the elements: ";

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

cin >> arr[i];

selectionSort(arr, n); // Perform selection sort

cout << "Sorted array: ";

printArray(arr, n); // Print sorted array

return 0;

Output:

16 | P a g e
GGNIMT

8. Program for implementing insertion sort.


#include <iostream>

using namespace std;

void insertionSort(int arr[], int n) {

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

int key = arr[i]; // The current element to insert

int j = i - 1;

// Shift elements greater than key to the right

while (j >= 0 && arr[j] > key) {

arr[j + 1] = arr[j];

j--;

// Place the key in its correct position

arr[j + 1] = key;

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

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

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

cout << endl;

int main() {

int n;

17 | P a g e
GGNIMT

cout << "Enter number of elements: ";

cin >> n;

int arr[n];

cout << "Enter elements: ";

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

cin >> arr[i];

insertionSort(arr, n);

cout << "Sorted array: ";

printArray(arr, n);

return 0;

Output:

9. Program for implementing quick sort.


#include <iostream>

using namespace std;

int partition(int arr[], int low, int high) {

int pivot = arr[high]; // Choose the last element as the pivot

int i = low - 1; // Index for the smaller element

for (int j = low; j < high; j++) {

// If current element is smaller than or equal to the pivot

if (arr[j] <= pivot) {

i++; // Increment index for the smaller element

swap(arr[i], arr[j]);

18 | P a g e
GGNIMT

// Swap the pivot element with the element at i+1

swap(arr[i + 1], arr[high]);

return i + 1; // Return the partition index

void quickSort(int arr[], int low, int high) {

if (low < high) {

int pi = partition(arr, low, high); // Partition the array

// Recursively sort elements before and after partition

quickSort(arr, low, pi - 1);

quickSort(arr, pi + 1, high);

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

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

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

cout << endl;

int main() {

int n;

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

cin >> n;

int arr[n];

cout << "Enter the elements: ";

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

cin >> arr[i];

19 | P a g e
GGNIMT

quickSort(arr, 0, n - 1);

cout << "Sorted array: ";

printArray(arr, n);

return 0;

Output:

10. Program for implementing merge sort.


#include <iostream>

using namespace std;

void merge(int arr[], int left, int mid, int right) {

int i = left, j = mid + 1, k = 0;

int temp[right - left + 1]; // Temporary array

// Merge elements from both halves

while (i <= mid && j <= right) {

if (arr[i] <= arr[j]) {

temp[k++] = arr[i++];

} else {

temp[k++] = arr[j++];

20 | P a g e
GGNIMT

// Copy remaining elements from the left half

while (i <= mid) {

temp[k++] = arr[i++];

// Copy remaining elements from the right half

while (j <= right) {

temp[k++] = arr[j++];

// Copy the merged array back to the original array

for (i = left, k = 0; i <= right; i++, k++) {

arr[i] = temp[k];

// Function to perform merge sort

void mergeSort(int arr[], int left, int right) {

if (left < right) {

int mid = left + (right - left) / 2;

// Recursively sort the two halves

mergeSort(arr, left, mid);

mergeSort(arr, mid + 1, right);

// Merge the sorted halves

merge(arr, left, mid, right);

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

21 | P a g e
GGNIMT

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

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

cout << endl;

int main() {

int n;

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

cin >> n;

int arr[n];

cout << "Enter the elements: ";

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

cin >> arr[i];

mergeSort(arr, 0, n - 1);

cout << "Sorted array: ";

printArray(arr, n);

return 0;

Output:

11. Program to calculate length of the string using user


defined function.
#include <iostream>

using namespace std;

22 | P a g e
GGNIMT

int stringLength(const char str[]) {

int length = 0;

// Traverse the string using a for loop

for (int i = 0; str[i] != '\0'; i++) {

length++;

return length;

int main() {

char str[100];

cout << "Enter a string: ";

cin.getline(str, 100);

int length = stringLength(str);

cout << "The length of the string is: " << length << endl;

return 0;

Output:

12. Program to concatenate and compare two strings


using user defined function.
#include <iostream>

#include <string>

using namespace std;

// Function to concatenate two strings


23 | P a g e
GGNIMT

string concatenate(const string& str1, const string& str2) {

return str1 + str2; // Simply use the '+' operator to concatenate

// Function to compare two strings

int compareStrings(const string& str1, const string& str2) {

if (str1 == str2) {

return 0; // Strings are equal

// Lexicographical comparison

if (str1 > str2) {

return 1; // str1 is greater than str2

else {

return -1; // str1 is less than str2

int main() {

string str1, str2;

cout << "Enter the first string: ";

getline(cin, str1);

cout << "Enter the second string: ";

getline(cin, str2);

string concatenated = concatenate(str1, str2);

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

// Compare the strings

int result = compareStrings(str1, str2);

if (result == 0) {

24 | P a g e
GGNIMT

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

} else if (result > 0) {

cout << "The first string is greater." << endl;

else{

cout << "The second string is greater." << endl;

return 0;

Output:
If one string is greater than other:

If both strings are equal:

13. Program for using the concept of pointer to string.


#include <iostream>

using namespace std;

int main() {

char str[] = "Hello, World!";

// Pointer to the first character of the string

char* ptr = str;

// Print the original string using the pointer

cout << "Original string: " << ptr << endl;

25 | P a g e
GGNIMT

// Modify the string using the pointer

ptr[7] = 'C'; // Change 'W' to 'C'

ptr[8] = 'P'; // Change 'o' to 'P'

ptr[9] = 'P'; // Change 'r' to 'P'

// Print the modified string

cout << "Modified string: " << ptr << endl;

// Access each character of the string using pointer arithmetic

cout << "Characters in the string: ";

for (int i = 0; ptr[i] != '\0'; i++) {

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

cout << endl;

// Pointer to a character (individual characters can also be accessed by


pointer)

char* p = &str[0]; // Points to the first character

cout << "First character: " << *p << endl; // Dereference the pointer to
get the value

return 0;

Output:

14. Program to reverse a sentence by recursion.


#include <iostream>

26 | P a g e
GGNIMT

#include <string>

using namespace std;

void reverseSentence(string& sentence, int start, int end) {

// Base case: if start is greater than or equal to end, stop the recursion

if (start >= end) {

return;

// Swap characters at the start and end positions

swap(sentence[start], sentence[end]);

// Recur with the next positions

reverseSentence(sentence, start + 1, end - 1);

int main() {

string sentence;

cout << "Enter a sentence: ";

getline(cin, sentence);

// Reverse the entire sentence using recursion

reverseSentence(sentence, 0, sentence.length() - 1);

cout << "Reversed sentence: " << sentence << endl;

return 0;

Output:

15. Program to delete all repeated words in string.


#include <iostream>

#include <sstream>

27 | P a g e
GGNIMT

#include <vector>

#include <string>

using namespace std;

int main() {

string str;

vector<string> words; // Vector to store words in the string

cout << "Enter string: ";

getline(cin, str); // Use getline to allow spaces in the input

stringstream ss(str); // Create a stringstream to split the string

string word;

// Split the string into words

while (ss >> word) {

words.push_back(word); // Add each word to the vector

// Remove duplicates

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

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

if (words[i] == words[j]) { // Compare words

words[j] = ""; // Mark duplicate words as empty

}}

// Display the result without duplicate words

cout << "Result is:" << endl;

for (const string& w : words) {

if (!w.empty()) { // Only print non-empty (non-duplicate) words

cout << w << " ";

cout << endl;

28 | P a g e
GGNIMT

return 0;

Output:

16. Program to find the number of vowels, consonants,


digits and white space in a string.
#include <iostream>

#include <cctype> // For isalpha, isdigit, isspace, tolower

using namespace std;

int main() {

string str;

int vowels = 0, consonants = 0, digits = 0, spaces = 0;

cout << "Enter a string: ";

getline(cin, str);

// Traverse the string

for (char ch : str) {

if (isalpha(ch)) { // Check if the character is an alphabet

char lower = tolower(ch); // Convert to lowercase for easier


comparison

if (lower == 'a' || lower == 'e' || lower == 'i' || lower == 'o' ||


lower == 'u') {

vowels++;

} else {

consonants++;

} else if (isdigit(ch)) { // Check if the character is a digit

digits++;

29 | P a g e
GGNIMT

} else if (isspace(ch)) { // Check if the character is a whitespace

spaces++;

cout << "Number of vowels: " << vowels << endl;

cout << "Number of consonants: " << consonants << endl;

cout << "Number of digits: " << digits << endl;

cout << "Number of white spaces: " << spaces << endl;

return 0;

Output:

17. Program to find highest and lowest frequency


character in a string.
#include <iostream>

#include <string>

#include <climits> // For INT_MIN and INT_MAX

using namespace std;

void findFrequency(string str) {

int highestFreq = INT_MIN, lowestFreq = INT_MAX;

char highestChar, lowestChar;

// Loop over all characters 'a' to 'z'

for (char ch = 'a'; ch <= 'z'; ch++) {

30 | P a g e
GGNIMT

int freq = 0;

// Count frequency of the current character in the string

for (char c : str) {

if (c == ch) {

freq++;

// Update highest and lowest frequency characters

if (freq > highestFreq) {

highestFreq = freq;

highestChar = ch;

if (freq > 0 && freq < lowestFreq) { // Ensure that the character is
present

lowestFreq = freq;

lowestChar = ch;

cout << "Highest frequency character: " << highestChar << " with
frequency " << highestFreq << endl;

cout << "Lowest frequency character: " << lowestChar << " with
frequency " << lowestFreq << endl;

int main() {

string str;

// Input the string

cout << "Enter a string: ";

getline(cin, str);

// Call the function to find highest and lowest frequency characters

findFrequency(str);

31 | P a g e
GGNIMT

return 0;

Output:

18. Program for implementing Stack using array.


#include <iostream>

using namespace std;

#define MAX 5 // Maximum size of the stack

class Stack {

private:

int arr[MAX];

int top;

public:

Stack() {

top = -1; // Stack is empty initially

bool isFull() {

return top == MAX - 1;

bool isEmpty() {

return top == -1;

void push(int value) {

if (isFull()) {

cout << "Stack Overflow! Cannot push " << value << endl;

} else {

32 | P a g e
GGNIMT

arr[++top] = value;

cout << value << " pushed to stack." << endl;

int pop() {

if (isEmpty()) {

cout << "Stack Underflow! Cannot pop." << endl;

return -1;

} else {

return arr[top--];

int peek() {

if (isEmpty()) {

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

return -1;

} else {

return arr[top];

};

int main() {

Stack stack;

stack.push(10);

stack.push(20);

stack.push(30);

stack.push(40);

stack.push(50);

33 | P a g e
GGNIMT

cout << "Top element is: " << stack.peek() << endl; // Should be 50

cout << "Popped element: " << stack.pop() << endl; // Should be 50

cout << "Top element is: " << stack.peek() << endl; // Should be 40

stack.push(60);

cout << "Top element is: " << stack.peek() << endl; // Should be 60

return 0;

Output:

19. Program for implementing Stack using pointer.


#include <iostream>

using namespace std;

class Stack {

private:

int *arr; // Pointer to array to hold stack elements

int top; // Index of the top element in the stack

int capacity; // Maximum capacity of the stack

public:

Stack(int size) {

capacity = size;

arr = new int[capacity]; // Dynamically allocate memory for stack

top = -1; // Stack is empty initially

34 | P a g e
GGNIMT

~Stack() {

delete[] arr; // Deallocate memory

bool isFull() {

return top == capacity - 1;

bool isEmpty() {

return top == -1;

void push(int value) {

if (isFull()) {

cout << "Stack Overflow! Cannot push " << value << endl;

} else {

arr[++top] = value;

cout << value << " pushed to stack." << endl;

int pop() {

if (isEmpty()) {

cout << "Stack Underflow! Cannot pop." << endl;

return -1;

} else {

return arr[top--];

int peek() {

if (isEmpty()) {

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

35 | P a g e
GGNIMT

return -1;

} else {

return arr[top];

} }};

int main() {

int size;

// Input the size of the stack

cout << "Enter the size of the stack: ";

cin >> size;

Stack stack(size);

// Demonstration of stack operations

stack.push(10);

stack.push(20);

stack.push(50);

cout << "Top element is: " << stack.peek() << endl;

cout << "Popped element: " << stack.pop() << endl;

cout << "Top element is: " << stack.peek() << endl;

stack.push(60);

cout << "Top element is: " << stack.peek() << endl;

return 0;

Output:

36 | P a g e
GGNIMT

20. Program for implementing multiple stack.


#include <iostream>

using namespace std;

class MultipleStacks {

private:

int *arr; // Pointer to the array that holds all stacks

int *top; // Pointer to track the top element for each stack

int capacity; // Total capacity of the array

int numStacks; // Number of stacks

public:

MultipleStacks(int size, int n) {

capacity = size;

numStacks = n;

arr = new int[capacity]; // Dynamically allocated array for all stacks

top = new int[numStacks]; // Array to hold the top index for each
stack

// Initialize all stacks to -1 (indicating empty)

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

top[i] = -1;

~MultipleStacks() {

37 | P a g e
GGNIMT

delete[] arr;

delete[] top;

bool isFull(int stackIndex) {

return top[stackIndex] == capacity / numStacks - 1;

bool isEmpty(int stackIndex) {

return top[stackIndex] == -1;

void push(int stackIndex, int value) {

if (isFull(stackIndex)) {

cout << "Stack " << stackIndex + 1 << " Overflow! Cannot push "
<< value << endl;

} else {

top[stackIndex]++;

arr[stackIndex * (capacity / numStacks) + top[stackIndex]] =


value;

cout << value << " pushed to stack " << stackIndex + 1 << endl;

int pop(int stackIndex) {

if (isEmpty(stackIndex)) {

cout << "Stack " << stackIndex + 1 << " Underflow! Cannot pop."
<< endl;

return -1;

} else {

int index = stackIndex * (capacity / numStacks) + top[stackIndex];

int poppedValue = arr[index];

top[stackIndex]--;

return poppedValue;

38 | P a g e
GGNIMT

int peek(int stackIndex) {

if (isEmpty(stackIndex)) {

cout << "Stack " << stackIndex + 1 << " is empty!" << endl;

return -1;

} else {

return arr[stackIndex * (capacity / numStacks) + top[stackIndex]];

} } };

int main() {

int size = 9; // Total capacity of the array

int n = 3; // Number of stacks

// Create multiple stacks

MultipleStacks stacks(size, n);

// Perform stack operations

stacks.push(0, 10); // Push to stack 1

stacks.push(1, 20); // Push to stack 2

stacks.push(2, 30); // Push to stack 3

stacks.push(0, 40); // Push to stack 1

stacks.push(1, 50); // Push to stack 2

cout << "Top element of stack 1: " << stacks.peek(0) << endl;

cout << "Top element of stack 2: " << stacks.peek(1) << endl;

cout << "Top element of stack 3: " << stacks.peek(2) << endl;

cout << "Popped element from stack 1: " << stacks.pop(0) << endl;

cout << "Popped element from stack 2: " << stacks.pop(1) << endl;

cout << "Popped element from stack 3: " << stacks.pop(2) << endl;

return 0;

Output:

39 | P a g e
GGNIMT

21. Program for converting infix to postfix form.


#include <iostream>

#include <stack>

using namespace std;

// Function to get precedence of operators

int precedence(char op) {

if (op == '+' || op == '-') return 1;

if (op == '*' || op == '/') return 2;

if (op == '^') return 3;

return 0;

// Function to convert Infix to Postfix

string infixToPostfix(string infix) {

stack<char> s;

string postfix = "";

for (char c : infix) {

if (isalnum(c)) {

postfix += c; // Operand, add to the result

} else if (c == '(') {

s.push(c); // Left Parenthesis, push to stack

} else if (c == ')') {

40 | P a g e
GGNIMT

while (!s.empty() && s.top() != '(') {

postfix += s.top();

s.pop(); // Pop until Left Parenthesis

s.pop(); // Remove '(' from the stack

} else { // Operator

while (!s.empty() && precedence(s.top()) >= precedence(c)) {

postfix += s.top();

s.pop(); // Pop higher or equal precedence operators

s.push(c); // Push current operator to stack

while (!s.empty()) {

postfix += s.top();

s.pop(); // Pop remaining operators from stack

return postfix;

int main() {

string infix;

cout << "Enter infix expression: ";

cin >> infix;

cout << "Postfix expression: " << infixToPostfix(infix) << endl;

return 0;

Output:

41 | P a g e
GGNIMT

22. Program for implementing Queue using array.


#include <iostream>

using namespace std;

class Queue {

int front, rear, size;

int* arr;

public:

Queue(int n) : size(n), front(-1), rear(-1) {

arr = new int[n];

~Queue() {

delete[] arr;

bool isEmpty() { return front == -1; }

bool isFull() { return rear == size - 1; }

void enqueue(int val) {

if (isFull()) {

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

return;

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

42 | P a g e
GGNIMT

arr[++rear] = val;

int dequeue() {

if (isEmpty()) {

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

return -1;

int val = arr[front];

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

else front++;

return val;

void display() {

if (isEmpty()) {

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

return;

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

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

cout << endl;

}};

int main() {

Queue q(5);

q.enqueue(10);

q.enqueue(20);

q.enqueue(30);

q.enqueue(40);

q.enqueue(50);

q.display();

43 | P a g e
GGNIMT

cout << "Dequeued: " << q.dequeue() << endl;

q.display();

return 0;

Output:

23. Program for dynamic implementation of queue.


#include <iostream>

using namespace std;

// Node structure for the queue

struct Node {

int data;

Node* next;

};

class Queue {

private:

Node *front, *rear;

public:

Queue() {

front = rear = nullptr;

~Queue() {

while (front != nullptr) {

44 | P a g e
GGNIMT

dequeue();

} }

bool isEmpty() {

return front == nullptr;

void enqueue(int value) {

Node* newNode = new Node();

newNode->data = value;

newNode->next = nullptr;

if (rear == nullptr) {

front = rear = newNode;

return;

rear->next = newNode;

rear = newNode;

int dequeue() {

if (isEmpty()) {

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

return -1;

Node* temp = front;

int value = front->data;

front = front->next;

if (front == nullptr) {

rear = nullptr; // If the queue is empty after dequeue, rear should


also be null

delete temp;

45 | P a g e
GGNIMT

return value;

void display() {

if (isEmpty()) {

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

return;

Node* temp = front;

cout << "Queue elements: ";

while (temp != nullptr) {

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

temp = temp->next;

cout << endl;

} };

int main() {

Queue q;

q.enqueue(10);

q.enqueue(20);

q.enqueue(30);

q.enqueue(40);

q.display();

cout << "Dequeued: " << q.dequeue() << endl;

cout << "Dequeued: " << q.dequeue() << endl;

q.display();

return 0;

Output:

46 | P a g e
GGNIMT

24. Program for implementing circular queue.


#include <iostream>

using namespace std;

class CircularQueue {

private:

int *arr;

int front, rear, size;

public:

CircularQueue(int n) : size(n), front(-1), rear(-1) {

arr = new int[size];

~CircularQueue() {

delete[] arr;

bool isEmpty() {

return front == -1;

bool isFull() {

return (rear + 1) % size == front;

void enqueue(int value) {

if (isFull()) {

47 | P a g e
GGNIMT

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

return;

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

else rear = (rear + 1) % size;

arr[rear] = value;

int dequeue() {

if (isEmpty()) {

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

return -1;

int value = arr[front];

if (front == rear) front = rear = -1; // Queue becomes empty

else front = (front + 1) % size;

return value;

void display() {

if (isEmpty()) {

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

return;

int i = front;

while (i != rear) {

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

i = (i + 1) % size;

cout << arr[rear] << endl; // print last element

48 | P a g e
GGNIMT

};

int main() {

CircularQueue q(5);

q.enqueue(10);

q.enqueue(20);

q.enqueue(30);

q.enqueue(40);

q.enqueue(50);

q.display();

q.enqueue(60); // Will show "Queue is full!"

cout << "Dequeued: " << q.dequeue() << endl;

q.display();

q.enqueue(60);

q.display();

return 0;

Output:

49 | P a g e
GGNIMT

25. Program for implementing dequeue.


#include <iostream>

using namespace std;

class Deque {

private:

int *arr;

int front, rear, size;

public:

Deque(int n) {

size = n;

arr = new int[size];

front = rear = -1;

~Deque() {

delete[] arr;

bool isEmpty() {

return front == -1;

bool isFull() {

return (front == 0 && rear == size - 1) || (front == rear + 1);

void insertFront(int value) {

if (isFull()) {

cout << "Deque is full!" << endl;

return;

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

50 | P a g e
GGNIMT

else front = (front - 1 + size) % size;

arr[front] = value;

void insertRear(int value) {

if (isFull()) {

cout << "Deque is full!" << endl;

return;

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

else rear = (rear + 1) % size;

arr[rear] = value;

int deleteFront() {

if (isEmpty()) {

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

return -1;

int value = arr[front];

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

else front = (front + 1) % size;

return value;

int deleteRear() {

if (isEmpty()) {

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

return -1;

int value = arr[rear];

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

51 | P a g e
GGNIMT

else rear = (rear - 1 + size) % size;

return value;

void display() {

if (isEmpty()) {

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

return;

int i = front;

while (i != rear) {

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

i = (i + 1) % size;

cout << arr[rear] << endl;

};

int main() {

Deque dq(5);

dq.insertRear(10);

dq.insertRear(20);

dq.insertFront(5);

dq.display();

cout << "Deleted from front: " << dq.deleteFront() << endl;

dq.display();

dq.insertRear(30);

dq.insertFront(2);

dq.display();

cout << "Deleted from rear: " << dq.deleteRear() << endl;

dq.display();

52 | P a g e
GGNIMT

return 0;

Output:

26. Program for implementing priority queue.


#include <iostream>

#include <vector>

using namespace std;

class PriorityQueue {

private:

vector<int> heap;

void heapifyUp(int index) {

while (index > 0 && heap[index] > heap[(index - 1) / 2]) {

swap(heap[index], heap[(index - 1) / 2]);

index = (index - 1) / 2;

void heapifyDown(int index) {

int leftChild = 2 * index + 1;

int rightChild = 2 * index + 2;

53 | P a g e
GGNIMT

int largest = index;

if (leftChild < heap.size() && heap[leftChild] > heap[largest]) largest


= leftChild;

if (rightChild < heap.size() && heap[rightChild] > heap[largest])


largest = rightChild;

if (largest != index) {

swap(heap[index], heap[largest]);

heapifyDown(largest);

public:

void insert(int value) {

heap.push_back(value);

heapifyUp(heap.size() - 1);

int remove() {

if (heap.empty()) return -1;

int root = heap[0];

heap[0] = heap.back();

heap.pop_back();

heapifyDown(0);

return root;

void display() {

for (int val : heap) cout << val << " ";

cout << endl;

} };

int main() {
54 | P a g e
GGNIMT

PriorityQueue pq;

pq.insert(10);

pq.insert(30);

pq.insert(20);

pq.insert(40);

pq.display();

cout << "Removed: " << pq.remove() << endl;

pq.display();

return 0;

Output:

27. Program to find factorial of a number using


recursion
#include <iostream>

using namespace std;

int factorial(int n) {

// Base case: factorial of 0 or 1 is 1

if (n <= 1) {

return 1;

} else {

// Recursive call

return n * factorial(n - 1);

} }

55 | P a g e
GGNIMT

int main() {

int num;

cout << "Enter a number: ";

cin >> num;

// Ensure that the input number is non-negative

if (num < 0) {

cout << "Factorial is not defined for negative numbers!" << endl;

} else {

// Call the factorial function

cout << "Factorial of " << num << " is: " << factorial(num) << endl;

return 0;

Output:

28. Program to print fibonacci series using recursion


#include <iostream>

using namespace std;

int fibonacci(int n) {

if (n <= 1) {

return n; // Base case: fib(0) = 0, fib(1) = 1

} else {

// Recursive case: fib(n) = fib(n-1) + fib(n-2)

return fibonacci(n - 1) + fibonacci(n - 2);

56 | P a g e
GGNIMT

int main() {

int n;

cout << "Enter the number of terms for Fibonacci series: ";

cin >> n;

cout << "Fibonacci series up to " << n << " terms: ";

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

cout << fibonacci(i) << " ";

cout << endl;

return 0;

Output:

29. Program to Merge two Un-Sorted array.


#include <iostream>

using namespace std;

void mergearrays(int arr1[], int arr2[], int size1, int size2, int
mergedarray[])

for (int i = 0; i < size1; i++)

mergedarray[i] = arr1[i];

for (int i = 0; i < size2; i++)

mergedarray[size1 + i] = arr2[i];

57 | P a g e
GGNIMT

int main()

int size1, size2;

cout << "Enter the size of the first array:";

cin >> size1;

int arr1[size1];

cout << "Enter elements of the first array: \n";

for (int i = 0; i < size1; i++)

cin >> arr1[i];

cout << "Enter the size of the second array: ";

cin >> size2;

int arr2[size2];

cout << "Enter the elements of the second array: \n";

for(int i = 0; i < size2; i++)

cin >> arr2[i];

int mergedsize = size1 + size2;

int mergedarray[mergedsize];

mergearrays(arr1, arr2, size1, size2, mergedarray);

cout << "Merged Array: ";

for (int i = 0; i < mergedsize; i++)

cout << mergedarray[i] << " ";

return 0;

58 | P a g e
GGNIMT

Output:

30. Program to Merge two Sorted array.


/* Merge Sorted arrays */

#include <iostream>

using namespace std;

void mergeSortedArrays(int arr1[], int size1, int arr2[], int size2, int
mergedArray[]) {

int i = 0, j = 0, k = 0;

// Merge arrays while there are elements in both

while (i < size1 && j < size2) {

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

mergedArray[k++] = arr1[i++];

} else {

mergedArray[k++] = arr2[j++];

// Copy remaining elements of arr1, if any

while (i < size1) {

mergedArray[k++] = arr1[i++];

// Copy remaining elements of arr2, if any

59 | P a g e
GGNIMT

while (j < size2) {

mergedArray[k++] = arr2[j++];

}}

int main() {

int size1, size2;

cout << "Enter the size of the first sorted array: ";

cin >> size1;

int arr1[size1];

cout << "Enter elements of the first sorted array:\n";

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

cin >> arr1[i];

cout << "Enter the size of the second sorted array: ";

cin >> size2;

int arr2[size2];

cout << "Enter elements of the second sorted array:\n";

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

cin >> arr2[i];

int mergedSize = size1 + size2;

int mergedArray[mergedSize];

mergeSortedArrays(arr1, size1, arr2, size2,

mergedArray);

cout << "Merged sorted array: ";

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

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

return 0;

60 | P a g e
GGNIMT

Output:

61 | P a g e

You might also like