C++ Program to Rotate Matrix Elements of a Matrix

Rotating Matrix elements in a C++ program involves rearranging the elements of a matrix by rotating them either clockwise or counterclockwise. Here’s a brief explanation of how to achieve this within a 400-word limit:

To begin, let’s consider rotating a square matrix. We’ll create a C++ function to rotate the matrix elements clockwise by 90 degrees. The steps involved are:

  1. Transpose the matrix.
  2. Reverse each row of the transposed matrix.

Here’s the implementation:

#include <iostream>

#include <vector>

using namespace std;

// Function to rotate the matrix elements clockwise by 90 degrees

void rotateMatrix(vector<vector<int>>& matrix) {

    int N = matrix.size(); // Size of the matrix

    // Transpose the matrix

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

        for (int j = i; j < N; ++j) {

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

        }

    }

    // Reverse each row

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

        for (int j = 0; j < N / 2; ++j) {

            swap(matrix[i][j], matrix[i][N – 1 – j]);

        }

    }

}

// Function to print the matrix

void printMatrix(const vector<vector<int>>& matrix) {

    for (const auto& row : matrix) {

        for (int num : row) {

            cout << num << ” “;

        }

        cout << endl;

    }

}

int main() {

    vector<vector<int>> matrix = {{1, 2, 3},

                                   {4, 5, 6},

                                   {7, 8, 9}};

    cout << “Original Matrix:” << endl;

    printMatrix(matrix);

    rotateMatrix(matrix);

    cout << “Matrix After Rotation:” << endl;

    printMatrix(matrix);

    return 0;

}

In this code:

  • We define a function rotateMatrix that takes a 2D vector matrix as input.
  • We find the size N of the matrix.
  • We iterate through each element of the matrix to transpose it.
  • Then, we reverse each row of the transposed matrix.
  • We define a printMatrix function to print the matrix.
  • In the main function, we initialize a sample matrix, print it, rotate it, and then print the rotated matrix.

This code demonstrates rotating a square matrix clockwise by 90 degrees. Similar techniques can be applied for rotating non-square matrices or rotating counterclockwise by modifying the logic accordingly.

C++ Program to Reverse a Sentence Using Recursion

Reversing a sentence using recursion is an interesting problem that illustrates the utility of recursive thinking in solving real-world problems. In this context, reversing a sentence means to print or return the words in reverse order compared to how they were originally inputted.

Here is a simple C++ program that demonstrates how to reverse a sentence using recursion. The program will ask the user for a sentence, then reverse it word by word using a recursive function.

#include <iostream>

#include <string>

#include <sstream>

// Recursive function to reverse the words in the sentence

void reverseSentence(std::istringstream& iss) {

    std::string word;

    if (iss >> word) {  // Read the next word

        reverseSentence(iss);  // Recursive call before printing the word

        std::cout << word << ” “;

    }

}

int main() {

    std::cout << “Enter a sentence: “;

    std::string input;

    getline(std::cin, input);  // Read the full line of text

    std::istringstream iss(input);  // Use istringstream to read words from the sentence

    std::cout << “Reversed sentence: “;

    reverseSentence(iss);

    std::cout << std::endl;

    return 0;

}

Explanation:

  • Input:

The program reads a complete line as input using getline, which allows it to handle spaces between words effectively.

  • Using istringstream:

The input string is fed into an istringstream object. This utility helps in extracting words one by one from the sentence.

  • Recursive Function (reverseSentence):

This function takes an istringstream object as an argument. It tries to extract a word from the stream. If it succeeds (i.e., if there are still words left to read), it makes a recursive call before it prints the word. This order of operations ensures that the recursion goes all the way to the end of the sentence, starts unwinding, and then prints the words in reverse order as the recursion stack collapses.

  • Output:

The words are printed in reverse order as the recursive function unwinds.

Note on Efficiency

The recursive method is clear and concise for reversing sentences or similar tasks where depth is typically not going to be prohibitive. However, recursion depth is limited by stack size, so for extremely long texts, an iterative approach might be necessary or you might need to adjust system settings to allow deeper recursion if stack overflow occurs. This is generally not an issue for most simple sentences or standard use cases.

C++ Program to Remove Duplicate Elements from an Array

