Knowee
Questions
Features
Study Tools

Given an array of length N and an integer x, you need to find if x is present in the array or not. Return true or false.Do this recursively.

Question

Given an array of length N and an integer x, you need to find if x is present in the array or not. Return true or false. Do this recursively.

🧐 Not the exact question you are looking for?Go ask a question

Solution

Here is a step-by-step solution in Python:

  1. Define a function, say is_present(arr, x, n), where arr is the array, x is the integer to be found, and n is the length of the array.

  2. The base case of the recursion would be when n is 0. If n is 0, it means we have traversed the entire array and did not find x. So, in this case, return False.

  3. Now, check if the last element of the array is x. If it is, return True.

  4. If the last element is not x, then call the function is_present recursively with the same array, same x, but with n-1 as the length.

  5. The function will keep checking the last element of the array and reducing the length by 1 until it either finds x or the length becomes 0.

Here is the Python code for the above steps:

def is_present(arr, x, n):
    if n == 0:
        return False
    if arr[n-1] == x:
        return True
    return is_present(arr, x, n-1)

You can call this function with your array, the integer to be found, and the length of the array. For example:

print(is_present([1, 2, 3, 4, 5], 3, 5))  # Returns: True
print(is_present([1, 2, 3, 4, 5], 6, 5))  # Returns: False

This problem has been solved

Similar Questions

Given an integer array and another integer element. The task is to find if the given element is present in array or not.

Given an array, check if there exist 2 elements of the array such that their sum is equal to the sum of the remaining elements of the array.

Given an array Arr of N positive integers. Your task is to find the elements whose value is equal to that of its index value ( Consider 1-based indexing ).

7. Write a recursive algorithm that calculates and returns the length of a list.

Select the correct answerOnly problems that are recursively defined can be solved using recursion.OptionsFalseTrue

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.