Logic Building
# Take array
n = int(input("Enter array size: "))
arr = []
for i in range(n):
arr.append(int(input(f"Element {i+1}: ")))
x = int(input("Enter element to find: "))
# Find last occurrence
last_index = -1
for i in range(len(arr)):
if arr[i] == x:
last_index = i
if last_index != -1:
print(f"Last occurrence at index: {last_index}")
else:
print("Element not found")Output
Enter array size: 5 Element 1: 10 Element 2: 20 Element 3: 30 Element 4: 20 Element 5: 40 Enter element to find: 20 Last occurrence at index: 3
Iterate and track last matching index.
Key Concepts:
- Loop through array
- Update last_index when found
- Track last occurrence