To remove duplicate elements from an array in C++, you can create a program that uses a data structure such as a set to track unique elements or a two-pointer technique to filter duplicates in place.

Here’s an example program that demonstrates how to remove duplicate elements from an array and output the resulting array with unique elements using the two-pointer technique:

#include <iostream>

int removeDuplicates(int arr[], int size) {

    // If the array is empty or has only one element, no need to remove duplicates

    if (size == 0 || size == 1) {

        return size;

    }

    // Index to store the next unique element

    int uniqueIndex = 0;

    // Iterate through the array

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

        // If the current element is different from the last unique element

        if (arr[i] != arr[uniqueIndex]) {

            // Move the unique element to the next position

            uniqueIndex++;

            arr[uniqueIndex] = arr[i];

        }

    }

    // Return the size of the array with unique elements

    return uniqueIndex + 1;

}

int main() {

    // Define the array

    int arr[] = {1, 1, 2, 3, 3, 4, 4, 5, 6, 6, 7};

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

    // Remove duplicates from the array

    int newSize = removeDuplicates(arr, size);

    // Output the array with unique elements

    std::cout << “Array with unique elements: “;

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

        std::cout << arr[i] << ” “;

    }

    std::cout << std::endl;

    return 0;

}

Here’s how the program works:

  • The function removeDuplicates takes an array and its size as parameters.
  • If the size of the array is less than 2, there is no need to remove duplicates, so the function simply returns the size.
  • The function uses a variable uniqueIndex to keep track of the index where the next unique element should be stored.
  • The loop iterates through the array, starting from the second element.
    • If an element is different from the element at uniqueIndex, the element is moved to the next position after uniqueIndex.
    • uniqueIndex is then incremented to point to the next position for unique elements.
  • After the loop completes, the function returns the size of the array with unique elements, which is uniqueIndex + 1.
  • In the main function, the array with duplicates removed is printed using the returned size.

C++ Program to Remove All Occurrences of an Element in an Array

To remove all occurrences of a specific element in an array in C++, you can create a program that iterates through the array and shifts the remaining elements forward whenever the target element is found. This effectively reduces the size of the array and removes all occurrences of the target element.

Here’s an example program that demonstrates how to remove all occurrences of a specified element from an array:

#include <iostream>

int removeElement(int arr[], int size, int element) {

    // Index to store the next element after removing occurrences

    int newSize = 0;

    // Iterate through the array

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

        // If the current element is not the element to be removed

        if (arr[i] != element) {

            // Move the current element to the position at newSize

            arr[newSize] = arr[i];

            // Increment newSize

            newSize++;

        }

    }

    // Return the new size of the array after removing the element

    return newSize;

}

int main() {

    // Define the array

    int arr[] = {4, 3, 2, 4, 1, 4, 5, 6, 4};

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

    // Element to be removed

    int elementToRemove = 4;

    // Remove all occurrences of the element from the array

    int newSize = removeElement(arr, size, elementToRemove);

    // Output the array after removing the element

    std::cout << “Array after removing element ” << elementToRemove << “: “;

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

        std::cout << arr[i] << ” “;

    }

    std::cout << std::endl;

    return 0;

}

Here’s how the Program Works:

  • The function removeElement takes an array, its size, and the element to be removed as parameters.
  • The function initializes a variable newSize to 0, which keeps track of the size of the array after removing occurrences.
  • It iterates through the array, checking each element.
    • If the current element is not the target element (element), it is moved to the position at newSize in the array.
    • The newSize variable is incremented to track the size of the array after removing occurrences.
  • After the loop completes, the function returns the new size of the array.
  • In the main function, the program prints the array after removing the specified element using the returned new size.

C++ Program to Print a 2D Array

Printing a 2D array in C++ is similar to printing a 1D array, but instead of a single loop, you use nested loops to iterate over the rows and columns of the 2D array.

Here’s an example program that demonstrates how to print a 2D array:

#include <iostream>

int main() {

    // Define the 2D array

    int arr[3][3] = {

        {1, 2, 3},

        {4, 5, 6},

        {7, 8, 9}

    };

    // Define the dimensions of the array

    int rows = 3;

    int cols = 3;

    // Print the 2D array

    std::cout << “2D array:” << std::endl;

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

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

            // Print the element at [i][j]

            std::cout << arr[i][j] << ” “;

        }

        // Print a new line after each row

        std::cout << std::endl;

    }

    return 0;

}

