
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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( "\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
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( "\nModified array is: "); for (int i = 0; i < n; ++i) System.out.print(arr[i] + " ");
- Related Questions & Answers
- Python program to reverse an array up to a given position
- Program to reverse an array up to a given position in Python
- Java program to reverse an array
- Java program to reverse an array in groups of given size
- Java Program to reverse a given String with preserving the position of space.
- C# program to reverse an array
- Python program to reverse an array in groups of given size?
- Write a Golang program to reverse an array
- C program to reverse an array elements
- Program to reverse the position of each word of a given string in Python
- Write a program to reverse an array in JavaScript?
- Java Program to Check if An Array Contains a Given Value
- Golang Program to reverse a given linked list.
- Write a program to reverse an array or string in C++
- Java Program to Reverse a Number
Advertisements