TYBBA(CA) Core Java Slip No 13 Q A

Q.Write a java program to accept ‘n’ integers from the user & store them in an ArrayList collection. Display the elements of ArrayList collection in reverse order.[15 M]

import java.util.ArrayList;
import java.util.Scanner;

public class ReverseArrayList {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> list = new ArrayList<>();

        System.out.print("Enter number of elements: ");
        int n = sc.nextInt();

        // Accept elements
        System.out.println("Enter integers:");
        for(int i = 0; i < n; i++) {
            list.add(sc.nextInt());
        }

        // Display in reverse order
        System.out.println("\nElements in reverse order:");
        for(int i = list.size() - 1; i >= 0; i--) {
            System.out.print(list.get(i) + " ");
        }

        sc.close();
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top