Java Program to Split an Array from Specified Position

This is a Java Program to Split an Array from Specified Position.

Enter size of array and then enter all the elements of that array. Now enter the position from where you want to split. We first copy the elements from first position to that given position in secnd array and remaining elements in third array.

Here is the source code of the Java Program to Split an Array from Specified Position. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. import java.util.Scanner;
  2. public class Split
  3. {
  4.     public static void main(String[] args) 
  5.     {
  6.         int n, x, flag = 1, loc = 0, k = 0,j = 0;
  7.         Scanner s = new Scanner(System.in);
  8.         System.out.print("Enter no. of elements you want in array:");
  9.         n = s.nextInt();
  10.         int a[] = new int[n];
  11.         int b[] = new int[n];
  12.         int c[] = new int[n];
  13.         System.out.println("Enter all the elements:");
  14.         for (int i = 0; i < n; i++) 
  15.         {
  16.             a[i] = s.nextInt();
  17.         }
  18.         System.out.print("Enter the position from where you want to split:");
  19.         loc = s.nextInt();
  20.         for(int i = 0; i < loc; i++)
  21.         {
  22.             b[k] = a[i];
  23.             k++;
  24.         }
  25.         for(int i = loc; i < n; i++)
  26.         {
  27.             c[j] = a[i];
  28.             j++;
  29.         }
  30.         System.out.print("First array:");
  31.         for(int i = 0;i < k; i++)
  32.         {
  33.             System.out.print(b[i]+" ");
  34.         }
  35.         System.out.println("");
  36.         System.out.print("Second array:");
  37.         for(int i = 0; i < j; i++)
  38.         {
  39.             System.out.print(c[i]+" ");
  40.         }
  41.     }
  42. }

Output:

$ javac Split.java
$ java Split
 
Enter no. of elements you want in array:8
Enter all the elements:
2
3
4
7
1
9
11
6
Enter the position from where you want to split:4
First array:2 3 4 7 
Second array:1 9 11 6

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

👉 For weekly programming practice and certification updates, join Sanfoundry’s official WhatsApp & Telegram channels
advertisement
Manish Bhojasia – Founder & CTO at Sanfoundry

I’m Manish, Founder & CTO at Sanfoundry, with 25+ years of experience across Linux systems, SAN technologies, advanced C programming, and building large-scale, performance-driven learning and certification platforms focused on clear skill validation.

LinkedIn  ·  YouTube MasterClass  ·  Telegram Classes  ·  Career Guidance & Conversations