Ask Question

Write a function called nth that finds the n-th occurrence of a particular value in an array of integers. The first argument is an integer array. The second argument is the length (size) of the array (i. e., the number of integers). The third argument is the value you want to match (an integer). The fourth argument is n, the particular match you want to find. In other words, n

+1
Answers (1)
  1. 30 April, 17:03
    0
    def nth (arr, length, match, n) : count = 0 for i in range (0, length) : if (arr[i] = = match) : count + = 1 if (count = = n) : return i myArr = [2, 3, 4, 3, 5, 6, 7, 3, 5, 8, 9] print (nth (myArr, 10, 5, 2))

    Explanation:

    The solution code is written in Python 3.

    Firstly, create a function and name it as nth that takes four inputs, arr, length, match and n as required by the question (Line 1).

    Next create a counter variable count (Line 2). This is used to track the current number of occurrence of the match in the list.

    Create a for loop to iterate through each number in the array and if any element is equal to the match, increment the count by one (Line 3 - 5)

    In the same loop, create another if statement to check if the current count number is equal to input n. If so return the current i index (Line 7-8).

    At last, test the function using a sample list (Line 10) and print the return output. We shall get 8 because the nth occurrence of 5 is positioned in index-8 of the list (Line 11).
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write a function called nth that finds the n-th occurrence of a particular value in an array of integers. The first argument is an integer ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers