📜  门| GATE-CS-2017(Set 1)|问题19(1)

📅  最后修改于: 2023-12-03 15:12:43.913000             🧑  作者: Mango

GATE-CS-2017(Set 1) - Problem 19

This question is aimed at testing a programmer's ability to understand and modify code in C++ and Python. The question provides the code for a C++ function and the equivalent Python code. The task is to write missing pieces of code for both the implementations of the function.

The function takes in an integer array A of size n and an integer value x. If x is present in the array, the function returns the index of the first occurrence of x in the array. If x is not present in the array, the function should return -1.

Here is the C++ implementation:

int find(int A[], int n, int x) {
    // Write your code here
}

And here is the Python implementation:

def find(A, n, x):
    # Write your code here
Approach for C++ implementation

We can loop through the array and return the index once we encounter the first occurrence of x. If x is not present, we should return -1.

Here is the complete code:

int find(int A[], int n, int x) {
    for(int i=0; i<n; i++) {
        if(A[i] == x) {
            return i;
        }
    }
    return -1;
}
Approach for Python implementation

In Python, we can make use of the in keyword to check if x is present in the array. If found, we should return the index of the first occurrence of x. If not found, we should return -1.

Here is the complete code:

def find(A, n, x):
    if x in A:
        return A.index(x)
    else:
        return -1

Note: As Python is a dynamically typed language, we don't need to define the type of variables explicitly as in C++.