- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to reverse an array upto a given position
An array can be reversed upto the given position pos and the remaining array is unchanged. An example of this is given as follows −
Array = 1 2 3 4 5 6 7 8 9 10 Position = 6 Modified array = 6 5 4 3 2 1 7 8 9 10
A program that demonstrates this is given as follows −
Example
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( "
Modified 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
Now let us understand the above program.
If the position is greater than the length of the array, then this is an error and that is printed. Otherwise, first the original array is printed. The code snippet that demonstrates this is given as follows −
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] + " ");
Now a for loop is used to reverse the array till pos. Then the modified array is displayed. The code snippet that demonstrates this is given as follows −
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( "
Modified array is: "); for (int i = 0; i < n; ++i) System.out.print(arr[i] + " ");
Advertisements