Google Add

Search

Java Program to Reverse an Array - Iterative Approach

Write a java program to reverse an array. Given an input array, we have to write a code to reverse an array. In this tutorial, I'll show how to solve this problem using iterative approach.

In my previous tutorials, i have written C, C++ code to reverse an array.

C, C++ program to reverse an array using recursion

C, C++ program to reverse an array using iterative approach

Java programming questions for practice




Java Program to Reverse an Array

import java.util.*;

public class IterativeReverse {

    public static void main(String[] args) {
        
        Scanner in = new Scanner(System.in);
        
        System.out.println("Enter the size of an array");
        int n = in.nextInt();
        
        //Declare an array
        int arr[] =  new int[n];
        
        System.out.println("Enter an array values");
        
        //Input array values
        for(int i = 0; i < n; i++) {
            arr[i] = in.nextInt();
        }
        
        int temp;
        
        int start = 0;
        int end   = n-1;
        
        //Logic to reverse an array
        while (start < end) {
            temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            
            start++;
            end--;
        }
        
        System.out.println("Printing an array after reverse");
        
        for(int j = 0; j < n; j++) {
            System.out.println(arr[j]);
        }
  
    }
    
}


Video Tutorial to Reverse an Array in Java




No comments:

Post a Comment