Here’s how the program works:

  • The program starts by defining a 2D array (arr) with 3 rows and 3 columns, and some example values.
  • The rows and cols variables are used to specify the number of rows and columns in the array.
  • A nested loop is used to iterate over the 2D array.
    • The outer loop iterates over each row of the array.
    • The inner loop iterates over each column of the current row.
    • Each element at position [i][j] in the array is printed, followed by a space.
  • After printing all the elements in a row, a new line is printed to separate rows visually.
  • This continues until all rows are printed, resulting in the 2D array being displayed in a matrix-like format.

C++ Program to Merge Two Arrays

Merging two arrays in C++ can be achieved by creating a new array that is large enough to hold both arrays, and then copying the elements from the original arrays into the new array. Here’s an example program that demonstrates how to merge two arrays:

#include <iostream>

int main() {

    // Define the first array

    int arr1[] = {1, 3, 5, 7, 9};

    int size1 = sizeof(arr1) / sizeof(arr1[0]);

    // Define the second array

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

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

    // Calculate the size of the merged array

    int mergedSize = size1 + size2;

    // Create a new array to hold the merged arrays

    int mergedArray[mergedSize];

    // Merge the two arrays

    // Copy elements from the first array

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

        mergedArray[i] = arr1[i];

    }

    // Copy elements from the second array

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

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

    }

    // Output the merged array

    std::cout << “Merged array: “;

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

        std::cout << mergedArray[i] << ” “;

    }

    std::cout << std::endl;

    return 0;

}

Here’s how the program works:

  • The program starts by defining two arrays (arr1 and arr2) with some example values.
  • The sizes of the arrays are calculated using sizeof to determine the length of each array.
  • The program calculates the size of the merged array by summing the sizes of the two arrays.
  • A new array (mergedArray) is created to hold the combined elements of the original arrays.
  • The program uses a loop to copy elements from the first array to the merged array.
  • Another loop is used to copy elements from the second array to the merged array, starting from where the first array’s elements ended.
  • Finally, the program prints the merged array.

C++ Program for void Pointer

A void pointer is a special type of pointer that can point to any data type. This is because a void pointer does not have an associated data type. However, since it doesn’t have a specific type, you cannot dereference it directly without casting it to another pointer type.

Key Concepts

  1. Declaration of a Void Pointer

void* ptr;

 

This declares a void pointer ‘ptr’ that can hold the address of any data type.

  1. Assigning Addresses to a Void Pointer

int a = 10;

float b = 5.5;

ptr = &a; // Void pointer pointing to an integer

ptr = &b; // Void pointer pointing to a float

  1. Dereferencing a Void Pointer

Since a void pointer does not have a type, you need to cast it to the appropriate type before dereferencing

int* intPtr = (int*)ptr;

cout << *intPtr << endl;

float* floatPtr = (float*)ptr;

cout << *floatPtr << endl;

 

Example Program: Using Void Pointers

Here’s a complete program that demonstrates the use of void pointers in C++:

#include <iostream>

using namespace std;

void printValue(void* ptr, char type) {

    switch (type) {

        case ‘i’: // Integer

            cout << “Integer: ” << *(int*)ptr << endl;

            break;

        case ‘f’: // Float

            cout << “Float: ” << *(float*)ptr << endl;

            break;

        case ‘d’: // Double

            cout << “Double: ” << *(double*)ptr << endl;

            break;

        case ‘c’: // Character

            cout << “Character: ” << *(char*)ptr << endl;

            break;

        default:

            cout << “Invalid type!” << endl;

    }

}

int main() {

    int a = 10;

    float b = 5.5f;

    double c = 3.14159;

    char d = ‘A’;

    void* ptr; // Declare a void pointer

    // Using the void pointer to point to different data types

    ptr = &a;

    printValue(ptr, ‘i’);

    ptr = &b;

    printValue(ptr, ‘f’);

    ptr = &c;

    printValue(ptr, ‘d’);

    ptr = &d;

    printValue(ptr, ‘c’);

    return 0;

}

