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.
Solution
Here is a step-by-step solution in Python:
-
Define a function, say
is_present(arr, x, n)
, wherearr
is the array,x
is the integer to be found, andn
is the length of the array. -
The base case of the recursion would be when
n
is 0. Ifn
is 0, it means we have traversed the entire array and did not findx
. So, in this case, returnFalse
. -
Now, check if the last element of the array is
x
. If it is, returnTrue
. -
If the last element is not
x
, then call the functionis_present
recursively with the same array, samex
, but withn-1
as the length. -
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
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
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.