Member-only story

Find Disorder method: Find the first item in an array that is less than the element preceding it using C++ pointers

Marika Lam
2 min readMay 20, 2022

--

Question

The findDisorder function is supposed to find the first item in an array that is less than the element preceding it. and set the p parameter to point to that item so the caller can know the location of that item

Explanation

Within the method declaration of findDisorder, an int array, int n (length of the array), and a reference variable of pointer p are the parameters. Within the method, a for loop is declared where it will loop from 1 to the length of the array.

When an element less than the previous element is found, the pointer p will be updated to the current index. Then it will exit the for loop with the statement ‘return’.

Once the method is finished executing, the main method will be able to call the pointer ‘p’ variable because it was declared as a reference ‘&’ in the parameter of the findDisorder method. ‘ptr’ will print out the memory address of the index, ‘ptr-nums’ will print out the index, and ‘*ptr’ will print out the value of the element.

Solution

void findDisorder(int arr[], int n, int* &p){for (int k = 1; k < n; k++){if (arr[k] < arr[k-1]){p = arr + k;

--

--

No responses yet