Java Program to Split the array and add the first part to the end

Java 8Server Side ProgrammingProgramming

Following is the Java program to split the array and add the first part to the end −

Example

 Live Demo

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.

raja
Published on 14-Sep-2020 08:33:18
Advertisements