Array: Reverse the numbers entered

Question: Write a program that reads 10 integers then displays them in the reverse of the order in which they were read.

Example:

Enter array size
5
Enter element 1:
2
Enter element 2:
1
Enter element 3:
5
Enter element 4:
6
Enter element 5:
7


Output: 7 6 5 1 2

package Array;

import java.util.Scanner;

/**
 * Write a program that reads 10 integers then displays them in the reverse of the order in which they were read.
 * Created by aarushi on 8/5/21.
 */

/*
    Step 1: Ask user to enter array size
    Step 2: Create array with size user has entered
    Step 3: Create a method which asks the user for array values
    Step 4: Create method that displays the array
        Step 4.1: Start the loop for length-1 till 0
 */
public class Ch7Ex2 {

    public static void main (String [] args){
        Scanner sc= new Scanner(System.in);
        int arrayLength;

      	//Ask user to enter array size
        System.out.println("Enter array size");
        arrayLength= sc.nextInt();

      	//Create array with size user has entered
        int [] array= new int[arrayLength];

        inputArray(array, arrayLength);
        displayArray(array, arrayLength);
    }

  	//Create a method which asks the user for array values
    public static void inputArray (int [] array, int arrayLength){
        Scanner sc= new Scanner (System.in);
        for (int i=0 ; i<arrayLength; i++){
            System.out.println("Enter element " + (i+1) + ": ");
            array[i]= sc.nextInt();
        }
    }

  	//Create method that displays the array
    public static void displayArray (int [] array, int arrayLength){
      	//Start the loop for length-1 till 0
        for (int i=(arrayLength-1); i>=0; i--){
            System.out.print(array[i]+ " ");
        }
    }
}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: