This is the Java Program to Check if an Array is Strictly Increasing.
Given an array of integers check whether it is strictly increasing or not.
A strictly increasing array is an array whose each element is greater than it’s preceding element.
Example:
Array = [1, 2, 3, 4, 5]
Output: Array is strictly increasing.
Iterate through the array and check whether the current array element is greater than its preceding element. If all the elements are greater 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 Increasing. 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 Increasing
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class StrictlyIncreasing {
// Function to check array is strictly increasing or not.
static boolean checkStrictlyIncreasing(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 the user input
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");
return;
}
}
boolean result=checkStrictlyIncreasing(array);
if(result){
System.out.println("Array is strictly increasing");
}
else{
System.out.println("Array is not strictly increasing");
}
}
}
1. In function checkStrictlyIncreasing(), the loop for(i=0; i<array.length-1; i++) checks whether each array element is greater than the element following it, through the condition if(array[i] >= array[i+1]).
2. Any element that fulfils this condition, implies that the array is not strictly increasing, and it sets the result to false and breaks from the loop.
3. Finally, the boolean variable result is returned as the answer.
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 1 2 3 4 5 Array is strictly increasing Case 2 (Negative Test Case): Enter the size of the array 8 Enter array elements 1 2 2 3 4 5 6 6 Array is not strictly increasing Case 3 (Positive Test Case - another example): Enter the size of the array 7 Enter array elements 12 24 45 56 678 890 980 Array is strictly increasing
Sanfoundry Global Education & Learning Series – Java Programs.
- Practice Programming MCQs
- Apply for Java Internship
- Check Programming Books
- Practice Information Technology MCQs
- Practice BCA MCQs