Reverse a user given string array in java | Problem Solving in Java | AskTheCode
Problem:
Reverse the order of elements of an Array. Use the Array provided below. The Array, as the name suggest, contains different fruit names. The aim is to print the elements of the array in reversed order.
Sample input:
Strawberry Blueberry Watermelon Peach Apple Banana Orange
Sample output:
Orange Banana Apple Peach Watermelon Blueberry Strawberry
Implementation:
These types of problems could be done in two ways:
Displaying the elements in reversed order
Reversing the elements of the array
Now, let's check first how to display a string array in reversed order
Code:
import java.util.Scanner;
public class Rev_Array{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
String[] arr = new String[a];
for (int i = 0; i < a; i++) {
arr[i] = sc.nextLine();
}
for (int i = a - 1; i >= 0; i--) {
System.out.println(arr[i]);
}
}
}
The second way is to actual store the elements of the array in reversed order.
Code:
import java.io.*;
public class Rev_ArrayValue{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the size of the array: ");
int n = Integer.parseInt(br.readLine());
String array[] = new String[n];
System.out.println("Enter the elements: ");
for (int i = 0; i < n; i++) {
array[i] = br.readLine();
}
System.out.println("Current elements in the array:");
printArray(array);
array = revArray(array);
System.out.println("After reversing, elements in the array:");
printArray(array);
}
static void printArray(String[] arr){
for (String i : arr) {
System.out.print(i+" ");
}
System.out.println();
}
static String[] revArray(String[] arr){
String temp[] = new String[arr.length];
for (int i = 0; i < arr.length; i++) {
temp[i] = arr[arr.length-1-i];
}
return temp;
}
}
Comments