How to search a 2d array using two pointers to the first and last elements in the array with C++

2 Answers

0 votes
#include <iostream>  

const int ROWS = 3;
const int COLS = 4;

// Function to search for a target value in a 2D matrix
bool searchMatrix(int matrix[][COLS], int rows, int cols, int target) {
    // Pointer to the first element of the matrix
    int* first = &matrix[0][0];

    // Pointer to the last element of the matrix
    int* last = &matrix[rows - 1][cols - 1];

    // Traverse the matrix linearly
    while (first < last && *first != target) {
        first++;
    }

    // Check if the target was found
    if (*first == target) {
        return true;
    }

    return false; // Target not found
}

int main() {
    // Define a 2D array (matrix)
    int matrix[ROWS][COLS] = {
        { 1,  4,  6,  9},
        {11, 17, 18, 29},
        {32, 38, 40, 70}
    };

    int target = 29;

    // Call the search function and print the result
    if (searchMatrix(matrix, ROWS, COLS, target)) {
        std::cout << "Target " << target << " found in the matrix." << std::endl;
    } else {
        std::cout << "Target " << target << " not found in the matrix." << std::endl;
    }
}



/*
run:

Target 29 found in the matrix.

*/

 



answered Sep 23, 2025 by avibootz
0 votes
#include <iostream>  

const int ROWS = 3;
const int COLS = 4;

// Function to search for a target value in a 2D matrix using pointer arithmetic
bool searchMatrix(int matrix[][COLS], int* first, int* last, int target) {
    // Traverse the matrix linearly using pointers
    while (first < last && *first != target) {
        first++;
    }

    // Check if the target was found
    if (*first == target) {
        return true;
    }

    return false; // Target not found
}

int main() {
    // Define a 2D array (matrix)
    int matrix[ROWS][COLS] = {
        { 1,  4,  6,  9},
        {11, 17, 18, 29},
        {32, 38, 40, 70}
    };

    int target = 29;

    // Pointer to the first element of the matrix
    int* first = &matrix[0][0];

    // Pointer to the last element of the matrix
    int* last = &matrix[ROWS - 1][COLS - 1];

    // Call the search function and print the result
    if (searchMatrix(matrix, first, last, target)) {
        std::cout << "Target " << target << " found in the matrix." << std::endl;
    } else {
        std::cout << "Target " << target << " not found in the matrix." << std::endl;
    }
}



/*
run:

Target 29 found in the matrix.

*/

 



answered Sep 23, 2025 by avibootz
...