Nth From The End
September 11, 2018
Counting from the end of the list, the third-last item in the list (1 2 3 4 5 6 7 8 9) is 7.
Your task is to write a program to find the nth-last item in a list; you must provide at least three fundamentally different solutions. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
A Haskell version. “Fundamentally different” is in the eye of the beholder…
Here’s a solution in C. n is zero-indexed. It doesn’t handle invalid inputs (e.g., setting n=5 for a list with three elements).
Example output:
I know only one.
b= [10,9,8,7,6,5,4,3,2,1,0]
index = 7
print b[len(b) – (index+1)]