Explanation of the Program

  1. Function ‘printValue’

This function takes a void pointer and a type identifier. It casts the void pointer to the appropriate type based on the type identifier and prints the value. The switch statement is used to handle different data types.

  1. Main Function

  • Four variables of different types (int, float, double, char) are declared.
  • A void pointer ‘ptr’ is used to point to each of these variables.
  • The ‘printValue’ function is called with the void pointer and a type identifier to print the value pointed to by the void pointer.

C++ Program for this Pointer

In C++, the ‘this’ pointer is an implicit parameter to all non-static member functions. It is a pointer to the object for which the member function is called. This pointer helps in accessing the member variables and other member functions of the class within its member functions.

Here’s a complete program that demonstrates the use of the this pointer in C++:

#include <iostream>

using namespace std;

class Rectangle {

private:

    int length;

    int width;

public:

    // Default constructor

    Rectangle() : length(0), width(0) {}

    // Parameterized constructor

    Rectangle(int length, int width) {

        // Use ‘this’ pointer to resolve name conflict

        this->length = length;

        this->width = width;

    }

    // Member function to set dimensions

    void setDimensions(int length, int width) {

        // Use ‘this’ pointer to resolve name conflict

        this->length = length;

        this->width = width;

    }

    // Member function to calculate area

    int area() const {

        return length * width;

    }

    // Member function to print dimensions

    void printDimensions() const {

        cout << “Length: ” << this->length << “, Width: ” << this->width << endl;

    }

    // Member function to return the current object

    Rectangle& increaseSize(int increment) {

        this->length += increment;

        this->width += increment;

        return *this;

    }

};

int main() {

    // Create an object of Rectangle using the default constructor

    Rectangle rect1;

    rect1.printDimensions();

    // Set dimensions using the member function

    rect1.setDimensions(10, 5);

    rect1.printDimensions();

    // Create another object of Rectangle using the parameterized constructor

    Rectangle rect2(3, 7);

    rect2.printDimensions();

    // Calculate and print the area of rect2

    cout << “Area of rect2: ” << rect2.area() << endl;

    // Increase the size of rect2 and print the new dimensions

    rect2.increaseSize(2).printDimensions();

    return 0;

}

Explanation of the Program

  1. Class Definition

‘Rectangle’ class has private member variables ‘length’ and ‘width’. It includes constructors, member functions to set dimensions, calculate area, print dimensions, and increase the size of the rectangle.

  1. Constructors
  • Default Constructor: Initializes length and width to 0.
  • Parameterized Constructor: Uses the ‘this’ pointer to distinguish between the member variables and parameters with the same name.
  1. Member Functions
  • Set Dimensions:

Uses the ‘this’ pointer to resolve the naming conflict between the member variables and parameters.

  • Area:

Returns the area of the rectangle.

  • Print Dimensions:

Prints the dimensions of the rectangle. Although this-> is not necessary here, it is used for clarity.

  • Increase Size:

Increases the size of the rectangle by a given increment and returns a reference to the current object.

  • Main Function:

Creates and manipulates Rectangle objects using the class member functions. Demonstrates the use of the ‘this’ pointer to set dimensions, calculate the area, and increase the size of the rectangle.

C++ Program for Reference to a Pointer

In C++, a reference to a pointer is essentially an alias for a pointer variable. This allows you to manipulate the pointer itself, not just the value it points to. Using references to pointers can be particularly useful in functions where you need to modify the actual pointer passed as an argument.

Example Program: Using a Reference to a Pointer

Here’s a complete program that demonstrates the use of references to pointers in C++:

#include <iostream>

using namespace std;

// Function to modify a pointer via a reference to a pointer

void modifyPointer(int*& ref) {

    ref = new int; // Allocate new memory

    *ref = 20;     // Assign a value to the allocated memory

}

int main() {

    int* ptr = nullptr; // Initialize pointer to nullptr

    cout << “Initial pointer value: ” << ptr << endl;

    // Pass the pointer to the function

    modifyPointer(ptr);

    // Output the modified pointer value and the value it points to

    cout << “Modified pointer value: ” << ptr << endl;

    cout << “Value at the modified pointer: ” << *ptr << endl;

    // Clean up dynamically allocated memory

    delete ptr;

    return 0;

}

