- 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 Split the array and add the first part to the end
Following is the Java program to split the array and add the first part to the end −
Example
import java.util.*; import java.lang.*; public class Demo { public static void split_array(int my_arr[], int arr_len, int k) { for (int i = 0; i < k; i++) { int x = my_arr[0]; for (int j = 0; j < arr_len - 1; ++j) my_arr[j] = my_arr[j + 1]; my_arr[arr_len - 1] = x; } } public static void main(String[] args) { int my_arr[] = { 67, 45, 78, 90, 12, 102, 34}; int arr_len = my_arr.length; int position = 2; split_array(my_arr, 4, position); System.out.println("The array after splitting and rotating is : "); for (int i = 0; i < arr_len; ++i) System.out.print(my_arr[i] + " "); } }
Output
The array after splitting and rotating is : 78 90 67 45 12 102 34
Explanation
A class named Demo contains a function named ‘split_array’ that takes the array, the length of the array and a position as its parameters. It iterates through the array upto the position of the array, and the first element in the array is assigned to a variable. Another loop iterates though the length of the array and assigns the second element to the first element. The first element of the array is then assigned to the last position.
In the main function, the array is declared, and the length of the array is stored in a variable. The function ‘split_array’ is called by passing the array, length and a position where the array needs to be split. The resultant output is displayed by iterating over the array.