Java Program To Reverse A String Array | AskTheCode

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:

  1. Displaying the elements in reversed order

  2. 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;
	}
}

13 views0 comments

Recent Posts

See All

Golf CodeChef Solution in Java - AskTheCode

CodeChef May Long Challenge Solution | Golf (LKDNGOLF) solution | AskTheCode Golf (LKDNGOLF) solution Problem: It's a lockdown. You’re bored in your house and are playing golf in the hallway. The hall

Solubility - CodeChef Solution in Java and C++| AskTheCode

CodeChef May Long Challenge Solution | Solubility (SOLBLTY) solution | AskTheCode Solubility (SOLBLTY) solution Problem: Suppose for a unit rise in temperature, the solubility of sugar in water increa

Valid Paths CodeChef Solution in C++ | AskTheCode

CodeChef May Long Challenge Solution | Valid Paths (VPATH) solution | AskTheCode Valid Paths (VPATH) CodeChef solution Problem: You are given a tree with N nodes numbered from 1 to N. A set S of nodes