Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Searching for a number in a given array using pointers

I need to create a program that searches for a user inserted number from an array using pointers. This is my current code

#include <iostream>
using namespace std;

void FindNumber(int *ptrArr, int size, int *ptr1) {
    for (int *p = ptrArr; p < ptrArr + size; ++p) {
        if (ptrArr[*p] == *ptr1) {
            cout << "Number (" << *ptr1 << ") found in the array with an index of: " << *p;
            break;
        }

        if (*p == size) {
            cout  << "No such number in given array\n";
        } 

    }
}

int main () {
    int numbers[10] = {5, 4, 7, 10, 24, 15, 8, 2, 9, 13};
    int num;

    cout << "What number do you want to search for?\n";
    cin >> num;

    FindNumber(numbers, sizeof(numbers) / sizeof(int), &num);
    return 0;
}

The problem is with for loop, but I don’t know what it is
Sometimes it finds the number with right index, sometimes it doesn’t find it even though there is that particular number in the array, sometimes it finds the number but outputs the wrong index

What number do you want to search for?
7
No such number in given array
Number (7) found in the array with an index of: 2

What number do you want to search for?
5
No such number in given array

Tried changing the for loop on my own but no successo. Hoping for some help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have 2 small typos in your code.

-No need to index the array with "*p"

-The index need to be calculated by subtracting p from the original pointer.

Please see here the fixed code:

#include <iostream>
using namespace std;

void FindNumber(int* ptrArr, int size, int* ptr1) {
    for (int* p = ptrArr; p < ptrArr + size; ++p) {
        if (*p == *ptr1) {
            cout << "Number (" << *ptr1 << ") found in the array with an index of: " << (p-ptrArr);
            return;
        }
    }
    cout << "No such number in given array\n";

}

int main() {
    int numbers[10] = { 5, 4, 7, 10, 24, 15, 8, 2, 9, 13 };
    int num;

    cout << "What number do you want to search for?\n";
    cin >> num;

    FindNumber(numbers, sizeof(numbers) / sizeof(int), &num);
    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading