Free Response Practice Question (with solution)- Increasing Order Array


<-- Back to Even Number Array Next to Integer Array -->





Increasing Order Array


Write a Java program that reads numbers (in increasing order) from the user and stores them in an array. The array stores numbers only in the increasing order. Every next number entered by the user should be higher than the previously entered number. If that is not the case, then an appropriate message is displayed and the user is asked to enter more numbers in increasing order. Once 10 numbers are stored in the array, the program should display all the numbers.


Solution:


import java.util.InputMismatchException;
import java.util.Scanner;

public class IncreasingOrderArray {

    public static void main(String[] args)
    {
        int SIZE =10;
        int[] increasingArr = new int[SIZE];
        int i=0;
        try (Scanner input = new Scanner(System.in)) {
            int number;
            char choice;
            do
            {
                System.out.print("Enter a number (all numbers should be in increasing order): ");
                number = input.nextInt();
            
                if (i>0) 
                {
                    if (increasingArr[i-1] < number)
                    {
                        increasingArr[i] = number;
                        i++;
                    }
                    else 
                    {
                        System.out.println("You must enter a number greater than the previous number("+ increasingArr[i-1]+")");
                        System.out.println("There are still "+ (SIZE -i) + " numbers to be entered");
                    }
                }
                else { // first number is entered
                    increasingArr[i] = number;
                    i++;
                }
                
                System.out.print("Do you want to continue y/n? ");
                choice = input.next().charAt(0);
                
            }while ((choice=='y' || choice == 'Y') && (i< SIZE));
                

        System.out.println("There are currently "+ i + " numbers in the array");
        
        for (int k=0; k < i; k++)
        {
            System.out.print(increasingArr[k]+ " ");
        }
        }
    
    catch (InputMismatchException  e)
    {
        System.out.println("Error reading input");
    }

}
}



Java project file:


<-- Back to Even Number Array Next to Integer Array -->