This is the Java Program to Check if an Array is Strictly Decreasing.
Given an array of integers check whether it is strictly decreasing or not.
A strictly decreasing array is an array whose each element is smaller than it’s preceding element.
Example:
Array = [5, 4, 3, 2, 1]
Output: Array is strictly decreasing.
Iterate through the array and check whether the current array element, is smaller than its preceding element if all the elements are smaller than its preceding element return true, else return false.
Here is the source code of the Java Program to Check if an Array is Strictly Decreasing. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
//Java Program to Check if an Array is Strictly Decreasing
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class StrictlyDecreasing {
// Function to check array is strictly decreasing
static boolean checkStrictlyDecreasing(int[] array){
boolean result=true;
int i;
for(i=0;i<array.length-1;i++){
if(array[i]<=array[i+1])
{
result=false;
break;
}
}
return result;
}
// Function to read input and decreasing output
public static void main(String[] args) {
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int size;
System.out.println("Enter the size of the array");
try{
size=Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println("Invalid Input");
return;
}
int[] array=new int[size];
System.out.println("Enter array elements");
int i;
for(i=0;i<array.length;i++){
try{
array[i]=Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println("An error occurred");
}
}
boolean result=checkStrictlyDecreasing(array);
if(result){
System.out.println("Array is strictly decreasing");
}
else{
System.out.println("Array is not strictly decreasing");
}
}
}
1. In function checkStrictlyDecreasing(), the loop for(i=0; i<array.length; i++) is used to iterate through the array.
2. The condition if(array[i] <= array[i+1]) checks if the current element is smaller than its following element.
3. If the condition is true, flag is set to false, indicating that the array is not strictly decreasing.
4. Finally, the flag variable is returned.
Time Complexity: O(n) where n is the number of elements in the array.
Case 1 (Positive Test Case): Enter the size of the array 5 Enter array elements 5 4 3 2 1 Array is strictly decreasing Case 2 (Negative Test Case): Enter the size of the array 8 Enter array elements 6 5 5 4 3 2 1 1 Array is not strictly decreasing
Sanfoundry Global Education & Learning Series – Java Programs.
- Check Java Books
- Practice BCA MCQs
- Practice Programming MCQs
- Apply for Java Internship
- Apply for Computer Science Internship