# Python Program: Check Monotonic Array

In this blog post, we’ll explore a Python program that checks whether a given array is monotonic or not. A monotonic array is one that is entirely non-increasing or non-decreasing. The program takes an array as input, performs the necessary checks, and outputs whether the array is monotonic or not. We’ll provide a step-by-step explanation of the algorithm, showcase the Python code, and include examples with corresponding outputs.

## Understanding the Algorithm

The algorithm to determine if an array is monotonic involves iterating through the array elements and checking whether the array is strictly increasing, strictly decreasing, or both. Here are the key steps:

1. Input Array: Receive an array as input to be checked for monotonicity.

2. Check Monotonicity: Iterate through the array to determine if it is non-increasing, non-decreasing, or neither.

3. Output Result: Display whether the array is monotonic or not based on the checks.

## Python Program for Checking Monotonic Array

Let’s implement the algorithm in a Python program:

``````def is_monotonic(arr):
increasing = decreasing = True

# Iterate through the array
for i in range(1, len(arr)):
# Check for increasing order
if arr[i] > arr[i - 1]:
decreasing = False
# Check for decreasing order
elif arr[i] < arr[i - 1]:
increasing = False

# Return the result
return increasing or decreasing

# Input array
array_input = list(map(int, input("Enter the array elements separated by space: ").split()))

# Check if the array is monotonic
result = is_monotonic(array_input)

# Output result
if result:
print("The given array is monotonic.")
else:
print("The given array is not monotonic.")
``````

## Output Example

### Example: Checking Monotonic Array

Let’s input an array such as `4 3 2 1`:

#### Input

``````Enter the array elements separated by space: 4 3 2 1
``````

#### Output

``````The given array is monotonic.
``````

## Explanation

The program defines a function `is_monotonic` that takes an array as input and checks for monotonicity. It uses two flags, `increasing` and `decreasing`, to determine whether the array is strictly increasing, strictly decreasing, or neither.

## Conclusion

This Python program demonstrates how to check if a given array is monotonic. Understanding the monotonicity of an array is useful in various scenarios, especially in algorithms and data analysis. You can further modify and extend this program to suit your specific requirements.

Feel free to experiment with different arrays and test the program with various inputs. If you have any questions or want to explore more Python programming topics, feel free to ask!