Replace Negatives with 0

Replace all negative elements with 0.

Logic BuildingIntermediate
Logic Building
# Take array
n = int(input("Enter array size: "))
arr = []
for i in range(n):
    arr.append(int(input(f"Element {i+1}: ")))

# Replace negatives
for i in range(len(arr)):
    if arr[i] < 0:
        arr[i] = 0

print(f"Modified array: {arr}")

Output

Enter array size: 5
Element 1: 5
Element 2: -3
Element 3: 10
Element 4: -2
Element 5: 7
Modified array: [5, 0, 10, 0, 7]

Modify array in-place.

Key Concepts:

  • Check each element
  • Replace if negative
  • In-place modification