I got stuck :(. Can anyone tell me the purpose of this following code please? (Suggest descriptive names for the function and its parameters.)

int mystery(int x, int y[], int z) {
for (int i = 0; i < z; i++) {
if (y[i] == x) return i;
}
return -1;
}

thank you so much.

Dani AI

Generated

Short answer: the first routine searches an array for a value and returns the index of the first match (or -1 if not found). As explained, it performs a linear scan; a clearer name would be index_of or find_index, and parameter names like target, arr and n (use size_t for sizes and const for read-only arrays).

A slightly more modern, safer signature uses std::optional to avoid overloading the meaning of -1:

#include <optional>
#include <cstddef>

template<typename T>
std::optional<std::size_t> index_of(const T* arr, std::size_t n, const T& target) {
    for (std::size_t i = 0; i < n; ++i)
        if (arr[i] == target) return i;
    return std::nullopt;
}

Or use the standard algorithm std::find to work with iterators or pointer ranges; see std::find.

For the pointer/pointer-arithmetic exercise (the one after your line 1), the state after each labeled step is:

  • After line 2:

    • a = {7, 2, 2, 3, 4, 5, 6}
    • p -> a[0]
    • q -> a[1]
  • After line 3:

    • a = {7, 2, 2, 7, 4, 5, 6}
    • p -> a[3]
    • q -> a[2]
  • After line 4:

    • a = {7, 2, 7, 7, 4, 5, 6}
    • p -> a[3]
    • q -> a[2]
  • After line 5:

    • a = {7, 2, 7, 7, 2, 5, 6}
    • p -> a[3]
    • q -> a[2]

The key is to track pointer targets (which index they point to) separately from the values. As suggested, walking the statements on paper or annotating indices makes this trivial. Note: pointer indexing like q[-1] is valid only when it stays inside the same array bounds — pointer arithmetic rules are covered here: .

Recommended Answers

All 4 Replies

returns the index where the current element of array y is equal to x, else returns -1 if the value of x is not in the array

thank you zeroliken :)

By the way, could you help me with this as well? this is the question:
what will print for a[], p, q after line 2, 3, 4 and 5? I have done for line 1, then I got stuck :(.

int a[] = { 0, 1, 2, 3, 4, 5, 6 };
int* p;
int* q;
p = a; q = p; *q = 6; // line 1
(*q)++; q++; (*q)++; // line 2
p = ++q; ++p; *p = 7; // line 3
*q = *p; // line 4
p[1] = q[-1]; // line 5

thanks

what will print

Nothing. There are no output statements.

Assuming that's not the correct answer, sit down with pen and paper and figure it out.

Write down the variables and their contents
Write down the pointers and where they point
Now follow the code statement by statement

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.