Explanation of the Program

  1. Function ‘modifyPointer’

This function takes a reference to a pointer to an integer (‘int*& ref’). It allocates new memory and assigns the value ‘20’ to the newly allocated memory. The modifications made to ‘ref’ affect the original pointer passed to the function.

  1. Main Function

  • A pointer ‘ptr’ is initialized to ‘nullptr’.
  • The initial value of ‘ptr’ is printed (which is ‘nullptr’).
  • The pointer ‘ptr’ is passed to the ‘modifyPointer’ function by reference.
  • The function allocates memory for ‘ptr’ and assigns the value ‘20’ to it.
  • The modified pointer value and the value it points to are printed.
  • Finally, the dynamically allocated memory is deallocated using ‘delete’.

Benefits of Using References to Pointers:

  1. Efficiency

Passing references to pointers is more efficient than passing pointers by value, especially when dealing with large data structures.

  1. Direct Modification

Allows direct modification of the original pointer, making it useful in scenarios where functions need to update pointer addresses

C++ Program for Pointers

Pointers are variables that store memory addresses. They are essential for dynamic memory management, array handling, and implementing complex data structures. Here are the basics:

  1. Pointer Declaration and Initialization

int *ptr; // Declaration of a pointer

int var = 10;

ptr = &var; // Initialization with the address of var

  1. Dereferencing Pointers

int value = *ptr; // Dereference ptr to get the value of var

  1. Pointer Arithmetic

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

int *ptr = arr; // Points to the first element of arr

ptr++; // Now points to the second element of arr

  1. Dynamic Memory Allocation

int *ptr = new int; // Allocate memory for an integer

*ptr = 10; // Assign a value to the allocated memory

delete ptr; // Deallocate the memory

  1. Function Pointers

void func(int a) {

    cout << a << endl;

}

void (*func_ptr)(int) = &func; // Function pointer

func_ptr(5); // Calling the function using the pointer

Example Program

Here’s a program that demonstrates several key aspects of pointers in C++:

#include <iostream>

using namespace std;

// Function to swap two integers using pointers

void swap(int *a, int *b) {

    int temp = *a;

    *a = *b;

    *b = temp;

}

 

// Function to dynamically allocate an array and fill it with values

int* createArray(int size) {

    int *arr = new int[size];

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

        arr[i] = i + 1;

    }

    return arr;

}

 

// Function to print the elements of an array

void printArray(int *arr, int size) {

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

        cout << arr[i] << ” “;

    }

    cout << endl;

}

 

// Function that takes a function pointer as an argument

void applyFunction(void (*func)(int), int value) {

    func(value);

}

 

// Simple function to demonstrate function pointers

void display(int a) {

    cout << “Value is: ” << a << endl;

}

 

int main() {

    // Basic pointer usage

    int var = 42;

    int *ptr = &var;

    cout << “Address of var: ” << ptr << endl;

    cout << “Value of var: ” << *ptr << endl;

 

    // Swapping values using pointers

    int x = 10, y = 20;

    cout << “Before swap: x = ” << x << “, y = ” << y << endl;

    swap(&x, &y);

    cout << “After swap: x = ” << x << “, y = ” << y << endl;

 

    // Dynamic memory allocation

    int size;

    cout << “Enter the size of the array: “;

    cin >> size;

    int *array = createArray(size);

    cout << “Array elements: “;

    printArray(array, size);

    delete[] array;

 

    // Function pointers

    void (*func_ptr)(int) = display;

    applyFunction(func_ptr, 5);

 

    return 0;

}

Explanation:             

  • Basic Pointer Usage

Declares an integer and a pointer to that integer. Prints the address and value using the pointer.

  • Swapping Values Using Pointers

The swap function demonstrates passing pointers to a function to swap the values of two variables.

  • Dynamic Memory Allocation

Prompts the user for the size of an array, dynamically allocates memory for the array, fills it with values, prints the array, and then deallocates the memory.

  • Function Pointers

Defines a simple function display and a function applyFunction that takes a function pointer as an argument. Demonstrates calling the display function using a function pointer.

error: Content is protected !!