Logic Building
# Take array
n = int(input("Enter array size: "))
arr = []
for i in range(n):
arr.append(int(input(f"Element {i+1}: ")))
# Find second largest
if n < 2:
print("Array too small")
else:
# Find max
max_val = max(arr)
# Find second max
second_max = None
for element in arr:
if element != max_val:
if second_max is None or element > second_max:
second_max = element
if second_max is None:
print("All elements are same")
else:
print(f"Second largest: {second_max}")Output
Enter array size: 5 Element 1: 10 Element 2: 5 Element 3: 20 Element 4: 15 Element 5: 20 Second largest: 15
Find max first, then find largest that's not max.
Key Concepts:
- First find maximum
- Then find largest excluding max
- Handle case where all same