
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reverse an Array Up to a Given Position in Java
In this article, we will reverse the elements of an array up to a specified position using Java. You will learn how the program takes an array, reverses the first part of it up to a given index, and prints the modified array. An array can be reversed upto the given position pos and the remaining array is unchanged.
Problem Statement
Write a Java program to reverse an array upto a given position.
Input
Array = 1 2 3 4 5 6 7 8 9 10 Position = 6
Output
Modified array is: 6 5 4 3 2 1 7 8 9 10
Steps to reverse an array upto a given position
Following are the steps to reverse an array upto a given position ?
- Declare an int[] array with predefined values.
- Set the position (pos) up to which the array will be reversed.
- Check if the pos is valid using an if statement.
- Print the initial array with a for loop.
- Reverse the array up to pos using a for loop and swap elements.
- Print the modified array with another for loop.
Java program to reverse an array upto a given position
A program that demonstrates this is given as follows ?
public class Example { public static void main(String args[]) { int[] arr = {1, 2, 3, 4, 5, 6, 7 ,8 ,9, 10}; int n = arr.length; int pos = 6; int temp; if (pos > n) { System.out.println( "Invalid...pos cannot be greater than n"); return; } System.out.print( "Initial array is: "); for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); for (int i = 0; i < pos / 2; i++) { temp = arr[i]; arr[i] = arr[pos - i - 1]; arr[pos - i - 1] = temp; } System.out.print( "\nModified array is: "); for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); } }
Output
Initial array is: 1 2 3 4 5 6 7 8 9 10 Modified array is: 6 5 4 3 2 1 7 8 9 10
Code Explanation
The above program starts by initializing an array of integers and a position pos to indicate where the array should be reversed. It checks if the position is valid, if pos is greater than the length of the array, it prints an error message and exits. The array is then reversed up to the given position using a loop that swaps elements from both ends of the section to be reversed. Finally, the modified array is printed.