Starter Tutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.
Home » Programming » Java » Programs » Arrays » Java program to reverse the array inplace
Suryateja Pericherla Categories: Arrays. 2 Comments on Java program to reverse the array inplace
Join Our Newsletter - Tips, Contests and Other Updates
Email
Name

In this article we will learn to implement a Java program to reverse the array. A Java program is provided below which reverses an array in-place (without using extra memory).

 

Following program reads an array of elements and reverses the array in place i.e., without using any temporary array:

import java.util.Scanner;

public class Driver
{	
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.println("Enter the no. of elements: ");
		int n = input.nextInt();
		int a[] = new int[n];
		System.out.println("Enter " + n + " numbers:");
		for(int i = 0; i < n; i++)
			a[i] = input.nextInt();
		for(int i = 0, j = n - 1; i < j; i++, j--)
		{
			int temp = a[i];
			a[i] = a[j];
			a[j] = temp;
		}
		System.out.print("Reversed array is: ");
		for(int i = 0; i < n; i++)
			System.out.print(a[i] + " ");
		input.close();
	}
}

 

Input and output for the above program are as follows:

Enter the no. of elements: 
5
Enter 5 numbers:
1 2 3 4 5
Reversed array is: 5 4 3 2 1

 

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

2 Comments

You can follow any responses to this entry through the RSS 2.0 feed.

Plz solve it
W. A. J. P. To print the value of 1/1+1/2+1/3+1/4+…….1/n

    int s=0;
    for (int i=0;i <=n;i++)
    {
    c=c+(1/i);
    }

Leave a Reply

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

Facebook
Twitter
Pinterest
Youtube
Instagram
Blogarama - Blog Directory